blowater/app/UI/app.tsx

560 lines
19 KiB
TypeScript
Raw Normal View History

2023-06-30 14:05:57 +00:00
/** @jsx h */
import { h, render, VNode } from "https://esm.sh/preact@10.17.1";
2024-01-01 17:28:10 +00:00
import { Channel } from "https://raw.githubusercontent.com/BlowaterNostr/csp/master/csp.ts";
import { PublicKey } from "../../libs/nostr.ts/key.ts";
import { NostrAccountContext, NostrEvent, NostrKind } from "../../libs/nostr.ts/nostr.ts";
import { ConnectionPool } from "../../libs/nostr.ts/relay-pool.ts";
import { Database_View } from "../database.ts";
2024-01-01 17:28:10 +00:00
import { EventBus } from "../event-bus.ts";
import { DirectedMessageController, getAllEncryptedMessagesOf, InvalidEvent } from "../features/dm.ts";
import { About } from "./about.tsx";
2023-06-30 14:05:57 +00:00
import { initialModel, Model } from "./app_model.ts";
import { AppEventBus, Database_Update, UI_Interaction_Event, UI_Interaction_Update } from "./app_update.tsx";
import { Popover, PopOverInputChannel } from "./components/popover.tsx";
import { OtherConfig } from "./config-other.ts";
2024-01-01 17:28:10 +00:00
import { DM_List } from "./conversation-list.ts";
import { DexieDatabase } from "./dexie-db.ts";
import { DirectMessageContainer } from "./dm.tsx";
import { EditProfile } from "./edit-profile.tsx";
import { RelayConfig } from "./relay-config.ts";
2023-10-07 20:40:18 +00:00
import { ProfileGetter } from "./search.tsx";
2024-01-01 17:28:10 +00:00
import { Setting } from "./setting.tsx";
import { getCurrentSignInCtx, getSignInState, setSignInState } from "./sign-in.ts";
2024-01-01 17:28:10 +00:00
import { SecondaryBackgroundColor } from "./style/colors.ts";
2023-11-18 17:11:07 +00:00
import { LamportTime } from "../time.ts";
2024-01-01 17:28:10 +00:00
import { InstallPrompt, NavBar } from "./nav.tsx";
import { Component } from "https://esm.sh/preact@10.17.1";
import { SingleRelayConnection } from "../../libs/nostr.ts/relay-single.ts";
import { ChannelContainer } from "./channel-container.tsx";
import { ChatMessage } from "./message.ts";
import { filter, map } from "./_helper.ts";
import { RightPanel } from "./components/right-panel.tsx";
import { ComponentChildren } from "https://esm.sh/preact@10.17.1";
import { SignIn } from "./sign-in.tsx";
import { getTags, Parsed_Event } from "../nostr.ts";
2024-03-15 14:30:58 +00:00
import { Toast } from "./components/toast.tsx";
import { ToastChannel } from "./components/toast.tsx";
2023-07-09 07:06:13 +00:00
2023-07-11 09:49:58 +00:00
export async function Start(database: DexieDatabase) {
console.log("Start the application");
2024-01-01 17:28:10 +00:00
const installPrompt: InstallPrompt = {
2023-11-27 13:35:01 +00:00
event: undefined,
};
window.addEventListener("beforeinstallprompt", async (event) => {
event.preventDefault();
installPrompt.event = event;
});
2023-11-25 14:29:50 +00:00
const lamport = new LamportTime();
const model = initialModel();
const eventBus = new EventBus<UI_Interaction_Event>();
const pool = new ConnectionPool();
const popOverInputChan: PopOverInputChannel = new Channel();
const rightPanelInputChan: Channel<() => ComponentChildren> = new Channel();
const toastInputChan: ToastChannel = new Channel();
const dbView = await Database_View.New(database, database, database);
2023-11-25 13:26:03 +00:00
const newNostrEventChannel = new Channel<NostrEvent>();
(async () => {
for await (const event of newNostrEventChannel) {
const err = await pool.sendEvent(event);
if (err instanceof Error) {
console.error(err);
}
}
})();
2024-01-19 07:21:43 +00:00
{
for (;;) {
if (getSignInState() === "none") {
break;
}
const ctx = await getCurrentSignInCtx();
2024-01-19 07:21:43 +00:00
if (ctx instanceof Error) {
console.error(ctx);
break;
2024-01-19 07:21:43 +00:00
} else if (ctx) {
const otherConfig = await OtherConfig.FromLocalStorage(ctx, newNostrEventChannel, lamport);
const app = await App.Start({
database: dbView,
model,
ctx,
eventBus,
pool,
popOverInputChan,
rightPanelInputChan,
2024-01-19 07:21:43 +00:00
otherConfig,
lamport,
installPrompt,
2024-03-15 14:30:58 +00:00
toastInputChan,
2024-01-19 07:21:43 +00:00
});
model.app = app;
break;
}
}
2023-07-09 08:17:09 +00:00
}
2023-07-09 07:06:13 +00:00
/* first render */ render(
<AppComponent
eventBus={eventBus}
model={model}
pool={pool}
popOverInputChan={popOverInputChan}
rightPanelInputChan={rightPanelInputChan}
installPrompt={installPrompt}
2024-03-15 14:30:58 +00:00
toastInputChan={toastInputChan}
/>,
document.body,
);
2023-07-21 12:40:49 +00:00
for await (
let ok of UI_Interaction_Update({
model,
eventBus,
dbView: dbView,
pool,
popOver: popOverInputChan,
rightPanel: rightPanelInputChan,
2023-11-25 13:26:03 +00:00
newNostrEventChannel: newNostrEventChannel,
2023-11-25 14:29:50 +00:00
lamport,
2023-11-27 13:35:01 +00:00
installPrompt,
2024-03-15 14:30:58 +00:00
toastInputChan: toastInputChan,
})
) {
if (ok == false) {
continue;
}
2023-07-09 07:06:13 +00:00
const t = Date.now();
{
render(
<AppComponent
eventBus={eventBus}
model={model}
pool={pool}
popOverInputChan={popOverInputChan}
rightPanelInputChan={rightPanelInputChan}
installPrompt={installPrompt}
2024-03-15 14:30:58 +00:00
toastInputChan={toastInputChan}
/>,
document.body,
);
2023-07-09 07:06:13 +00:00
}
console.log("UI_Interaction_Update render:", Date.now() - t);
2023-07-09 07:06:13 +00:00
}
}
2023-06-30 14:05:57 +00:00
export class App {
private constructor(
public readonly database: Database_View,
public readonly model: Model,
public readonly ctx: NostrAccountContext,
public readonly eventBus: EventBus<UI_Interaction_Event>,
public readonly pool: ConnectionPool,
public readonly popOverInputChan: PopOverInputChannel,
public readonly rightPanelInputChan: Channel<() => ComponentChildren>,
2023-10-01 23:16:08 +00:00
public readonly otherConfig: OtherConfig,
2023-10-15 22:39:21 +00:00
public readonly conversationLists: DM_List,
public readonly relayConfig: RelayConfig,
2024-01-01 17:28:10 +00:00
public readonly lamport: LamportTime,
public readonly dmController: DirectedMessageController,
public readonly toastInputChan: ToastChannel,
) {}
static async Start(args: {
database: Database_View;
model: Model;
ctx: NostrAccountContext;
eventBus: EventBus<UI_Interaction_Event>;
pool: ConnectionPool;
popOverInputChan: PopOverInputChannel;
rightPanelInputChan: Channel<() => ComponentChildren>;
otherConfig: OtherConfig;
2023-11-25 14:29:50 +00:00
lamport: LamportTime;
2024-01-01 17:28:10 +00:00
installPrompt: InstallPrompt;
toastInputChan: ToastChannel;
}) {
const all_events = Array.from(args.database.getAllEvents());
args.lamport.fromEvents(all_events);
2023-11-18 17:11:07 +00:00
// init relay config
const relayConfig = await RelayConfig.FromLocalStorage({
ctx: args.ctx,
relayPool: args.pool,
});
console.log(relayConfig.getRelayURLs());
// init conversation list
2023-11-28 18:06:49 +00:00
const conversationLists = new DM_List(args.ctx);
2023-12-22 13:03:59 +00:00
const err = conversationLists.addEvents(all_events, false);
2023-12-22 12:20:34 +00:00
if (err instanceof InvalidEvent) {
console.error(err);
await args.database.remove(err.event.id);
}
2023-10-03 15:15:45 +00:00
const dmController = new DirectedMessageController(args.ctx);
(async () => {
// load DMs
2023-12-22 12:20:34 +00:00
for (const e of all_events) {
if (e.kind == NostrKind.DIRECT_MESSAGE) {
const error = await dmController.addEvent({
...e,
kind: e.kind,
});
if (error instanceof Error) {
console.error(error.message);
await args.database.remove(e.id);
}
} else {
continue;
}
}
})();
2023-10-23 03:59:41 +00:00
const app = new App(
args.database,
args.model,
args.ctx,
args.eventBus,
args.pool,
args.popOverInputChan,
args.rightPanelInputChan,
args.otherConfig,
conversationLists,
relayConfig,
2023-11-25 14:29:50 +00:00
args.lamport,
dmController,
2024-03-15 14:30:58 +00:00
args.toastInputChan,
);
2023-11-27 13:35:01 +00:00
await app.initApp(args.installPrompt);
2023-10-23 03:59:41 +00:00
return app;
2023-06-30 14:05:57 +00:00
}
2024-01-01 17:28:10 +00:00
private initApp = async (installPrompt: InstallPrompt) => {
2023-07-09 07:06:13 +00:00
console.log("App.initApp");
// Sync events
{
forever(sync_client_specific_data(this.pool, this.ctx, this.database));
forever(sync_dm_events(this.database, this.ctx, this.pool));
forever(sync_profile_events(this.database, this.pool));
forever(sync_kind_1(this.pool, this.database));
}
2023-06-30 14:05:57 +00:00
/* my profile */
const myProfileEvent = this.database.getProfilesByPublicKey(this.ctx.publicKey);
if (myProfileEvent != undefined) {
this.model.myProfile = myProfileEvent.profile;
}
2023-06-30 14:05:57 +00:00
2023-07-09 07:06:13 +00:00
// Database
2023-06-30 14:05:57 +00:00
(async () => {
2023-07-09 07:06:13 +00:00
let i = 0;
2023-06-30 14:05:57 +00:00
for await (
let _ of Database_Update(
this.ctx,
2023-06-30 14:05:57 +00:00
this.database,
this.model,
2023-07-09 07:06:13 +00:00
this.lamport,
this.conversationLists,
this.dmController,
2023-10-15 22:39:21 +00:00
this.eventBus.emit,
2023-11-25 13:26:03 +00:00
{
otherConfig: this.otherConfig,
},
2023-06-30 14:05:57 +00:00
)
) {
const t = Date.now();
render(
<AppComponent
eventBus={this.eventBus}
model={this.model}
pool={this.pool}
popOverInputChan={this.popOverInputChan}
rightPanelInputChan={this.rightPanelInputChan}
installPrompt={installPrompt}
2024-03-15 14:30:58 +00:00
toastInputChan={this.toastInputChan}
/>,
document.body,
);
console.log(`Database_Update: render ${++i} times, ${Date.now() - t}`);
2023-06-30 14:05:57 +00:00
}
})();
};
logout = () => {
setSignInState("none");
window.location.reload();
};
}
type AppProps = {
model: Model;
eventBus: AppEventBus;
pool: ConnectionPool;
popOverInputChan: PopOverInputChannel;
rightPanelInputChan: Channel<() => ComponentChildren>;
toastInputChan: ToastChannel;
2024-01-01 17:28:10 +00:00
installPrompt: InstallPrompt;
};
export class AppComponent extends Component<AppProps> {
events = this.props.eventBus.onChange();
componentWillUnmount() {
this.events.close();
2023-06-30 14:05:57 +00:00
}
render(props: AppProps) {
const t = Date.now();
const model = props.model;
if (model.app == undefined) {
console.log("render sign in page");
return <SignIn emit={props.eventBus.emit} />;
}
const app = model.app;
const myAccountCtx = model.app.ctx;
let dmVNode;
let aboutNode;
if (
model.navigationModel.activeNav == "DM" ||
model.navigationModel.activeNav == "About"
) {
if (model.navigationModel.activeNav == "DM" && model.currentRelay) {
dmVNode = (
<DirectMessageContainer
{...model.dm}
bus={app.eventBus}
ctx={myAccountCtx}
getters={{
convoListRetriever: app.conversationLists,
messageGetter: app.dmController,
newMessageChecker: app.conversationLists,
relayRecordGetter: app.database,
pinListGetter: app.otherConfig,
profileGetter: app.database,
isUserBlocked: app.conversationLists.isUserBlocked,
getEventByID: app.database.getEventByID,
}}
userBlocker={app.conversationLists}
/>
);
}
if (model.navigationModel.activeNav == "About") {
aboutNode = About(app.eventBus.emit);
}
}
let socialNode: VNode | undefined;
if (model.navigationModel.activeNav == "Social" && model.currentRelay) {
socialNode = (
<ChannelContainer
ctx={myAccountCtx}
{...model.social}
getters={{
convoListRetriever: app.conversationLists,
newMessageChecker: app.conversationLists,
relayRecordGetter: app.database,
profileGetter: app.database,
isUserBlocked: app.conversationLists.isUserBlocked,
getEventByID: app.database.getEventByID,
}}
messages={Array.from(
map(
filter(
app.database.getAllEvents(),
(e) => {
if (e.kind != NostrKind.TEXT_NOTE) {
return false;
}
const relays = app.database.getRelayRecord(e.id);
return relays.has(model.currentRelay);
},
),
(e) => {
const msg: ChatMessage = {
author: e.publicKey,
content: e.content,
created_at: new Date(e.created_at * 1000),
event: e as Parsed_Event<NostrKind.TEXT_NOTE>,
lamport: getTags(e).lamport_timestamp,
type: "text",
};
return msg;
},
),
)}
relay={props.pool.getRelay(model.currentRelay) as SingleRelayConnection}
bus={app.eventBus}
/>
2023-06-30 14:05:57 +00:00
);
}
console.debug("AppComponent:2", Date.now() - t);
const final = (
<div class={`h-screen w-full flex`}>
<NavBar
publicKey={app.ctx.publicKey}
profile={app.database.getProfilesByPublicKey(myAccountCtx.publicKey)}
emit={app.eventBus.emit}
installPrompt={props.installPrompt}
currentRelay={model.currentRelay}
activeNav={model.navigationModel.activeNav}
pool={app.pool}
/>
2023-06-30 14:05:57 +00:00
2023-12-21 17:17:03 +00:00
<div
class={`h-full px-[3rem] sm:px-4 bg-[${SecondaryBackgroundColor}] flex-1 overflow-auto${
model.navigationModel.activeNav == "Profile" ? " block" : " hidden"
}`}
2023-12-21 17:17:03 +00:00
>
<div
class={`max-w-[35rem] h-full m-auto`}
>
<EditProfile
ctx={model.app.ctx}
profileGetter={app.database}
emit={props.eventBus.emit}
/>
</div>
2023-06-30 14:05:57 +00:00
</div>
{socialNode}
{dmVNode}
{aboutNode}
{Setting({
show: model.navigationModel.activeNav == "Setting",
logout: app.logout,
relayConfig: app.relayConfig,
myAccountContext: myAccountCtx,
relayPool: props.pool,
emit: props.eventBus.emit,
})}
<Popover
inputChan={props.popOverInputChan}
/>
<RightPanel
inputChan={props.rightPanelInputChan}
/>
2024-03-15 14:30:58 +00:00
<Toast inputChan={props.toastInputChan} />
2023-06-30 14:05:57 +00:00
</div>
);
2023-06-30 14:05:57 +00:00
console.debug("AppComponent:end", Date.now() - t);
return final;
}
2023-06-30 14:05:57 +00:00
}
// todo: move to somewhere else
export function getFocusedContent(
focusedContent: PublicKey | NostrEvent | undefined,
2023-10-07 20:40:18 +00:00
profileGetter: ProfileGetter,
2023-06-30 14:05:57 +00:00
) {
if (focusedContent == undefined) {
return;
}
if (focusedContent instanceof PublicKey) {
2023-10-07 20:40:18 +00:00
const profileData = profileGetter.getProfilesByPublicKey(focusedContent)?.profile;
2023-06-30 14:05:57 +00:00
return {
type: "ProfileData" as "ProfileData",
data: profileData,
pubkey: focusedContent,
};
}
}
async function sync_dm_events(
database: Database_View,
ctx: NostrAccountContext,
pool: ConnectionPool,
) {
const messageStream = getAllEncryptedMessagesOf(
ctx.publicKey,
pool,
);
for await (const msg of messageStream) {
if (msg.res.type == "EVENT") {
const err = await database.addEvent(msg.res.event, msg.url);
if (err instanceof Error) {
console.log(err);
}
}
}
}
async function sync_profile_events(
database: Database_View,
pool: ConnectionPool,
) {
const messageStream = await pool.newSub("sync_profile_events", {
kinds: [NostrKind.META_DATA],
});
if (messageStream instanceof Error) {
return messageStream;
}
for await (const msg of messageStream.chan) {
if (msg.res.type == "EVENT") {
const err = await database.addEvent(msg.res.event, msg.url);
if (err instanceof Error) {
console.log(err);
}
}
}
}
const sync_kind_1 = async (pool: ConnectionPool, database: Database_View) => {
const stream = await pool.newSub("sync_kind_1", {
kinds: [NostrKind.TEXT_NOTE],
});
if (stream instanceof Error) {
return stream;
}
for await (const msg of stream.chan) {
if (msg.res.type == "EOSE" || msg.res.type == "NOTICE") {
continue;
}
const ok = await database.addEvent(msg.res.event, msg.url);
if (ok instanceof Error) {
console.error(msg);
console.error(ok);
}
}
};
const sync_client_specific_data = async (
pool: ConnectionPool,
ctx: NostrAccountContext,
database: Database_View,
) => {
const stream = await pool.newSub(OtherConfig.name, {
authors: [ctx.publicKey.hex],
kinds: [NostrKind.Encrypted_Custom_App_Data],
});
if (stream instanceof Error) {
throw stream; // crash the app
}
for await (const msg of stream.chan) {
if (msg.res.type == "EOSE" || msg.res.type == "NOTICE") {
continue;
}
const ok = await database.addEvent(msg.res.event, msg.url);
if (ok instanceof Error) {
console.error(msg.res.event);
console.error(ok);
}
}
};
// f should not resolve, if it does resolve, it should only throw an error
async function forever(f: Promise<Error | undefined | void>) {
const r = await f;
if (r == undefined) {
throw new Error(`${f} should not resolve`);
}
throw r;
}