@42px/matrix-effector 中文文档教程

发布于 3年前 浏览 27 项目主页 更新于 3年前

Data Access Layer for matrix-js-sdk

DAL 的这个实现使用效应器状态管理器。

Installation

1.4.0 version is unstable, please avoid it

npm install @42px/matrix-effector

Usage

import { IndexedDBStore } from 'matrix-js-sdk'
import {
  initStoreFx,
  loginByPasswordFx,
  prependClientParams,
  onInitialSync,
  newMessagesLoaded,
  initTimelineWindowFx,
  $currentRoomId, // Use these stores in your view
  $messages,
  initRoom,
  onRoomInitialized,
  loadRoom,
  paginateForward,
  paginateBackward,
  searchRoomMessagesFx,
  loadTimelineWindowFx,
  onCachedState,
  getRoomsWithActivitiesFx,
  createOnSyncThrottled,
  checkEventPermissionsFx,
  getUrlPreviewFx
} from '@42px/matrix-effector'
import { forward, guard, sample } from 'effector'
import {
  initApp,
  onLoadMoreBack,
  onLoadMoreFront,
  onSearch,
  onSearchInput,
  onSearchResultSelect,
  roomSelected,
} from './events'
import {
  $rooms,
  $searchInput,
  $searchResults,
  $currentUser,
} from './state'

const chatWindowSize = 20

$rooms.on(getRoomsWithActivitiesFx.doneData, (_, value) => value)
$searchInput.on(onSearchInput, (_, value) => value)
$searchResults.on(searchRoomMessagesFx.doneData, (_, messages) => messages)
$currentUser.on(getLoggedUserFx.doneData, (_, user) => user)

const store: IndexedDBStore = new IndexedDBStore({
  indexedDB: window.indexedDB,
  dbName: 'zuggat-cache',
})
prependClientParams({
  baseUrl: process.env.MATRIX_BASE_URL,
  store,
  timelineSupport: true,
  unstableClientRelationAggregation: true,
})

forward({
  from: initApp,
  to: initStoreFx,
})
forward({
  from: initStoreFx.done.map(() => ({
    user: 'username',
    password: 'password',
  })),
  to: loginByPasswordFx,
})
forward({
  from: loginByPasswordFx.done,
  to: getLoggedUserFx,
})
// new messages event (live timeline)
newMessagesLoaded.watch((messages) => console.log(messages))

// on back pagination complete
onPaginateBackwardDone.watch(() => console.log('paginated back in history'))

// explicit triger to load live timeline (for example: to get to the end of history)
toLiveTimeline()

liveTimelineLoaded.watch(() => console.log('room live timeline loaded'))

// events to go to message in current room
loadRoomMessage({ initialEventId: 'messageId' })

loadRoomMessageDone.watch(() => console.log('loaded timeline around message'))

// To select current room trigger initRoom - it will also create a TimelineWindow instance for it
forward({
  from: roomSelected.map((roomId) => { roomId }),
  to: initRoom,
})
forward({
  from: onRoomInitialized,
  to: loadRoom,
})
guard({
  source: sample(
    [$searchInput, $currentRoomId],
    onSearch,
    (([term, roomId]) => ({ term, roomId, orderBy: 'recent' })),
  ),
  filter: combine($currentRoomId, $searchInput, (roomId, term) => Boolean(roomId) && Boolean(term)),
  target: searchRoomMessagesFx,
})
guard({
  source: onSearchResultSelect.map((eventId) => ({
    initialEventId: eventId,
    initialWindowSize: chatWindowSize,
  })),
  filter: $currentRoomId.map((roomId) => Boolean(roomId)),
  target: loadRoom,
})
guard({
  source: onLoadMoreBack.map(() => ({ size: 10 })),
  filter: $currentRoomId.map((roomId) => Boolean(roomId)),
  target: paginateBackward,
})
guard({
  source: onLoadMoreFront.map(() => ({ size: 10 })),
  filter: $currentRoomId.map((roomId) => Boolean(roomId)),
  target: paginateForward,
})
const onSyncThrottled = createOnSyncThrottled(500)
forward({
  from: [onCachedState, onInitialSync, onSyncThrottled],
  to: getRoomsWithActivitiesFx,
})
guard({
  source: sample(
    $currentRoomId,
    $selectedMessage.updates,
    (roomId, messageId) => ({
      roomId: roomId as string,
      eventId: messageId as string,
    }),
  ),
  filter: combine(
    $hasRoom,
    $selectedMessage,
    (hasRoom, messageId) => hasRoom && Boolean(messageId),
  ),
  target: checkEventPermissionsFx,
})
checkEventPermissionsFx.doneData.watch(({ canRedact, canEdit }) => console.log(canRedact, canEdit))

Utils

get RoomMember Avatar url / Room Avatar Url

import { getRoomMemberAvatarUrl, getSenderAvatarUrl, Message } from '@42px/matrix-effector'

...

 const dialogAvatar = getRoomMemberAvatarUrl({
  roomId: item.roomId,
  userId: item.directUserId,
  width: 40,
  height: 40,
  resizeMethod: 'crop',
})

const avatarUrl = getSenderAvatarUrl({
  sender: message.sender,
  width: 40,
  height: 40,
  resizeMethod: 'crop',
})

API Reference

Store

$messages

const $messages = store<Message>()

Store 提供对已打开房间中消息的访问权限

$currentRoomId

const $currentRoomId = store<RoomWithActivity["roomId"] | null>(null)

Store 提供对已打开房间中 roomId 的访问权限

$currentRoom

const $currentRoom = store<RoomWithActivity | null>(null)

Store 提供对已打开房间的访问权限

$currentRoomMembers

const $currentRoomMembers = store<MappedRoomMember[] | null>(null)

Store 包含所选房间

Events

onRoomMemberUpdate

const onRoomMemberUpdate = event<RoomMember>()

的成员 当邀请新成员时发生事件,成员进入房间,开始输入,更改他的名称,成员的功率级别发生变化。

onRoomLoaded

const onRoomLoaded = event<void>()

当房间初始化并且消息加载到 $messages 时事件发出。

roomCreated

const roomCreated = event<Room>()

当您被邀请到一个新房间时,事件就会发出。

const directRoomCreated = event<Room>()

当您被邀请到一个新的直接房间时,事件就会发出。

新房间出现在矩阵“房间”事件中。

Effects

createDirectRoomFx

const createDirectRoomFx = effect<CreateDirectRoomParams, { roomId: string }, Error>()

创建具有私人可见性的直接房间并设置您的 m.direct 帐户数据

Data Access Layer for matrix-js-sdk

This implementation of DAL uses the effector state manager.

Installation

1.4.0 version is unstable, please avoid it

npm install @42px/matrix-effector

Usage

import { IndexedDBStore } from 'matrix-js-sdk'
import {
  initStoreFx,
  loginByPasswordFx,
  prependClientParams,
  onInitialSync,
  newMessagesLoaded,
  initTimelineWindowFx,
  $currentRoomId, // Use these stores in your view
  $messages,
  initRoom,
  onRoomInitialized,
  loadRoom,
  paginateForward,
  paginateBackward,
  searchRoomMessagesFx,
  loadTimelineWindowFx,
  onCachedState,
  getRoomsWithActivitiesFx,
  createOnSyncThrottled,
  checkEventPermissionsFx,
  getUrlPreviewFx
} from '@42px/matrix-effector'
import { forward, guard, sample } from 'effector'
import {
  initApp,
  onLoadMoreBack,
  onLoadMoreFront,
  onSearch,
  onSearchInput,
  onSearchResultSelect,
  roomSelected,
} from './events'
import {
  $rooms,
  $searchInput,
  $searchResults,
  $currentUser,
} from './state'

const chatWindowSize = 20

$rooms.on(getRoomsWithActivitiesFx.doneData, (_, value) => value)
$searchInput.on(onSearchInput, (_, value) => value)
$searchResults.on(searchRoomMessagesFx.doneData, (_, messages) => messages)
$currentUser.on(getLoggedUserFx.doneData, (_, user) => user)

const store: IndexedDBStore = new IndexedDBStore({
  indexedDB: window.indexedDB,
  dbName: 'zuggat-cache',
})
prependClientParams({
  baseUrl: process.env.MATRIX_BASE_URL,
  store,
  timelineSupport: true,
  unstableClientRelationAggregation: true,
})

forward({
  from: initApp,
  to: initStoreFx,
})
forward({
  from: initStoreFx.done.map(() => ({
    user: 'username',
    password: 'password',
  })),
  to: loginByPasswordFx,
})
forward({
  from: loginByPasswordFx.done,
  to: getLoggedUserFx,
})
// new messages event (live timeline)
newMessagesLoaded.watch((messages) => console.log(messages))

// on back pagination complete
onPaginateBackwardDone.watch(() => console.log('paginated back in history'))

// explicit triger to load live timeline (for example: to get to the end of history)
toLiveTimeline()

liveTimelineLoaded.watch(() => console.log('room live timeline loaded'))

// events to go to message in current room
loadRoomMessage({ initialEventId: 'messageId' })

loadRoomMessageDone.watch(() => console.log('loaded timeline around message'))

// To select current room trigger initRoom - it will also create a TimelineWindow instance for it
forward({
  from: roomSelected.map((roomId) => { roomId }),
  to: initRoom,
})
forward({
  from: onRoomInitialized,
  to: loadRoom,
})
guard({
  source: sample(
    [$searchInput, $currentRoomId],
    onSearch,
    (([term, roomId]) => ({ term, roomId, orderBy: 'recent' })),
  ),
  filter: combine($currentRoomId, $searchInput, (roomId, term) => Boolean(roomId) && Boolean(term)),
  target: searchRoomMessagesFx,
})
guard({
  source: onSearchResultSelect.map((eventId) => ({
    initialEventId: eventId,
    initialWindowSize: chatWindowSize,
  })),
  filter: $currentRoomId.map((roomId) => Boolean(roomId)),
  target: loadRoom,
})
guard({
  source: onLoadMoreBack.map(() => ({ size: 10 })),
  filter: $currentRoomId.map((roomId) => Boolean(roomId)),
  target: paginateBackward,
})
guard({
  source: onLoadMoreFront.map(() => ({ size: 10 })),
  filter: $currentRoomId.map((roomId) => Boolean(roomId)),
  target: paginateForward,
})
const onSyncThrottled = createOnSyncThrottled(500)
forward({
  from: [onCachedState, onInitialSync, onSyncThrottled],
  to: getRoomsWithActivitiesFx,
})
guard({
  source: sample(
    $currentRoomId,
    $selectedMessage.updates,
    (roomId, messageId) => ({
      roomId: roomId as string,
      eventId: messageId as string,
    }),
  ),
  filter: combine(
    $hasRoom,
    $selectedMessage,
    (hasRoom, messageId) => hasRoom && Boolean(messageId),
  ),
  target: checkEventPermissionsFx,
})
checkEventPermissionsFx.doneData.watch(({ canRedact, canEdit }) => console.log(canRedact, canEdit))

Utils

get RoomMember Avatar url / Room Avatar Url

import { getRoomMemberAvatarUrl, getSenderAvatarUrl, Message } from '@42px/matrix-effector'

...

 const dialogAvatar = getRoomMemberAvatarUrl({
  roomId: item.roomId,
  userId: item.directUserId,
  width: 40,
  height: 40,
  resizeMethod: 'crop',
})

const avatarUrl = getSenderAvatarUrl({
  sender: message.sender,
  width: 40,
  height: 40,
  resizeMethod: 'crop',
})

API Reference

Store

$messages

const $messages = store<Message>()

Store provides access to messages in opened room

$currentRoomId

const $currentRoomId = store<RoomWithActivity["roomId"] | null>(null)

Store provides access to roomId in opened room

$currentRoom

const $currentRoom = store<RoomWithActivity | null>(null)

Store provides access to opened room

$currentRoomMembers

const $currentRoomMembers = store<MappedRoomMember[] | null>(null)

Store contains members of the selected room

Events

onRoomMemberUpdate

const onRoomMemberUpdate = event<RoomMember>()

The event occurs when a new member is invited, the member enters the room, starts typing, changes his name, the member's power level changes.

onRoomLoaded

const onRoomLoaded = event<void>()

Event emmits when room initialized and messages loaded in $messages.

roomCreated

const roomCreated = event<Room>()

Event emmits when you are invited to a new room.

const directRoomCreated = event<Room>()

Event emmits when you are invited to a new direct room.

New rooms come in the matrix "Room" event.

Effects

createDirectRoomFx

const createDirectRoomFx = effect<CreateDirectRoomParams, { roomId: string }, Error>()

Creates a direct room with private visibility and set yur m.direct account data

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文