repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
samjeyam/nestjs-passport-clientcert-demo
src/helloworld/helloworld.module.ts
<reponame>samjeyam/nestjs-passport-clientcert-demo import { Module } from '@nestjs/common'; import { HelloworldController } from './helloworld.controller'; @Module({ controllers: [HelloworldController] }) export class HelloworldModule {}
samjeyam/nestjs-passport-clientcert-demo
src/auth/client-cert.strategy.ts
<filename>src/auth/client-cert.strategy.ts import { PeerCertificate, Strategy } from 'passport-client-cert'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config' @Injectable() export class ClientCertStrategy extends PassportStrategy(Strategy) { private whitelistedCns: string[] = []; constructor(private configService: ConfigService) { super(); this.whitelistedCns.push(this.configService.get<string>('WHITELISTED_CN')); } async validate(clientCert: PeerCertificate): Promise<any> { const cn = clientCert && clientCert.subject && clientCert.subject.CN; if (!this.whitelistedCns.includes(cn)) { console.error('Unauthorized: Client cert cn : %s is not whitelisted', cn); throw new UnauthorizedException(); } console.log(cn, 'Client Authorized'); return Promise.resolve({user: {name: cn}}); } }
niklaas/rx-angular
libs/cdk/src/index.ts
/* @todo: remove the following backward compatibility barrel exports when we have a migration script. */ export * from '@rx-angular/cdk/coalescing'; export * from '@rx-angular/cdk/coercing'; export * from '@rx-angular/cdk/internals/scheduler'; export * from '@rx-angular/cdk/render-strategies'; export * from '@rx-angular/cdk/state'; export * from '@rx-angular/cdk/template'; export * from '@rx-angular/cdk/notifications'; export * from '@rx-angular/cdk/zone-less'; export * from '@rx-angular/cdk/zone-configurations';
niklaas/rx-angular
libs/cdk/render-strategies/src/lib/config.ts
import { InjectionToken } from '@angular/core'; import { RX_CONCURRENT_STRATEGIES } from './concurrent-strategies'; import { RxCustomStrategyCredentials, RxDefaultStrategyNames, RxStrategyNames } from './model'; import { RX_NATIVE_STRATEGIES } from './native-strategies'; export interface RxRenderStrategiesConfig<T extends string> { primaryStrategy?: RxStrategyNames<T>; customStrategies?: RxCustomStrategyCredentials<T>; patchZone?: boolean; } /** * @deprecated use RxAngularRenderStrategiesConfig instead */ export interface RxAngularConfig<T extends string> extends RxRenderStrategiesConfig<T> { }; export const RX_RENDER_STRATEGIES_CONFIG = new InjectionToken<RxRenderStrategiesConfig<string>>( 'rxa-render-strategies-config' ); export const RX_ANGULAR_RENDER_STRATEGIES_DEFAULTS: Required<RxRenderStrategiesConfig<RxDefaultStrategyNames>> = { primaryStrategy: 'normal', customStrategies: { ...RX_NATIVE_STRATEGIES, ...RX_CONCURRENT_STRATEGIES }, patchZone: true } as const; /** * @deprecated use RX_ANGULAR_RENDER_STRATEGIES_CONFIG instead */ export const RX_ANGULAR_CONFIG = new InjectionToken<RxAngularConfig<string>>( 'rx-angular-config' ); /** * @deprecated use RX_ANGULAR_RENDER_STRATEGIES_DEFAULTS instead */ export const RX_ANGULAR_DEFAULTS: Required<RxAngularConfig<RxDefaultStrategyNames>> = { primaryStrategy: 'normal', customStrategies: { ...RX_NATIVE_STRATEGIES, ...RX_CONCURRENT_STRATEGIES }, patchZone: true } as const; export function mergeDefaultConfig<T extends string>( cfg?: RxRenderStrategiesConfig<T> ): Required<RxRenderStrategiesConfig<T | RxDefaultStrategyNames>> { const custom: RxRenderStrategiesConfig<T> = cfg ? cfg : ({ customStrategies: {} } as any); return { ...RX_ANGULAR_RENDER_STRATEGIES_DEFAULTS, ...custom, customStrategies: { ...custom.customStrategies, ...RX_ANGULAR_RENDER_STRATEGIES_DEFAULTS.customStrategies } }; }
ErgerSusha/Diploma_Server
src/socket/socket.module.ts
import { Module } from '@nestjs/common'; import { SocketsController } from './socket.gateway'; @Module({ providers: [SocketsController] }) export class SocketModule { }
ErgerSusha/Diploma_Server
src/socket/socket.gateway.ts
<reponame>ErgerSusha/Diploma_Server<filename>src/socket/socket.gateway.ts import { WebSocketGateway, OnGatewayConnection, OnGatewayDisconnect, SubscribeMessage, } from '@nestjs/websockets'; import { Socket } from 'socket.io'; interface ChatSocket extends Socket { isAdmin: boolean; calleeId: string; isCalling: boolean; } @WebSocketGateway() export class SocketsController implements OnGatewayConnection, OnGatewayDisconnect { adminToken = '<PASSWORD>'; users: ChatSocket[] = []; private sendTo(connection: ChatSocket, event: string, data?: any) { data ? connection.emit(event, JSON.stringify(data)) : connection.emit(event); } @SubscribeMessage('rtcevent') sendMessageByUserId(caller: ChatSocket, eventJson: string) { let data: any; try { data = JSON.parse(eventJson); } catch (error) { console.warn(`Invalid JSON: ${error}`); return; } const callee = this.users.find(user => user.id === data.calleeId); switch (data.type) { case 'offer': caller.calleeId = data.calleeId; this.sendTo(callee, 'offer', { offer: data.offer, callerId: caller.id }); break; case 'answer': caller.calleeId = data.calleeId; caller.isCalling = true; callee.isCalling = true; this.onUsersCallStatusChanged(true, caller, callee); this.sendTo(callee, 'answer', { answer: data.answer }); break; case 'candidate': this.sendTo(callee, 'candidate', { candidate: data.candidate }); break; case "hangup": delete caller.calleeId; delete caller.isCalling; this.onUsersCallStatusChanged(false, caller, callee); this.sendTo(callee, 'hangup'); break; } } async handleConnection(client: ChatSocket) { if (client.handshake.query.adminToken === this.adminToken) { client.isAdmin = true; } this.users.push(client); this.users.forEach(user => { if (client.id === user.id) { client.emit('init_users', this.users .filter(_user => client.isAdmin ? !_user.isAdmin : _user.isAdmin) .map(_user => ({ id: _user.id, isCalling: _user.isCalling })) ); } else if ((client.isAdmin && !user.isAdmin) || (!client.isAdmin && user.isAdmin)) { user.emit('user_connected', client.id); } }); } async handleDisconnect(client: ChatSocket) { if (client.calleeId) { const callee = this.users.find(user => user.id === client.calleeId); if (callee) { delete callee.calleeId; } } this.users.splice(this.users.indexOf(client), 1); this.users.forEach(user => { if ((client.isAdmin && !user.isAdmin) || (!client.isAdmin && user.isAdmin)) { user.emit('user_disconnected', client.id); } }); } onUsersCallStatusChanged(isCalling: boolean, caller: ChatSocket, callee: ChatSocket) { const callingAdminId = (caller.isAdmin ? caller : callee).id; const callingClientId = (caller.isAdmin ? callee : caller).id; this.users.forEach(user => { if (user.isAdmin) { user.emit('user_call_status_changed', { isCalling, callingClientId }); } else { user.emit('user_call_status_changed', { isCalling, callingAdminId }); } }); } }
JairzinhoGil/Platzi--Store
src/recap.ts
const myName = 'Jair'; const myAge = 35; const suma = (a: number, b: number) => { return a + b; }; suma(35, 33); class Persona { constructor(private age: number, private name: string) {} getSummary() { return `my name is ${this.name}, ${this.age}`; } } const jair = new Persona(35, 'jair'); jair.getSummary();
ArunMurugan78/mdslide
components/PrevSlideButton/index.tsx
import { Flex, FlexProps } from "@chakra-ui/react"; import { ChevronLeftIcon } from "@chakra-ui/icons"; import { useStore } from "lib/stores/presentation"; export type PrevSlideButtonProps = FlexProps; export const PrevSlideButton = (props: PrevSlideButtonProps) => { const onClick = useStore((store) => store.goToPrevSlide); const disabled = useStore((state) => state.currentSlideIdx === 0); return ( <Flex as="button" aria-label="go to previous slide" mr="5" p="10px" bg="#fafafa" borderRadius="50%" height="36px" alignItems="center" justify="center" width="36px" boxShadow="base" color="#495464" _disabled={{ cursor: "not-allowed" }} _hover={{ boxShadow: "md" }} _focus={{ boxShadow: "md" }} {...props} onClick={onClick} disabled={disabled} > <ChevronLeftIcon w={6} h={6} /> </Flex> ); };
ArunMurugan78/mdslide
components/EditorNavbar/index.tsx
import Link from "next/link"; import { FC } from "react"; import { Input, Flex, Spacer, Spinner, Tooltip, Icon, IconButton, Divider, useDisclosure, } from "@chakra-ui/react"; import Logo from "components/Logo"; import AccountActions from "components/AccountActions"; import StartPresentationModeButton from "components/StartPresentationModeButton"; import PublishSettingsModal from "components/PublishSettingsModal"; import { useStore } from "lib/stores/presentation"; export interface EditorNavbarProps {} export const EditorNavbar: FC<EditorNavbarProps> = () => { const { isOpen, onClose, onOpen } = useDisclosure(); const isSaving = useStore((state) => state.isSaving); const title = useStore((state) => state.presentation.title); const updateTitle = useStore((store) => store.updateTitle); return ( <> <PublishSettingsModal isOpen={isOpen} onClose={onClose} /> <Flex as="nav" p="20px" boxShadow="xl" width="100%" height="70px" alignItems="center" borderWidth="1px" borderColor="#e2e8f0" > <Link href="/"> <Logo fontSize="xl" /> </Link> <Spacer /> <Input maxWidth="400px" textAlign="center" value={title} required isInvalid={title?.trim() === ""} focusBorderColor="black" onChange={(e) => updateTitle(e.target.value)} /> <Spacer /> {isSaving ? ( <Tooltip label="saving.." aria-label="saving the changes"> <Flex justifyContent="flex-end" width="34px" height="25px"> <Spinner emptyColor="gray.200" color="gray.400" width="25px" height="25px" /> </Flex> </Tooltip> ) : ( <Tooltip label="saved" aria-label="saved to cloud"> <Icon viewBox="0 0 24 24" width="34px" color="gray.300" height="34px" > <path d="M0 0h24v24H0z" fill="none" /> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96z" fill="currentColor" /> </Icon> </Tooltip> )} <Divider orientation="vertical" ml="20px" /> <StartPresentationModeButton ml="20px" /> <Tooltip label="Publish Settings"> <IconButton bg="transparent" aria-label="" onClick={onOpen} size="sm" ml="20px" icon={ <Icon height="30px" viewBox="0 0 24 24" width="30px" fill="gray.500" > <path d="M0 0h24v24H0z" fill="none" /> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z" /> </Icon> } /> </Tooltip> <AccountActions aria-label="account options" ml="20px" size="sm" /> </Flex> </> ); }; export default EditorNavbar;
ArunMurugan78/mdslide
lib/db/entity.ts
import "reflect-metadata"; export const Entity = (options: { name: string }) => Reflect.metadata("entity", options.name);
ArunMurugan78/mdslide
utils/isValidSlug.ts
export const isValidSlug = (slug: string | undefined) => typeof slug === "string" && slug.trim().length !== 0 && !/[^0-9a-zA-Z-_]/.test(slug.trim()) && /^[a-zA-Z]/.test(slug.trim());
ArunMurugan78/mdslide
lib/stores/presentation/createNewSlide.ts
import axios from "axios"; import Slide from "model/slide"; import createErrorToast from "lib/createErrorToast"; import type { MapToPartial } from "./types"; import { isTempId } from "lib/utils/getTempId"; export const createNewSlide = ( slide: Slide, pid: string, updateSlide: (id: string, map: MapToPartial<Slide>) => void, callback: (promise: Promise<any>) => void ) => { const sid = slide.id; if (!isTempId(slide.id)) { console.error( "new slide should have temporary id before saving it at remote. got ", slide.id ); return; } const promise = axios.post(`/api/p/${pid}/slide/new`, { slide, }); promise.then((res) => { const { data: { id }, } = res; if (typeof id === "string") { updateSlide(sid, () => ({ id })); } else { console.error("expected id of type string from the api. got ", id); } }); promise.catch(() => { createErrorToast("Error saving the slide"); }); callback(promise); };
ArunMurugan78/mdslide
lib/atoms/LoadedFontFaces.ts
<filename>lib/atoms/LoadedFontFaces.ts<gh_stars>10-100 import { atom } from "jotai"; export const loadedFontFamiliesAtom = atom<Set<string>>(new Set<string>()); export const fontFaceTextsAtom = atom<string>("");
ArunMurugan78/mdslide
components/index.ts
export { EditorNavbar } from "./EditorNavbar"; export { EditorPanel } from "./EditorPanel"; export { PreviewSpace } from "./PreviewSpace"; export { HomeNavbar } from "./HomeNavbar"; export { SlideNavigator } from "./SlideNavigator"; export { Slide } from "./Slide"; export { Logo } from "./Logo"; export { PrimaryButton } from "./PrimayButton"; export { PublishSettingsModal } from "./PublishSettingsModal"; export { AccountActions } from "./AccountActions"; export { ColorPicker } from "./ColorPicker"; export { LoadFonts } from "./LoadFonts"; export { FullScreenPresentation } from "./FullScreenPresentation"; export { NextSlideButton } from "./NextSlideButton"; export { PrevSlideButton } from "./PrevSlideButton"; export { Meta } from "./Meta"; export { StartPresentationModeButton } from "./StartPresentationModeButton"; export type { EditorNavbarProps } from "./EditorNavbar"; export type { EditorPanelProps } from "./EditorPanel"; export type { HomeNavbarProps } from "./HomeNavbar"; export type { SlideNavigatorProps } from "./SlideNavigator"; export type { PreviewSpaceProps } from "./PreviewSpace"; export type { LogoProps } from "./Logo"; export type { NextSlideButtonProps } from "./NextSlideButton"; export type { PrevSlideButtonProps } from "./PrevSlideButton"; export type { SlideProps } from "./Slide"; export type { ColorPickerProps } from "./ColorPicker"; export type { AccountActionsProps } from "./AccountActions"; export type { PublishSettingsModalProps } from "./PublishSettingsModal"; export type { MetaProps } from "./Meta"; export type { FullScreenPresentationProps } from "./FullScreenPresentation"; export type { StartPresentationModeButtonProps } from "./StartPresentationModeButton";
ArunMurugan78/mdslide
pages/api/p/[pid]/slide/[sid].ts
import { catchErrors } from "./../../../../../lib/exceptions/catcherrors"; import { withApiAuthRequired } from "@auth0/nextjs-auth0"; import { ObjectId } from "mongodb"; import { getDb } from "lib/db/getDb"; import { getSession } from "@auth0/nextjs-auth0"; import { NextApiHandler } from "next"; import { BadRequestException } from "lib/exceptions/common"; import { Presentation } from "model/presentation"; import { isValidSlide } from "lib/utils/isValidSlide"; const handler: NextApiHandler = async (req, res) => { const { user } = getSession(req, res); const { sid, pid } = req.query as { sid: string; pid: string }; const db = await getDb(); const collection = db.getCollection(Presentation); const filter = { _id: new ObjectId(pid), userEmail: user.email }; if (req.method === "DELETE") { await collection.updateOne(filter, { $pull: { slides: { _id: new ObjectId(sid) } }, }); } else { const { slide } = req.body; if (!isValidSlide(slide)) { throw new BadRequestException(); } if (sid === "new") { const id = new ObjectId(); collection.updateOne(filter, { $push: { slides: { ...slide, _id: id } }, }); res.json({ id: id.toHexString() }); return; } await collection.updateOne( filter, { $set: { "slides.$[slide]": { ...slide, _id: new ObjectId(sid) } } }, { arrayFilters: [{ "slide._id": new ObjectId(sid) }] } ); } res.json(200); }; export default withApiAuthRequired(catchErrors(handler));
ArunMurugan78/mdslide
pages/api/p/[pid]/unpublish.ts
import { ObjectId } from "mongodb"; import { Presentation } from "model/presentation"; import { getDb } from "lib/db/getDb"; import { NextApiHandler } from "next"; import { catchErrors } from "lib/exceptions/catcherrors"; import { withApiAuthRequired, getSession } from "@auth0/nextjs-auth0"; const handler: NextApiHandler = async (req, res) => { const { user } = getSession(req, res); const { pid } = req.query as { pid: string }; const db = await getDb(); const collection = db.getCollection(Presentation); await collection.updateOne( { _id: new ObjectId(pid), userEmail: user.email }, { $set: { isPublished: false } } ); res.status(200).send("OK"); }; export default withApiAuthRequired(catchErrors(handler));
ArunMurugan78/mdslide
model/interfaces/presentation.ts
<gh_stars>10-100 import { Slide } from "model/slide"; export interface Presentation { id: string; title: string; userEmail: string; slides: Slide[]; isPublished: boolean; createdAt: string; pubmeta?: { slug: string }; } export default Presentation;
ArunMurugan78/mdslide
components/SlideNavigator/index.tsx
import AutoSizer from "react-virtualized-auto-sizer"; import { FC, useRef, useEffect } from "react"; import { FixedSizeList as List } from "react-window"; import { Flex, Box } from "@chakra-ui/react"; import Slide from "components/Slide"; import { useStore } from "lib/stores/presentation"; import { NewSlideButton } from "./components"; export interface SlideNavigatorProps { onClickSlide: (idx: number) => any; } export const SlideNavigator: FC<SlideNavigatorProps> = (props) => { const { onClickSlide } = props; const slides = useStore((state) => state.presentation.slides); const currentSlideIndex = useStore((state) => state.currentSlideIdx); const onAddNewSlide = useStore((store) => store.addNewSlide); const listRef = useRef<List<any>>(); useEffect(() => { if (listRef.current) { listRef.current?.scrollToItem(slides.length); } }, [slides.length]); return ( <Flex pl={"20px"} alignItems="flex-start" bg="#F4F4F2" width="100%" height="100%" > <NewSlideButton onClick={onAddNewSlide} /> <Box width={"calc(100% - 115px)"} height={"80px"}> <AutoSizer> {({ width, height }) => { return ( <List ref={listRef} width={width} height={height} itemCount={slides.length} itemSize={105} layout="horizontal" > {({ style, index }) => ( <Slide key={index} fontFamily={slides[index].fontFamily} constraintSize={{ width: 100, height: 1000 }} mdContent={slides[index].mdContent} fontColor={slides[index].fontColor} bgColor={slides[index].bgColor} onClick={() => { onClickSlide(index); }} opacity={currentSlideIndex === index ? 1 : 0.8} border={currentSlideIndex === index ? "2px" : "1px"} borderColor="#495464" as="button" outline="none" _focus={{ opacity: 1, }} mr="5px" borderRadius="3px" style={{ ...style, marginLeft: "5px", width: 100, height: 60, }} /> )} </List> ); }} </AutoSizer> </Box> </Flex> ); };
ArunMurugan78/mdslide
components/PreviewSpace/Size.ts
<reponame>ArunMurugan78/mdslide<filename>components/PreviewSpace/Size.ts export type Size = { height: number; width: number };
ArunMurugan78/mdslide
components/Slide/index.tsx
import { FC } from "react"; import { Box, BoxProps } from "@chakra-ui/react"; import MDEditor from "@uiw/react-md-editor"; import { getSlideSize } from "./getSlideSize"; import { getScaleFactor } from "./getScaleFactor"; export type SlideProps = { constraintSize: { height: number; width: number }; mdContent: string; bgColor: string; fontColor: string; fontFamily: string; } & BoxProps; export const Slide: FC<SlideProps> = (props) => { const { constraintSize, mdContent, bgColor, fontColor, fontFamily, ...rest } = props; const slideSize = getSlideSize(constraintSize); return ( <Box {...rest} width={slideSize.width} overflow="hidden" height={slideSize.height} bg={bgColor} id="slide-outer" position="relative" > <Box width={1920} bg={bgColor} position="absolute" top={-1 * 540 + slideSize.height / 2} left={-1 * (1920 / 2) + slideSize.width / 2} transform={`scale(${getScaleFactor(constraintSize)})`} color={fontColor} height={1080} > <MDEditor.Markdown style={{ fontSize: 1920 / 34, paddingLeft: "200px", paddingRight: "200px", fontFamily, }} source={mdContent} /> </Box> </Box> ); }; export default Slide;
ArunMurugan78/mdslide
pages/api/p/[pid]/publish.ts
import { ObjectId } from "mongodb"; import { NextApiHandler } from "next"; import { withApiAuthRequired, getSession } from "@auth0/nextjs-auth0"; import { getDb } from "lib/db/getDb"; import { Presentation } from "model/presentation"; import { catchErrors } from "lib/exceptions/catcherrors"; import { UnAuthorizedException } from "lib/exceptions/common"; const handler: NextApiHandler<{ pubmeta: { slug: string } }> = async ( req, res ) => { const { user } = getSession(req, res); const { pid } = req.query as { pid: string }; const db = await getDb(); const collection = db.getCollection(Presentation); const filter = { _id: new ObjectId(pid) }; const { isPublished, pubmeta, title, userEmail } = await collection.findOne( filter, { projection: { isPublished: 1, pubmeta: 1, title: 1, userEmail: 1 } } ); if (userEmail !== user.email) { throw new UnAuthorizedException(); } if (isPublished) { res.json({ pubmeta }); return; } const slug = "p" + pid; await collection.updateOne(filter, { $set: { pubmeta: { slug }, isPublished: true }, }); res.json({ pubmeta: { slug } }); }; export default catchErrors(withApiAuthRequired(handler));
ArunMurugan78/mdslide
components/PreviewSpace/index.tsx
<reponame>ArunMurugan78/mdslide import { FC } from "react"; import { Flex, Box } from "@chakra-ui/react"; import { ChevronRightIcon, ChevronLeftIcon } from "@chakra-ui/icons"; import Slide from "components/Slide"; import useConstraint from "./useConstraint"; import { useStore } from "lib/stores/presentation"; export interface PreviewSpaceProps { mdContent: string; bgColor: string; fontColor: string; fontFamily: string; } export const PreviewSpace: FC<PreviewSpaceProps> = (props) => { const { mdContent, fontColor, bgColor, fontFamily } = props; const constraint = useConstraint(); const store = useStore(); return ( <Box position="relative" width="100%" height="100%"> <Flex as="button" aria-label="go to previous slide" position="absolute" top="calc(50% - 15px)" left="20px" p="10px" bg="#fafafa" borderRadius="50%" height="30px" alignItems="center" justify="center" width="30px" onClick={store.goToPrevSlide} boxShadow="base" color="#495464" disabled={store.currentSlideIdx === 0} _disabled={{ cursor: "not-allowed" }} _hover={{ boxShadow: "md" }} _focus={{ boxShadow: "md" }} > <ChevronLeftIcon /> </Flex> <Flex position="absolute" as="button" aria-label="go to next slide" top="calc(50% - 15px)" right="20px" p="10px" bg="#fafafa" borderRadius="50%" height="30px" alignItems="center" justify="center" width="30px" onClick={store.goToNextSlide} boxShadow="base" color="#495464" disabled={ store.currentSlideIdx === store.presentation.slides.length - 1 } _disabled={{ cursor: "not-allowed" }} _hover={{ boxShadow: "md" }} _focus={{ boxShadow: "md" }} > <ChevronRightIcon /> </Flex> <Flex id="preview-space" p="20px" style={{ backgroundColor: "#f6f5f5" }} width="100%" height="100%" justifyContent="center" alignItems="center" > {constraint.width !== 0 ? ( <Slide bgColor={bgColor} fontFamily={fontFamily} fontColor={fontColor} constraintSize={{ width: constraint.width - 150, height: constraint.height - 100, }} mdContent={mdContent} boxShadow="lg" /> ) : null}{" "} </Flex> </Box> ); }; export default PreviewSpace;
ArunMurugan78/mdslide
lib/exceptions/common.ts
<gh_stars>10-100 import { StatusCodes } from "http-status-codes"; export class UnAuthorizedException extends Error { public readonly code = StatusCodes.UNAUTHORIZED; } export class BadRequestException extends Error { public readonly code = StatusCodes.BAD_REQUEST; } export class InternalServerException extends Error { public readonly code = StatusCodes.INTERNAL_SERVER_ERROR; } export class NotFoundException extends Error { public readonly code = StatusCodes.NOT_FOUND; }
ArunMurugan78/mdslide
components/PreviewSpace/untilAsync.ts
export function untilAsync( fn: () => any, predicate: () => boolean, interval: number ) { const intv = setInterval(() => { fn(); if (predicate()) { clearInterval(intv); } }, interval); }
ArunMurugan78/mdslide
components/PreviewSpace/useConstraint.ts
import { useEffect, useState } from "react"; import type { Size } from "./Size"; import { untilAsync } from "./untilAsync"; import { getConstraint } from "./getConstraint"; export function useConstraint(): Size { const [constraint, setConstraint] = useState<Size>(getConstraint); useEffect(() => { if (typeof window !== "undefined") { window.addEventListener("resize", () => { setConstraint(getConstraint); }); untilAsync( () => setConstraint(getConstraint), () => constraint.width !== 0, 500 ); } }, []); return constraint; } export default useConstraint;
ArunMurugan78/mdslide
lib/stores/presentation/updateRemoteTitle.ts
<reponame>ArunMurugan78/mdslide import axios from "axios"; import debounce from "debounce"; import createErrorToast from "lib/createErrorToast"; export const updateRemoteTitle = (pid: string) => debounce((newTitle: string, callback: (promise: Promise<any>) => void) => { // TODO handle error. const promise = axios.patch(`/api/p/${pid}/title`, { title: newTitle }); promise.catch(() => { createErrorToast("Error saving the title. Try again later"); }); callback(promise); }, 500);
ArunMurugan78/mdslide
components/HomeNavbar/index.tsx
<filename>components/HomeNavbar/index.tsx import axios from "axios"; import { useRouter } from "next/router"; import { FC, useState } from "react"; import { Container, Flex, Spacer, Box } from "@chakra-ui/react"; import { AddIcon } from "@chakra-ui/icons"; import Logo from "components/Logo"; import AccountActions from "components/AccountActions"; import PrimaryButton from "components/PrimayButton"; export interface HomeNavbarProps { isDisabled?: boolean; } export const HomeNavbar: FC<HomeNavbarProps> = (props) => { const { isDisabled } = props; const router = useRouter(); const [isLoading, setLoading] = useState(false); const handleNewPresentation = async () => { setLoading(true); try { const { data } = await axios.post("/api/p/new"); if (typeof data?.id === "string") { await router.push(`/app/${data.id}`); } } catch (e) { console.error(e); } finally { setLoading(false); } }; return ( <Box as="nav" borderBottom="1px" bg="white" borderColor="gray.200"> <Container maxW="container.xl"> <Flex alignItems="center" height="70px"> <Logo /> <Spacer /> <PrimaryButton size="md" isLoading={isLoading} disabled={isDisabled || isLoading} onClick={handleNewPresentation} leftIcon={<AddIcon fontSize={"sm"} />} > New </PrimaryButton> <AccountActions aria-label="account options" size="md" isRound isDisabled={isDisabled} ml="25px" /> </Flex> </Container> </Box> ); }; export default HomeNavbar;
ArunMurugan78/mdslide
model/slide.ts
<filename>model/slide.ts<gh_stars>10-100 export interface Slide { id: string; mdContent: string; bgColor: string; fontColor: string; fontFamily: string; } export default Slide;
ArunMurugan78/mdslide
lib/stores/presentation/deleteSlide.ts
<reponame>ArunMurugan78/mdslide import axios from "axios"; import { createErrorToast } from "lib/createErrorToast"; import debounce from "debounce"; export const deleteSlideRemote = debounce( (sid: string, pid: string, callback: (promise: Promise<any>) => void) => { const promise = axios.delete(`/api/p/${pid}/slide/${sid}`); promise.catch((e) => { console.error(e); createErrorToast("Error deleting the slide."); }); callback(promise); } );
ArunMurugan78/mdslide
components/SlideNavigator/components/index.ts
<filename>components/SlideNavigator/components/index.ts export { NewSlideButton } from "./NewSlideButton"; export type { NewSlideButtonProps } from "./NewSlideButton";
ArunMurugan78/mdslide
lib/utils/isValidSlide.ts
import { Slide } from "model/slide"; function isString(s: any): boolean { return typeof s === "string"; } export function isValidSlide(s: any): s is Slide { return ( isString(s?.mdContent) && isString(s?.bgColor) && isString(s?.fontColor) && isString(s?.fontFamily) ); }
ArunMurugan78/mdslide
pages/api/p/[pid]/title.ts
import { BadRequestException } from "lib/exceptions/common"; import { patchFieldApi } from "@lib/decorators/patch-field"; export default patchFieldApi("title", (newTitle) => { if (typeof newTitle !== "string" || newTitle.trim().length === 0) { throw new BadRequestException("title is required"); } return { $set: { title: newTitle, }, }; });
ArunMurugan78/mdslide
components/PublishSettingsModal/index.tsx
<gh_stars>10-100 import { FC, useState, useEffect } from "react"; import axios from "axios"; import { Modal, ModalOverlay, ModalHeader, ModalBody, ModalFooter, Text, ModalContent, ModalCloseButton, Box, Input, Button, } from "@chakra-ui/react"; import { PrimaryButton } from "components/PrimayButton"; import { useStore } from "@lib/stores/presentation"; import { Presentation } from "model/interfaces/presentation"; import { isValidSlug } from "utils/isValidSlug"; import createErrorToast from "lib/createErrorToast"; export interface PublishSettingsModalProps { isOpen: boolean; onClose: () => void; } export const PublishSettingsModal: FC<PublishSettingsModalProps> = (props) => { const { isOpen, onClose } = props; const store = useStore(); const [isLoading, setLoading] = useState(false); const [isSaving, setSaved] = useState(false); const presentation = store.presentation; const [slug, setSlug] = useState(presentation?.pubmeta?.slug ?? ""); const [error, setError] = useState(null); const publishedURL = `/p/${presentation?.pubmeta?.slug}`; const onPublish = async () => { try { setLoading(true); const { data } = await axios.post(`/api/p/${presentation.id}/publish`); const { pubmeta } = data; store.setPresentation({ ...presentation, pubmeta, isPublished: true, } as Presentation); } catch (e) { console.error(e); createErrorToast("Error publishing the presentation. Try again later"); } finally { setLoading(false); } }; const onUnPublish = async () => { setLoading(true); try { await axios.post(`/api/p/${presentation.id}/unpublish`); store.setPresentation({ ...presentation, isPublished: false, } as Presentation); } catch (e) { console.error(e); createErrorToast("Something went wrong. Try again later."); } finally { setLoading(false); } }; const onSave = async () => { setSaved(true); try { await axios.patch(`/api/p/${presentation.id}/slug`, { slug }); store.setPresentation({ ...presentation, pubmeta: { ...presentation.pubmeta, slug, }, } as Presentation); } catch (e) { if (typeof e?.response?.data?.message === "string") { setError(e?.response?.data?.message); } else { createErrorToast("Something went wrong. Try again later."); } } finally { setSaved(false); } }; useEffect(() => { if (slug.trim().length === 0) { setError("should not be empty."); } else if (!isValidSlug(slug)) { setError( "should contain only alphabets, numbers, - and _ . should start with a alphabet." ); } else { setError(null); } }, [slug]); useEffect(() => { if (presentation?.pubmeta?.slug) setSlug(presentation?.pubmeta.slug); }, [presentation?.pubmeta?.slug]); if (typeof window === "undefined") return null; return ( <Modal isOpen={isOpen} onClose={onClose} size="lg"> <ModalOverlay /> <ModalContent> <ModalHeader>Publish Settings</ModalHeader> <ModalCloseButton /> <Text bg="#fafafa" pt="5" pb="5" pl="6" borderWidth="1px" borderColor="#e2e8f0" width="100%" > {presentation.isPublished ? ( <> Your Presentation is publised at{" "} <Box as="a" target="_blank" href={publishedURL}> <strong>{window.location.origin + publishedURL}</strong> </Box> </> ) : ( <> {" "} You&apos;re presentation is not published. You can publish it as a webpage.{" "} </> )} </Text> <ModalBody mt="4"> {presentation.isPublished ? ( <> <Text as="label" htmlFor="slug" fontSize="xs" style={{ letterSpacing: "0.15em" }} fontWeight="bold" > SLUG </Text> <Input focusBorderColor="black" placeholder="slug" mt="2" id="slug" value={slug} isInvalid={!isValidSlug(slug) || !!error} onChange={(e) => { setSlug(e.target.value); }} /> {error && ( <Text color="red" fontSize="sm" mt="1"> * {error} </Text> )} </> ) : null} </ModalBody> <ModalFooter> {!presentation.isPublished ? ( <PrimaryButton onClick={onPublish} isLoading={isLoading} disabled={isLoading} > Publish Now </PrimaryButton> ) : ( <> <PrimaryButton mr="3" onClick={onSave} isLoading={isSaving} disabled={ error !== null || isLoading || isSaving || slug.trim() === presentation?.pubmeta?.slug } _disabled={{ opacity: 0.6 }} > Save </PrimaryButton> <Button bg="white" variant="outline" _hover={{ bg: "#f6f6f6" }} isLoading={isLoading} disabled={isLoading} onClick={onUnPublish} > Un Publish </Button> </> )} </ModalFooter> </ModalContent> </Modal> ); }; export default PublishSettingsModal;
ArunMurugan78/mdslide
lib/exceptions/exception.ts
export interface Exception extends Error { code: number; }
ArunMurugan78/mdslide
pages/api/p/all.ts
import { NextApiHandler } from "next"; import { getSession, withApiAuthRequired } from "@auth0/nextjs-auth0"; import { getDb } from "lib/db/getDb"; import { Presentation } from "model/presentation"; import { catchErrors } from "lib/exceptions/catcherrors"; import { mapUnderscoreIdToId } from "lib/utils/mapUnderscoreId"; const handler: NextApiHandler = async function (req, res) { const { user } = getSession(req, res); const db = await getDb(); const collection = db.getCollection(Presentation); const presentations = await collection .find<Presentation>({ userEmail: user.email }) .sort({ createdAt: -1 }) .project({ title: 1, slides: { $slice: 1 } }) .toArray(); res.json( presentations .map((p) => ({ ...p, slides: undefined, coverSlide: p.slides[0], })) .map(mapUnderscoreIdToId) ); }; export default catchErrors(withApiAuthRequired(handler));
ArunMurugan78/mdslide
lib/db/getDb.ts
import * as mongo from "mongodb"; import Db from "./Db"; const client = new mongo.MongoClient( process.env.MONGO_URI || "mongodb://127.0.0.1:27017", {} ); let cachedDb: Db | null = null; export async function getDb(): Promise<Db> { if (cachedDb) { return cachedDb; } await client.connect(); console.log("[DB]: connected"); const db = client.db(process.env.MONGO_DATABASE || "mdslide_dev"); const database = new Db(db); cachedDb = database; return database; }
ArunMurugan78/mdslide
model/presentation.ts
<reponame>ArunMurugan78/mdslide import { Entity } from "@lib/db/entity"; import type { Slide } from "./slide"; import type { Presentation as IPresentation } from "./interfaces/presentation"; @Entity({ name: "presentation" }) export class Presentation implements IPresentation { id: string; title: string; // Uniquely identifies the user. // Currently the best way to uniquely identify the user. userEmail: string; slides: Slide[]; isPublished: boolean; createdAt: string; pubmeta?: { slug: string }; } export default Presentation;
ArunMurugan78/mdslide
components/SlideNavigator/components/NewSlideButton/index.tsx
<filename>components/SlideNavigator/components/NewSlideButton/index.tsx<gh_stars>10-100 import { FC } from "react"; import { IconButton } from "@chakra-ui/react"; import { AddIcon } from "@chakra-ui/icons"; export interface NewSlideButtonProps { onClick: () => void; } export const NewSlideButton: FC<NewSlideButtonProps> = (props) => { const { onClick } = props; return ( <IconButton colorScheme="black" height="57.25px" opacity="1" borderRadius="3px" width="100px" onClick={onClick} variant="outline" _hover={{ bg: "black", color: "white", opacity: 1, boxShadow: "none" }} _focus={{ bg: "black", color: "white", opacity: 1, boxShadow: "none" }} aria-label="Add new Slide" icon={<AddIcon />} /> ); }; export default NewSlideButton;
ArunMurugan78/mdslide
components/StartPresentationModeButton/index.tsx
<gh_stars>10-100 import { FC } from "react"; import { IconButton, Icon, IconButtonProps, Tooltip } from "@chakra-ui/react"; import { useStore } from "lib/stores/presentation"; export type StartPresentationModeButtonProps = Omit< IconButtonProps, "aria-label" >; export const StartPresentationModeButton: FC<StartPresentationModeButtonProps> = (props) => { const startPresentationMode = useStore( (store) => store.startPresentationMode ); return ( <Tooltip label="Start Presenting" aria-label="Start Presenting"> <IconButton aria-label="start presenting" onClick={startPresentationMode} bg="transparent" size="sm" icon={ <Icon height="30px" viewBox="0 0 24 24" width="30px" fill="gray.500" > <g> <rect fill="none" height="24" width="24" /> <path d="M19,3H5C3.89,3,3,3.9,3,5v14c0,1.1,0.89,2,2,2h14c1.1,0,2-0.9,2-2V5C21,3.9,20.11,3,19,3z M19,19H5V7h14V19z M13.5,13 c0,0.83-0.67,1.5-1.5,1.5s-1.5-0.67-1.5-1.5c0-0.83,0.67-1.5,1.5-1.5S13.5,12.17,13.5,13z M12,9c-2.73,0-5.06,1.66-6,4 c0.94,2.34,3.27,4,6,4s5.06-1.66,6-4C17.06,10.66,14.73,9,12,9z M12,15.5c-1.38,0-2.5-1.12-2.5-2.5c0-1.38,1.12-2.5,2.5-2.5 c1.38,0,2.5,1.12,2.5,2.5C14.5,14.38,13.38,15.5,12,15.5z" /> </g> </Icon> } {...props} /> </Tooltip> ); }; export default StartPresentationModeButton;
ArunMurugan78/mdslide
lib/decorators/patch-field.ts
<filename>lib/decorators/patch-field.ts import { ObjectId, UpdateFilter } from "mongodb"; import { NextApiRequest, NextApiResponse } from "next"; import { getSession, withApiAuthRequired } from "@auth0/nextjs-auth0"; import { getDb } from "lib/db/getDb"; import { Presentation } from "model/presentation"; import { BadRequestException } from "lib/exceptions/common"; import { catchErrors } from "lib/exceptions/catcherrors"; import { UnAuthorizedException, NotFoundException, } from "lib/exceptions/common"; export const patchFieldApi = <T, V>( property: string, getUpdateFilter: (newValue: V, meta: any) => UpdateFilter<T> | Partial<T> ) => catchErrors( withApiAuthRequired(async function ( req: NextApiRequest, res: NextApiResponse ) { const { user } = getSession(req, res); if (req.method !== "PATCH") { throw new NotFoundException(); } const { [property]: newPropertyValue, meta } = req.body; const { pid } = req.query; if (!newPropertyValue) throw new BadRequestException(`${property} should not be empty`); const db = await getDb(); const id = new ObjectId(pid as string); const collection = db.getCollection(Presentation); const { userEmail, [property]: oldPropertyValue } = (await collection.findOne<Presentation>( { _id: id }, { projection: { userEmail: 1, [property]: 1 } } )) as Record<string, any>; if (typeof oldPropertyValue !== typeof newPropertyValue) { throw new BadRequestException("type mismatch"); } if (userEmail !== user.email) throw new UnAuthorizedException(); await collection.updateOne( { _id: id }, getUpdateFilter(newPropertyValue, meta) ); res.json(200); }) );
ArunMurugan78/mdslide
components/PrimayButton/index.tsx
import { chakra, Button } from "@chakra-ui/react"; export const PrimaryButton = chakra(Button, { baseStyle: { bg: "black", color: "white", borderRadius: "6px", border: "1px solid black", _hover: { bg: "white", color: "black", "&:disabled": { bg: "black", color: "white", }, }, _focus: { bg: "white", color: "black", }, _disabled: { bg: "black", color: "white", }, }, }); export default PrimaryButton;
ArunMurugan78/mdslide
lib/createErrorToast.tsx
<reponame>ArunMurugan78/mdslide import { createStandaloneToast, Flex } from "@chakra-ui/react"; import { InfoIcon } from "@chakra-ui/icons"; import theme from "config/theme"; const toast = createStandaloneToast({ theme }); export const createErrorToast = (text: string) => toast({ status: "error", isClosable: true, title: text, duration: 5000, position: "bottom-right", }); export default createErrorToast;
ArunMurugan78/mdslide
pages/api/p/[pid]/slug.ts
import { NextApiHandler } from "next"; import { ObjectId, MongoServerError } from "mongodb"; import { getSession, withApiAuthRequired } from "@auth0/nextjs-auth0"; import { getDb } from "lib/db/getDb"; import { isValidSlug } from "utils/isValidSlug"; import { Presentation } from "model/presentation"; import { catchErrors } from "lib/exceptions/catcherrors"; import { BadRequestException } from "lib/exceptions/common"; const handler: NextApiHandler = async (req, res) => { const { user } = getSession(req, res); const { pid } = req.query as { pid: string }; const payload = req.body; if (!payload || !isValidSlug(payload.slug)) { throw new BadRequestException(); } const db = await getDb(); const collection = db.getCollection(Presentation); try { await collection.updateOne( { _id: new ObjectId(pid), userEmail: user.email }, { $set: { "pubmeta.slug": payload.slug, }, } ); } catch (e) { if (e instanceof MongoServerError && e.code === 11000) { throw new BadRequestException("not available. try something else"); } else { throw e; } } res.status(200).send("OK"); }; export default catchErrors(withApiAuthRequired(handler));
ArunMurugan78/mdslide
pages/app/index.tsx
import useSWR from "swr"; import axios from "axios"; import { useRouter } from "next/router"; import { useState } from "react"; import { withPageAuthRequired } from "@auth0/nextjs-auth0"; import { Container, Text, Box, Flex, Skeleton, Progress, } from "@chakra-ui/react"; import createErrorToast from "lib/createErrorToast"; import { HomeNavbar, Slide, LoadFonts, Meta } from "components"; const fetcher = (url) => axios.get(url).then((res) => res.data); export function Index() { const router = useRouter(); const { data, error } = useSWR("/api/p/all", fetcher); const [isNextRouteLoading, setNextRouteLoading] = useState(false); if (error) { console.error(error); createErrorToast("Something went wrong. Try again later"); } const isLoading = !data; const presentations = data ?? [{}, {}, {}]; const fontFamilies = presentations .map((p) => p?.coverSlide?.fontFamily) .filter(Boolean); return ( <Box bg="#fafafa" minHeight="100vh"> <Meta title="Dashboard" url={"https://mdslide.vercel.app/app"} /> <LoadFonts fontFamilies={fontFamilies} /> {isNextRouteLoading ? ( <Progress size="xs" colorScheme="blackAlpha" isIndeterminate /> ) : null} <HomeNavbar isDisabled={isNextRouteLoading} /> <Container maxW="container.xl"> <Text style={{ letterSpacing: "0.15em" }} fontWeight="bold" mt={"40px"} fontSize="xs" > YOUR PRESENTATIONS </Text> <Flex mt="30px" wrap={"wrap"}> {presentations.length === 0 && !isLoading ? ( <Text color="gray.500" fontSize="md"> Your presentations show up here. </Text> ) : null} {presentations.map((presentation, idx) => ( <Box as="button" onClick={() => { if (isLoading) return; setNextRouteLoading(true); router.push(`/app/${presentation.id}`); }} p="2" borderRadius="8px" mr="6" disabled={isNextRouteLoading} mb="6" key={idx} width="auto" bg="white" opacity={isNextRouteLoading ? 0.8 : 1} tabIndex={0} boxShadow="base" _hover={{ boxShadow: isNextRouteLoading ? "base" : "lg" }} _focus={{ boxShadow: isNextRouteLoading ? "base" : "lg", outline: "black solid 2px", }} > {isLoading ? ( <Skeleton width={100 * 3 + "px"} height={56.25 * 3 + "px"} /> ) : ( <> <Slide constraintSize={{ width: 300, height: 1000 }} borderWidth="1px" borderColor="gray.100" fontFamily={presentation.coverSlide.fontFamily ?? "Inter"} bgColor={presentation.coverSlide.bgColor} fontColor={presentation.coverSlide.fontColor} mdContent={presentation.coverSlide.mdContent} /> </> )} {isLoading ? ( <Skeleton mt={"10px"} p="5px" width="100%" height="20px" /> ) : ( <Text mt={"10px"} p="5px" ml="5px" textOverflow="ellipsis" overflow="hidden" whiteSpace="nowrap" maxWidth="300px" > {presentation?.title} </Text> )} </Box> ))} </Flex> </Container> </Box> ); } export default withPageAuthRequired(Index);
ArunMurugan78/mdslide
lib/stores/presentation/updateSlideRemote.ts
import axios from "axios"; import debounce from "debounce"; import Slide from "model/slide"; import createErrorToast from "lib/createErrorToast"; import { isTempId } from "lib/utils/getTempId"; export const updateSlideRemote = debounce( (slide: Slide, pid: string, callback: (promise: Promise<any>) => void) => { const sid = slide.id; if (isTempId(sid)) { return; } const promise = axios.patch(`/api/p/${pid}/slide/${sid}`, { slide, }); promise.catch(() => { createErrorToast("Error saving the slide"); // TODO set the icon from saving to unsaved }); callback(promise); }, 300 );
ArunMurugan78/mdslide
components/Slide/getScaleFactor.ts
import { getSlideSize } from "./getSlideSize"; export const getScaleFactor = (constraint: { width: number; height: number; }): number => { const { width } = getSlideSize(constraint); return width / 1920; };
ArunMurugan78/mdslide
lib/createInfoToast.tsx
<gh_stars>10-100 import { createStandaloneToast, Flex } from "@chakra-ui/react"; import { InfoIcon } from "@chakra-ui/icons"; import theme from "config/theme"; const toast = createStandaloneToast({ theme }); export const createInfoToast = (text: string) => toast({ status: "info", isClosable: true, title: "", duration: 4000, render() { return ( <Flex alignItems="center" color="white" bg="black" p="5"> <InfoIcon mr="4" /> {text} </Flex> ); }, }); export default createInfoToast;
ArunMurugan78/mdslide
components/AccountActions/index.tsx
<reponame>ArunMurugan78/mdslide<gh_stars>10-100 import { FC } from "react"; import { Menu, MenuButton, MenuItem, Avatar, IconButton, MenuList, MenuButtonProps, IconButtonProps, } from "@chakra-ui/react"; import { useUser } from "@auth0/nextjs-auth0"; export type AccountActionsProps = { size: "sm" | "md"; isDisabled?: boolean; } & MenuButtonProps & IconButtonProps; export const AccountActions: FC<AccountActionsProps> = (props) => { const { isDisabled, size, ...rest } = props; const { user } = useUser(); const iconSize = size === "sm" ? "27px" : "37px"; return ( <Menu> <MenuButton as={IconButton} _focus={{ outline: "black solid 2px" }} disabled={isDisabled} bg="transparent" size={size} icon={ <Avatar width={iconSize} name={user?.name} height={iconSize} src={user?.picture} /> } {...rest} > Actions </MenuButton> <MenuList> <MenuItem as={"a"} href="/api/auth/logout"> Logout </MenuItem> </MenuList> </Menu> ); }; export default AccountActions;
ArunMurugan78/mdslide
pages/p/[slug].tsx
import { ObjectId } from "mongodb"; import { FC, useState, useEffect } from "react"; import { GetServerSideProps } from "next"; import { Flex, Spacer } from "@chakra-ui/react"; import PresentationInterface from "model/presentation"; import PresentationModel from "model/presentation"; import { useStore } from "lib/stores/presentation"; import { getDb } from "lib/db/getDb"; import { Logo, FullScreenPresentation, Slide, LoadFonts, NextSlideButton, PrevSlideButton, StartPresentationModeButton, Meta, } from "components"; import { keyListeners } from "lib/setupKeyListeners"; import "@uiw/react-md-editor/dist/markdown-editor.css"; import "@uiw/react-markdown-preview/dist/markdown.css"; import { mapUnderscoreIdToId } from "@lib/utils/mapUnderscoreId"; interface PageProps { presentation: PresentationInterface; } const PublishedPresentationPage: FC<PageProps> = (props) => { const { presentation } = props; const store = useStore(); const slides = store.presentation.slides; const currentSlideIndex = store.currentSlideIdx; const currentSlide = slides[currentSlideIndex]; const IsPresentationMode = store.isPresentationMode; const [constraint, setConstraint] = useState({ height: 0, width: 0 }); const fontFamilies = slides.map((s) => s.fontFamily); useEffect(() => { const setScreenSize = () => setConstraint({ height: window.innerHeight - 200, width: window.innerWidth - 100, }); window.addEventListener("resize", setScreenSize); setScreenSize(); store.setPresentation(presentation); const { cleanUp, setUpKeyListener } = keyListeners(); setUpKeyListener(); return cleanUp; }, []); return ( <> <Meta title={presentation.title} url={`https://mdslide.vercel.app/p/${presentation.id}`} /> {!IsPresentationMode ? ( <> <LoadFonts fontFamilies={fontFamilies} /> <Flex as="nav" height="70px" alignItems="center" p="5" width="100%" borderWidth="1px" borderColor="#e2e8f0" > <Logo fontSize="xl" /> <Spacer /> <StartPresentationModeButton ml="20px" /> </Flex> <Flex alignItems="center" justifyContent="center" bg="#f6f5f5" height="calc(100vh - 70px)" > <PrevSlideButton /> {constraint.height !== 0 ? ( <Slide constraintSize={constraint} mdContent={currentSlide.mdContent} bgColor={currentSlide.bgColor} fontColor={currentSlide.fontColor} height={constraint.height} fontFamily={currentSlide.fontFamily} width={constraint.width} boxShadow="lg" /> ) : null} <NextSlideButton /> </Flex> </> ) : ( <FullScreenPresentation /> )} </> ); }; export const getServerSideProps: GetServerSideProps = async (ctx) => { const { query } = ctx; const { slug } = query as { slug: string }; const db = await getDb(); const collection = db.getCollection(PresentationModel); const presentation = await collection.findOne( { pubmeta: { slug }, isPublished: true }, { projection: { slides: 1, title: 1 } } ); if (!presentation) { return { redirect: { destination: "/not-found", permanent: false, }, }; } const { _id, ...payload } = presentation as PresentationModel & { _id: ObjectId; }; const props: PageProps = { presentation: { ...payload, id: _id.toHexString(), slides: payload.slides.map(mapUnderscoreIdToId), }, }; return { props, }; }; export default PublishedPresentationPage;
ArunMurugan78/mdslide
lib/stores/presentation/types.ts
<reponame>ArunMurugan78/mdslide import Presentation from "model/interfaces/presentation"; import Slide from "model/slide"; export type MapToPartial<T> = (value: T) => Partial<T>; export type State = { currentSlideIdx: number; presentation: Pick< Presentation, "slides" | "isPublished" | "pubmeta" | "title" > & Partial<Pick<Presentation, "id">>; lastSaveRequestPromise: Promise<any> | null; isSaving: boolean; isPresentationMode: boolean; }; export type Actions = { getCurrentSlide: () => Slide; goToSlide: (index: number) => void; updateSlide: (id: string, map: MapToPartial<Slide>) => void; updateCurrentSlide: (map: MapToPartial<Slide>) => void; goToNextSlide: () => void; goToPrevSlide: () => void; addNewSlide: () => void; setPresentation: (presentation: Presentation) => void; startPresentationMode: () => void; stopPresentationMode: () => void; updateTitle: (newTitle: string) => void; deleteSlide: (id: string) => void; deleteCurrentSlide: () => void; setLastSaveRequestPromise: (promise: Promise<any> | null) => void; };
ArunMurugan78/mdslide
lib/utils/mapUnderscoreId.ts
<reponame>ArunMurugan78/mdslide import { ObjectId } from "mongodb"; export function mapUnderscoreIdToId<T>(doc: T & { _id: ObjectId }) { return { ...doc, id: doc._id.toHexString(), _id: null }; }
ArunMurugan78/mdslide
lib/setupKeyListeners.ts
import { KeyboardEvent } from "react"; import { useStore } from "lib/stores/presentation"; export function keyListeners() { const keyDownHandler: (e: Event) => void = (e: Event) => { const editorEl = document.querySelector<HTMLTextAreaElement>( ".w-md-editor-text-input" ); const key = (e as unknown as KeyboardEvent)?.key; if (key === "Delete") { const { deleteCurrentSlide } = useStore.getState(); deleteCurrentSlide(); return; } if (document.activeElement === editorEl) { return; } switch (key) { case " ": case "ArrowRight": const { goToNextSlide } = useStore.getState(); goToNextSlide(); break; case "ArrowLeft": const { goToPrevSlide } = useStore.getState(); goToPrevSlide(); break; } }; const setUpKeyListener = () => window.addEventListener("keydown", keyDownHandler); const cleanUp = () => window.removeEventListener("keydown", keyDownHandler); return { setUpKeyListener, cleanUp }; }
ArunMurugan78/mdslide
lib/utils/getTempId.ts
import { v4 as uuidv4 } from "uuid"; const ids = new Set<string>(); export const getUUID = (): string => { const randId = uuidv4(); if (ids.has(randId)) { return getUUID(); } ids.add(randId); return randId; }; export const TEMP_ID_PREFIX = "_TEMP_"; export const getTempId = (): string => { return TEMP_ID_PREFIX + getUUID(); }; export const isTempId = (id: string): boolean => id.startsWith(TEMP_ID_PREFIX);
ArunMurugan78/mdslide
pages/api/p/new.ts
import { ObjectId } from "mongodb"; import type { NextApiRequest, NextApiResponse, NextApiHandler } from "next"; import { withApiAuthRequired, getSession } from "@auth0/nextjs-auth0"; import Slide from "model/slide"; import { getDb } from "lib/db/getDb"; import { Presentation } from "model/presentation"; import { catchErrors } from "lib/exceptions/catcherrors"; const handler: NextApiHandler = async function ( req: NextApiRequest, res: NextApiResponse<{ id: string }> ) { const { user } = getSession(req, res); if (!user?.email) { throw new Error("User Email required"); } const db = await getDb(); const collection = db.getCollection(Presentation); const newPresentation = new Presentation(); newPresentation.slides = [ { _id: new ObjectId(), id: "", mdContent: `# Slide One \n\n by ${user.name ?? "Unknown"}`, bgColor: "#fff", fontColor: "#000", fontFamily: "Inter", } as Slide, ]; newPresentation.title = "Untitled"; newPresentation.userEmail = user.email; newPresentation.createdAt = new Date().toISOString(); const { insertedId } = await collection.insertOne(newPresentation); res.json({ id: insertedId.toHexString() }); }; export default catchErrors(withApiAuthRequired(handler));
ArunMurugan78/mdslide
lib/db/Db.ts
import * as mongo from "mongodb"; export class Db { constructor(private db: mongo.Db) {} getCollectionName<T>(doc: T): string { const collectionName = Reflect.getMetadata("entity", doc); if (!collectionName) { throw new Error("Entity must decorated @Entity"); } return collectionName; } async insert<T>(doc: T): Promise<T & { id: string }> { const collectionName = this.getCollectionName(doc); const { insertedId } = await this.db .collection(collectionName) .insertOne(doc); return { ...doc, id: insertedId.toHexString() }; } getCollection<T extends Function>( entity: T ): mongo.Collection<mongo.Document> { const collectionName = this.getCollectionName(entity); return this.db.collection(collectionName); } } export default Db;
ArunMurugan78/mdslide
components/Slide/getSlideSize.ts
type Size = { width: number; height: number }; const getHeight = (width: number) => (9 * width) / 16; const getWidth = (height: number) => (16 * height) / 9; export const getSlideSize = (constraint: Size): Size => { let { height, width } = constraint; if (getHeight(width) > height) { width = getWidth(height); } else { height = getHeight(width); } return { height, width }; };
ArunMurugan78/mdslide
components/EditorPanel/index.tsx
import dynamic from "next/dynamic"; import MDEditor from "@uiw/react-md-editor"; import { FC } from "react"; import { Box, Text, Flex, Tooltip } from "@chakra-ui/react"; import { InfoIcon } from "@chakra-ui/icons"; import ColorPicker from "components/ColorPicker"; import "@uiw/react-md-editor/dist/markdown-editor.css"; import "@uiw/react-markdown-preview/dist/markdown.css"; const FontPicker = dynamic(() => import("font-picker-react"), { ssr: false }); export interface EditorPanelProps { value: string; bgColor: string; fontColor: string; fontFamily: string; setValue: (value: string) => any; setBgColor: (value: string) => any; setFontColor: (value: string) => any; setFontFamily: (value: string) => any; } export const EditorPanel: FC<EditorPanelProps> = (props) => { const { value, setValue, bgColor, setBgColor, fontColor, setFontColor, fontFamily, setFontFamily, } = props; return ( <Box width="100%" height="100%" overflow="hidden"> <Box width="100%" p="20px" height="200px" fontSize="xs" color="#495464" bg="#fafafa" > <Text className="spaced-bold-text" ml="0.5" mr="2" mt="0.7"> APPEARANCE </Text> <Flex mt="18px" width="100%"> <ColorPicker id="bg-color-picker" aria-label="Background Color Picker" label="BG" value={bgColor} setValue={setBgColor} /> <ColorPicker id="font-color-picker" aria-label="Font Color Picker" label="A" value={fontColor} setValue={setFontColor} /> </Flex> {typeof window !== "undefined" ? ( // @ts-ignore <FontPicker apiKey={process.env.NEXT_PUBLIC_GOOGLE_FONT_API_KEY} activeFontFamily={fontFamily} limit={50} sort="popularity" onChange={(nextFont) => { if (nextFont.family !== fontFamily) { setFontFamily(nextFont.family); } }} /> ) : null} </Box> <Box p="20px" width="100%" borderTop="1px" borderColor="gray.200" height="100%" > <Flex pb="3" alignItems="center" fontSize="xs" color="#495464"> <Text style={{ letterSpacing: "0.15em" }} fontWeight="bold" ml="0.5" mr="2" mt="0.7" > EDITOR{" "} </Text> <Tooltip label="This editor uses Markdown format. To learn more about it, click " aria-label="This editor uses Markdown format. To learn more about it, click " > <a target="_blank" href="https://www.markdownguide.org/basic-syntax/" rel="noreferrer" > <InfoIcon color="#BBBFCA" fontSize="xs" /> </a> </Tooltip> </Flex> <MDEditor fullscreen={false} autoFocus={true} enableScroll={true} preview={"edit"} value={value} color="gray" toolbarHeight={38} textareaProps={{ placeholder: "Start Typing..." }} onChange={(value) => setValue(value ?? "")} /> </Box> </Box> ); }; export default EditorPanel;
ArunMurugan78/mdslide
pages/api/p/[pid]/index.ts
import { ObjectId } from "mongodb"; import { withApiAuthRequired, getSession } from "@auth0/nextjs-auth0"; import type { NextApiRequest, NextApiResponse, NextApiHandler } from "next"; import { UnAuthorizedException, InternalServerException, NotFoundException, } from "lib/exceptions/common"; import { getDb } from "lib/db/getDb"; import { Presentation } from "model/presentation"; import { catchErrors } from "lib/exceptions/catcherrors"; import { mapUnderscoreIdToId } from "lib/utils/mapUnderscoreId"; const handler: NextApiHandler = async function ( req: NextApiRequest, res: NextApiResponse ) { const { user } = getSession(req, res); if (!user?.email) { console.error("got empty email from session"); throw new InternalServerException(); } const db = await getDb(); const collection = db.getCollection(Presentation); const presentation = await collection.findOne< Presentation & { _id: ObjectId } >({ userEmail: { $eq: user.email, }, }); if (!presentation) { throw new NotFoundException(); } if (presentation.userEmail !== user.email) { throw new UnAuthorizedException(); } res.json(mapUnderscoreIdToId(presentation)); }; export default catchErrors(withApiAuthRequired(handler));
ArunMurugan78/mdslide
pages/app/[pid].tsx
<gh_stars>10-100 import Head from "next/head"; import debounce from "debounce"; import { useEffect } from "react"; import { ObjectId } from "mongodb"; import { GetServerSideProps } from "next"; import { withPageAuthRequired, getSession } from "@auth0/nextjs-auth0"; import { Grid, GridItem } from "@chakra-ui/react"; import PresentationModel from "model/presentation"; import PresentationType from "model/interfaces/presentation"; import { EditorPanel, EditorNavbar, PreviewSpace, SlideNavigator, FullScreenPresentation, } from "components"; import { getDb } from "lib/db/getDb"; import { Slide } from "model/slide"; import { useStore } from "lib/stores/presentation"; import { keyListeners } from "lib/setupKeyListeners"; import { mapUnderscoreIdToId } from "@lib/utils/mapUnderscoreId"; interface EditorPageProps { presentation: PresentationType; pid: string; } export function EditorPage(props: EditorPageProps) { const { presentation } = props; const store = useStore(); const slides = useStore((state) => state.presentation.slides); const currentSlide = slides[store.currentSlideIdx]; const getUpdateCurrentSlideFn = ( field: keyof Slide, shouldDebounce = false ) => { const updateFn = (value: string) => store.updateCurrentSlide(() => ({ [field]: value })); if (shouldDebounce) { return debounce(updateFn, 300); } return updateFn; }; const updateBgColor = getUpdateCurrentSlideFn("bgColor", true); const updateFontColor = getUpdateCurrentSlideFn("fontColor", true); const updateMdContent = getUpdateCurrentSlideFn("mdContent"); const updateFontFamily = getUpdateCurrentSlideFn("fontFamily"); useEffect(() => { store.setPresentation(presentation); const { cleanUp, setUpKeyListener } = keyListeners(); setUpKeyListener(); return cleanUp; }, []); return ( <> <Head> <title>{presentation.title}</title> </Head> {!store.isPresentationMode ? ( <> <EditorNavbar /> <Grid height={"calc(100vh - 70px)"} templateRows="repeat(12, 1fr)" templateColumns="repeat(3, 1fr)" as="main" > <GridItem rowSpan={12} colSpan={1}> <EditorPanel value={currentSlide.mdContent} bgColor={currentSlide.bgColor} setBgColor={updateBgColor} fontColor={currentSlide.fontColor} setFontColor={updateFontColor} setValue={updateMdContent} fontFamily={currentSlide.fontFamily} setFontFamily={updateFontFamily} /> </GridItem> <GridItem rowSpan={11} colSpan={2}> <PreviewSpace fontFamily={currentSlide.fontFamily} bgColor={currentSlide.bgColor} fontColor={currentSlide.fontColor} mdContent={currentSlide.mdContent} /> </GridItem> <GridItem rowSpan={1} colSpan={2}> <SlideNavigator onClickSlide={store.goToSlide} /> </GridItem> </Grid>{" "} </> ) : ( <FullScreenPresentation /> )} </> ); } export const getServerSideProps: GetServerSideProps<{}> = withPageAuthRequired({ async getServerSideProps(ctx) { const { req, res, params } = ctx; const pid = params["pid"]; const { user } = getSession(req, res); const db = await getDb(); const collection = db.getCollection(PresentationModel); const presentation = await collection.findOne<PresentationModel>({ userEmail: user.email, _id: new ObjectId(pid as string), }); if (!presentation) { return { redirect: { destination: "/not-found", permanent: false, }, }; } const { _id, ...payload } = presentation as PresentationModel & { _id: ObjectId; }; const props: EditorPageProps = { presentation: { ...payload, id: _id.toHexString(), slides: payload.slides.map(mapUnderscoreIdToId), }, pid: pid as string, }; return { props, }; }, }); export default EditorPage;
ArunMurugan78/mdslide
components/Logo/index.tsx
import { FC } from "react"; import { Text, TextProps } from "@chakra-ui/react"; export type LogoProps = TextProps; export const Logo: FC<LogoProps> = (props) => { return ( <Text fontSize="2xl" {...props}> <strong>MD</strong>SLIDE </Text> ); }; export default Logo;
ArunMurugan78/mdslide
components/PreviewSpace/getConstraint.ts
import type { Size } from "./Size"; export const getConstraint = (): Size => { if (typeof window === "undefined") return { width: 0, height: 0 }; const element = window.document.querySelector("#preview-space"); if (element) { return { width: element.getBoundingClientRect().width, height: element.getBoundingClientRect().height, }; } return { width: 0, height: 0 }; };
ArunMurugan78/mdslide
pages/index.tsx
import { FC, useEffect, useState } from "react"; import { useRouter } from "next/router"; import { Center, Text, Stack, Button } from "@chakra-ui/react"; import { ArrowForwardIcon } from "@chakra-ui/icons"; import Typewriter from "typewriter-effect/dist/core"; import { PrimaryButton, Meta } from "components"; const LandingPage: FC<{}> = () => { const router = useRouter(); const [completedTyping, setCompletedTyping] = useState(false); useEffect(() => { const el = document.querySelector("#title"); if (el) { const typewriter = new Typewriter(el, { delay: 150, }); typewriter .typeString("# **MD**SLIDE ") .pauseFor(400) .callFunction(() => { setCompletedTyping(true); }) .start(); } }, []); return ( <> <Meta title="MDSLIDE" url={"https://mdslide.vercel.app"} /> <Center height="100vh"> <Stack> <Center> {!completedTyping ? ( <Text fontSize="xl"> <div id="title"></div> </Text> ) : ( <Text fontSize="5xl"> <strong>MD</strong>SLIDE </Text> )} </Center> <Text mt="6" fontSize="2xl" textAlign="center"> Create Minimalistic Slide Presentations using <i>Markdown.</i> </Text> <Center p="3"> <PrimaryButton onClick={() => { router.push("/app"); }} href="/app" size="lg" p="8" m="2" rightIcon={<ArrowForwardIcon />} > Try Now </PrimaryButton> <Button onClick={() => { router.push("https://github.com/ArunMurugan78/mdslide"); }} href="github.com/ArunMurugan78" variant="outline" size="lg" p="8" m="2" _hover={{ bg: "#f6f6f6" }} leftIcon={ <svg stroke="currentColor" fill="currentColor" strokeWidth="0" version="1.1" viewBox="0 0 32 32" aria-hidden="true" focusable="false" height="1.5em" width="1.5em" xmlns="http://www.w3.org/2000/svg" > <path d="M16 5.343c-6.196 0-11.219 5.023-11.219 11.219 0 4.957 3.214 9.162 7.673 10.645 0.561 0.103 0.766-0.244 0.766-0.54 0-0.267-0.010-1.152-0.016-2.088-3.12 0.678-3.779-1.323-3.779-1.323-0.511-1.296-1.246-1.641-1.246-1.641-1.020-0.696 0.077-0.682 0.077-0.682 1.126 0.078 1.72 1.156 1.72 1.156 1.001 1.715 2.627 1.219 3.265 0.931 0.102-0.723 0.392-1.219 0.712-1.498-2.49-0.283-5.11-1.246-5.11-5.545 0-1.226 0.438-2.225 1.154-3.011-0.114-0.285-0.501-1.426 0.111-2.97 0 0 0.941-0.301 3.085 1.15 0.894-0.25 1.854-0.373 2.807-0.377 0.953 0.004 1.913 0.129 2.809 0.379 2.14-1.453 3.083-1.15 3.083-1.15 0.613 1.545 0.227 2.685 0.112 2.969 0.719 0.785 1.153 1.785 1.153 3.011 0 4.31-2.624 5.259-5.123 5.537 0.404 0.348 0.761 1.030 0.761 2.076 0 1.5-0.015 2.709-0.015 3.079 0 0.299 0.204 0.648 0.772 0.538 4.455-1.486 7.666-5.69 7.666-10.645 0-6.195-5.023-11.219-11.219-11.219z"></path> </svg> } > Github </Button> </Center> </Stack> </Center> </> ); }; export default LandingPage;
ArunMurugan78/mdslide
lib/exceptions/catcherrors.ts
import { getReasonPhrase, ReasonPhrases, StatusCodes } from "http-status-codes"; import { NextApiHandler, NextApiResponse } from "next"; import { NextApiRequest } from "next"; import { Exception } from "./exception"; export const catchErrors: <T>(handler: NextApiHandler<T>) => NextApiHandler<T> = (handler: NextApiHandler) => async (req: NextApiRequest, res: NextApiResponse) => { try { await handler(req, res); } catch (e: Exception | any) { if (typeof e?.code === "number") { res .status(e.code) .json({ message: e.message || getReasonPhrase(e.code) }); return; } console.error(e); res .status(StatusCodes.INTERNAL_SERVER_ERROR) .json({ message: ReasonPhrases.INTERNAL_SERVER_ERROR }); } };
ArunMurugan78/mdslide
components/ColorPicker/index.tsx
import { FC } from "react"; import { Flex, Box } from "@chakra-ui/react"; export interface ColorPickerProps { id: string; value: string; label: string; "aria-label": string; setValue: (value: string) => void; } export const ColorPicker: FC<ColorPickerProps> = (props) => { const { value, setValue, label, id, "aria-label": ariaLabel } = props; return ( <Flex mr="13px" direction="column" alignItems="center" width="40px"> <Box border="1px" borderColor="gray.300" width="40px" height="40px" bg={value} borderRadius="5px" > <Box opacity="0" as="input" id={id} value={value} type="color" width="100%" height="100%" onChange={(e) => { setValue((e.target as any)?.value || value); }} /> </Box> <label htmlFor={id} aria-label={ariaLabel}> {label} </label> </Flex> ); }; export default ColorPicker;
ArunMurugan78/mdslide
pages/_app.tsx
<gh_stars>10-100 import type { AppProps } from "next/app"; import { ChakraProvider } from "@chakra-ui/react"; import { UserProvider } from "@auth0/nextjs-auth0"; import theme from "config/theme"; import "focus-visible/dist/focus-visible"; import "styles/global.css"; import "styles/editor.css"; import "styles/md-preview.css"; function MyApp({ Component, pageProps }: AppProps) { return ( <ChakraProvider resetCSS theme={theme}> <UserProvider> <Component {...pageProps} /> </UserProvider> </ChakraProvider> ); } export default MyApp;
ArunMurugan78/mdslide
components/FullScreenPresentation/index.tsx
<reponame>ArunMurugan78/mdslide<gh_stars>10-100 import { FC, useEffect } from "react"; import { Box, Text, IconButton, Icon } from "@chakra-ui/react"; import Slide from "components/Slide"; import LoadFonts from "components/LoadFonts"; import createErrorToast from "lib/createErrorToast"; import createToast from "lib/createInfoToast"; import { useStore } from "lib/stores/presentation"; export interface FullScreenPresentationProps {} export const FullScreenPresentation: FC<FullScreenPresentationProps> = ( props ) => { const slides = useStore((state) => state.presentation.slides); const currentSlideIndex = useStore((state) => state.currentSlideIdx); const onClose = useStore((store) => store.stopPresentationMode); const currentSlide = slides[currentSlideIndex]; useEffect(() => { document.body.onfullscreenchange = () => { if (document.fullscreenElement !== document.body) { onClose(); } }; document.body.requestFullscreen().catch((e) => { console.error(e); onClose(); createErrorToast("Unable to start fullscreen mode"); }); createToast("Use Left and Right Arrow keys to navigate"); }, []); return ( <> <LoadFonts fontFamilies={slides.map((s) => s.fontFamily)} /> <Box bg={currentSlide.bgColor} width="100vw" height="100vh" display="flex" alignItems="center" justifyContent="center" position="fixed" top="0" left="0" overflow="hidden" > <IconButton aria-label="exit presentation mode" position="fixed" top="5" left="5" bg="transparent" _hover={{ bg: "transparent", border: "1px solid " + currentSlide.fontColor, }} zIndex={1} onClick={() => { document.exitFullscreen().finally(() => { onClose(); }); }} > <Icon height="24px" viewBox="0 0 24 24" width="24px"> <path d="M0 0h24v24H0z" fill="none" /> <path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z" fill={currentSlide.fontColor} /> </Icon> </IconButton> <Text position="fixed" top="5" zIndex={1} color={currentSlide.fontColor} right="5" > {currentSlideIndex + 1}/{slides.length} </Text> <Slide constraintSize={{ width: window.screen.width, height: window.screen.height, }} fontFamily={currentSlide.fontFamily} bgColor={currentSlide.bgColor} fontColor={currentSlide.fontColor} mdContent={currentSlide.mdContent} height={window.screen.height} width={window.screen.width} /> </Box> </> ); };
ArunMurugan78/mdslide
components/LoadFonts/index.tsx
import { FC, useEffect } from "react"; import Head from "next/head"; import { useAtom } from "jotai"; import { fontFaceTextsAtom, loadedFontFamiliesAtom, } from "lib/atoms/LoadedFontFaces"; export interface LoadFontsProps { fontFamilies: string[]; } export const fetchFontFace = (fontFamilies: string[]): Promise<string> => fetch( `https://fonts.googleapis.com/css?family=${fontFamilies .map((f) => f + ":regular") .join("|")}` ).then((r) => r.text()); export const LoadFonts: FC<LoadFontsProps> = (props) => { const { fontFamilies: fontFamilesProps } = props; const [fontFamiles] = useAtom(loadedFontFamiliesAtom); const [fontFaceText, setFontFaceText] = useAtom(fontFaceTextsAtom); const loadFonts = (fontFamiles: string[]) => { if (fontFamiles.length === 0) return; fetchFontFace(fontFamiles) .then((fontFace) => setFontFaceText((f) => f + "\n" + fontFace)) .catch((e) => console.error("Failed to fetch font faces: ", e)); }; useEffect(() => { console.log(fontFamilesProps); const notLoadedFontFamilies: string[] = []; for (const fontFamily of fontFamilesProps.map((s) => s.trim())) { if (!fontFamiles.has(fontFamily)) { fontFamiles.add(fontFamily); notLoadedFontFamilies.push(fontFamily); } } loadFonts(notLoadedFontFamilies); }, [fontFamilesProps]); return ( <> <Head> <style id="font-families">{fontFaceText}</style> </Head> </> ); }; export default LoadFonts;
ArunMurugan78/mdslide
lib/stores/presentation/index.ts
import create from "zustand"; import Slide from "model/slide"; import { getTempId } from "lib/utils/getTempId"; import { updateSlideRemote } from "./updateSlideRemote"; import { updateRemoteTitle } from "./updateRemoteTitle"; import { deleteSlideRemote } from "./deleteSlide"; import { createInfoToast } from "lib/createInfoToast"; import type { Actions, State } from "./types"; import { createNewSlide } from "./createNewSlide"; const defaultSlideValue: Slide = { id: "", fontColor: "black", bgColor: "white", mdContent: "# Slide", fontFamily: "Inter", }; export const useStore = create<State & Actions>((set, get) => ({ currentSlideIdx: 0, presentation: { slides: [defaultSlideValue], isPublished: false, title: "Untitled", }, lastSaveRequestPromise: null, isSaving: false, isPresentationMode: false, getCurrentSlide: () => get().presentation.slides[get().currentSlideIdx], goToSlide: (index: number) => { const { presentation: { slides }, } = get(); if (index >= slides.length || index < 0) return; set({ currentSlideIdx: index }); }, goToNextSlide: () => { const { goToSlide, currentSlideIdx } = get(); goToSlide(currentSlideIdx + 1); }, goToPrevSlide: () => { const { goToSlide, currentSlideIdx } = get(); goToSlide(currentSlideIdx - 1); }, updateSlide: (id: string, map: (slide: Slide) => Partial<Slide>) => { const { presentation, setLastSaveRequestPromise } = get(); const { slides } = presentation; const pid = presentation.id; const idx = slides.findIndex((s) => s.id === id); if (idx === -1) return; const partialSlide = map(slides[idx]); const slide = { ...slides[idx], ...partialSlide }; updateSlideRemote(slide, pid, setLastSaveRequestPromise); set({ presentation: { ...presentation, slides: [...slides.slice(0, idx), slide, ...slides.slice(idx + 1)], }, isSaving: true, }); }, updateCurrentSlide: (map: (slide: Slide) => Partial<Slide>) => { const { currentSlideIdx, updateSlide, presentation: { slides }, } = get(); updateSlide(slides[currentSlideIdx].id, map); }, addNewSlide: () => { const { presentation, updateSlide, setLastSaveRequestPromise } = get(); const { slides } = presentation; const lastSlide = slides[slides.length - 1]; const newSlide = { id: getTempId(), mdContent: `# Slide ${slides.length + 1} \n`, bgColor: lastSlide?.bgColor ?? "white", fontColor: lastSlide?.fontColor ?? "black", fontFamily: lastSlide?.fontFamily ?? "Inter", }; set({ currentSlideIdx: slides.length, presentation: { ...presentation, slides: [...slides, newSlide], }, }); createNewSlide( newSlide, presentation.id, updateSlide, setLastSaveRequestPromise ); }, setPresentation: (presentation) => { set({ presentation }); }, startPresentationMode: () => { set({ isPresentationMode: true }); }, stopPresentationMode: () => { set({ isPresentationMode: false }); }, updateTitle: (newTitle: string) => { const { presentation, isSaving, setLastSaveRequestPromise } = get(); const isInvalid = !newTitle || newTitle?.trim() === ""; set({ presentation: { ...presentation, title: newTitle }, isSaving: isSaving || !isInvalid, }); if (isInvalid) { return; } updateRemoteTitle(presentation.id)(newTitle, setLastSaveRequestPromise); }, deleteSlide: (id: string) => { const { presentation, setLastSaveRequestPromise } = get(); const { slides, id: pid } = presentation; const idx = slides.findIndex((s) => s.id === id); if (idx === -1) { console.error("Tried deleting slide which is not present. ", id); return; } deleteSlideRemote(id, pid, setLastSaveRequestPromise); set({ isSaving: true, presentation: { ...presentation, slides: slides.filter((s) => s.id !== id), }, }); }, deleteCurrentSlide: () => { const { currentSlideIdx, presentation: { slides }, deleteSlide, } = get(); const id = slides[currentSlideIdx].id; if (slides.length === 1) { createInfoToast("You need to have atleast one slide"); return; } if (!window.confirm("Do you really want to delete this slide?")) { return; } if (currentSlideIdx === slides.length - 1) { set({ currentSlideIdx: currentSlideIdx - 1 }); } deleteSlide(id); }, setLastSaveRequestPromise: (promise) => { const { lastSaveRequestPromise } = get(); const combinedPromise = Promise.allSettled( [lastSaveRequestPromise, promise].filter(Boolean) ); combinedPromise.finally(() => { const { lastSaveRequestPromise } = get(); if (lastSaveRequestPromise === combinedPromise) { set({ lastSaveRequestPromise: null, isSaving: false }); } }); set({ lastSaveRequestPromise: combinedPromise, isSaving: true }); }, })); export default useStore;
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/DeployPage/DeployConsole/DeployManager/index.ts
<reponame>uconomy/tezos-builder-suite<filename>frontend/src/routes/Deployer/DeployPage/DeployConsole/DeployManager/index.ts export * from './DeployManager';
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/PrepareStoragePage/StorageBuilder/builders/SetBuilder.tsx
<reponame>uconomy/tezos-builder-suite<filename>frontend/src/routes/Deployer/PrepareStoragePage/StorageBuilder/builders/SetBuilder.tsx import { Form, Button, Table } from 'antd'; import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'; import { useTranslation } from 'react-i18next'; import React from "react"; import "../StorageBuilder.css"; import { Builder, BuilderProps, extractAnnots } from "./Builder"; import { UnwrappedMichelsonObject, UnwrappedSimpleMichelsonObject } from '../../michelsonStorageParser'; import { renderBuilder } from '.'; interface FormListFieldData { name: number; key: number; fieldKey: number; } export const SetBuilder: React.FC<BuilderProps> = (props) => { const { object, index, itemProps, } = props; const { t } = useTranslation(); const renderMapBuilders = (data: FormListFieldData, list: UnwrappedMichelsonObject[]) => { console.log('BUILKDDDDDDD', { name: [data.name, extractAnnots(index, ['annots'])], fieldKey: [data.fieldKey, extractAnnots(index, ['annots'])], rules: [{ required: true }] }); return ( <> { list.length > 1 ? list.map((item, index) => ( renderBuilder({ ...item }, index, { name: [data.name, extractAnnots(index, item?.annots)], fieldKey: [data.fieldKey, extractAnnots(index, item?.annots)], rules: [{ required: true }] }) )) : renderBuilder({ ...list[0] }, 0, { name: [data.name], fieldKey: [data.fieldKey], rules: [{ required: true }] }) } </> ); } return ( <Builder className="list-block" object={object} index={index} render={(name: string, object: UnwrappedMichelsonObject) => ( <Form.List name={itemProps?.name || name} initialValue={[]}> { (fields, { add, remove }, { errors }) => { // Build table data here const columns = [ { title: t(`value`), dataInde: 'value', key: 'value', render: (data: FormListFieldData) => renderMapBuilders(data, (object as UnwrappedSimpleMichelsonObject).value) }, { className: 'actions', render: (data: FormListFieldData) => <MinusCircleOutlined onClick={() => remove(data.name)} /> } ]; return ( <div className={ fields.length > 0 ? "list-block-spacer" : "list-add-button" }> {fields.length > 0 && <Table columns={columns} dataSource={fields} className="list-table" bordered pagination={false} />} <Button type="dashed" size="small" onClick={() => add()} icon={<PlusOutlined />} >{t('add_items_to', { name })}</Button> <Form.ErrorList errors={errors} /> </div> ); } } </Form.List> )} /> ); }
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/DeployPage/DeployConsole/SignerManager/index.ts
export * from './SignerManager';
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/Deployer.tsx
import React from "react"; import { Layout } from 'antd'; import "./Deployer.css"; import { Summary } from "./Summary"; import { Router } from "../../shared/Router"; import { routes } from ".."; import { defaultDeployerPage, deployerRoutes } from "./routes"; const { Sider, } = Layout; export const Deployer: React.FC = () => { return ( <Layout className="page-container"> <Router routerRoot={`/${routes[0].path}`} defaultRoute={defaultDeployerPage} routes={deployerRoutes} /> <Sider className="page-sider" width={300}> <Summary /> </Sider> </Layout> ); }
uconomy/tezos-builder-suite
frontend/src/graphql/contract/index.ts
<reponame>uconomy/tezos-builder-suite<filename>frontend/src/graphql/contract/index.ts<gh_stars>1-10 export * from './contract.queries'; export * from './contract.mutations';
uconomy/tezos-builder-suite
backend/src/domain/endpoint/endpoint.types.ts
import { FaucetAccount } from "../tezos"; export type Endpoint = { url: string; scope: NetworkScope; protocolVersion: NetworkType; signerPrivateKey?: string; faucet?: FaucetAccount; }; export type NetworkScope = 'mainnet' | 'testnet' | 'sandbox'; export enum NetworkType { MAINNET = "mainnet", DELPHINET = "delphinet", EDONET = "edonet", FLORENCENET = "florencenet", GRANADANET = "granadanet", CUSTOM = "custom" };
uconomy/tezos-builder-suite
frontend/src/shared/AppLayout/AppLayout.tsx
import { Layout, Menu } from 'antd'; import SubMenu from 'antd/lib/menu/SubMenu'; import React from 'react'; import { TFunction, useTranslation } from 'react-i18next'; import { useHistory, useRouteMatch } from 'react-router-dom'; import { MenuItem, RouteDefinition } from '../../routes/routes.types'; import { Router } from '../Router'; import "./AppLayout.css"; const { Content, Header } = Layout; export type AppLayoutProps = { menu: MenuItem[]; routes: RouteDefinition[]; defaultRoute: string; routerRoot: string; } const getDefaultOpenedKeys = (items: MenuItem[]) => { return items.filter(x => !!x.children).map(x => x.route.path); } const renderMenuItem = (item: MenuItem, index: number, root: string, history: any, t: TFunction) => { if (item.children) { return ( <SubMenu key={`${item.route.path}`} icon={item.icon && <item.icon />} title={t(item.label)} > {item.children.map((e, i) => renderMenuItem(e, i, root, history, t))} </SubMenu> ); } return ( <Menu.Item key={`${root}${item.route.path}`} icon={item.icon && <item.icon />} onClick={() => history.push(`${root}${item.route.path}`)} >{t(item.label)}</Menu.Item> ); }; export const AppLayout: React.FC<AppLayoutProps> = ({ menu, routes, routerRoot, defaultRoute }) => { // const { isAuthenticated, isAuthenticating, user, login } = useAuth(); const history = useHistory(); const match = useRouteMatch(); const { t } = useTranslation(); const menuItems = menu.sort((a, b) => a.order < b.order ? -1 : 0); const pageMatch = useRouteMatch(menuItems.map(x => `${match.path}${x.route.path}`)); const matchedPage = pageMatch ? pageMatch.path : '/'; return ( <Layout className="app-container"> <Layout> <Header className="app-header"> <div className="app-logo"> Tezos deployer </div> <Menu mode="horizontal" theme="dark" selectedKeys={[matchedPage]} defaultOpenKeys={getDefaultOpenedKeys(menuItems)}> {menuItems.map((e, i) => renderMenuItem(e, i, match.path, history, t))} </Menu> </Header> <Content className="app-content"> <Router routerRoot={routerRoot} defaultRoute={defaultRoute} routes={routes} /> </Content> </Layout> </Layout> ); };
uconomy/tezos-builder-suite
backend/src/domain/tezos/tezos.types.ts
<filename>backend/src/domain/tezos/tezos.types.ts export type FaucetAccount = { mnemonic: string | string[]; secret: string; amount: string; // mutez pkh: string; password?: string; email: string; };
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/DeployPage/DeployConsole/DeployManager/DeployManager.tsx
<gh_stars>1-10 import React, { useCallback } from 'react'; import { CloudServerOutlined, CloudUploadOutlined, ContainerOutlined } from '@ant-design/icons'; import { useQuery, useMutation } from '@apollo/client'; import { Button } from 'antd'; import { useTranslation } from 'react-i18next'; import { ProgressCard } from '../../../../../shared/ProgressCard'; import { useDeployState } from '../../../state'; import "./DeployManager.css"; import { Endpoint, GET_ENDPOINT, NetworkType } from '../../../../../graphql/endpoint'; import { Contract, CONTRACT_DEPLOY_COMPLETED } from '../../../../../graphql/contract'; export const DeployManager: React.FC = () => { const { t } = useTranslation(); const { data } = useQuery<{ endpoint: Endpoint }>(GET_ENDPOINT); const [onDeployCompleted] = useMutation<{ contract: Contract; address: string; }>(CONTRACT_DEPLOY_COMPLETED); const [Tezos] = useDeployState('Tezos'); const [signer] = useDeployState('signer'); const [contract] = useDeployState('contract'); const [initialStorage] = useDeployState('initialStorage'); const [opHash, setOperationHash] = useDeployState('operationHash'); const [contractAddress, setContractAddress] = useDeployState('contractAddress'); const handleDeployContract = useCallback(async () => { if (!Tezos || !signer || !contract || !initialStorage) { return; } const op = await Tezos.wallet.originate({ code: JSON.parse(contract.michelson), storage: initialStorage, }).send(); const opHash = op.opHash; setOperationHash(opHash); const deployedContract = await op.contract(); setContractAddress(deployedContract.address); const receipt = await op.receipt(); console.log('RECEIPT', receipt); await onDeployCompleted({ variables: { contract: { name: contract.name, code: contract.code, michelson: contract.michelson }, address: deployedContract.address, } }); }, [Tezos, signer, contract, initialStorage, setOperationHash, setContractAddress, onDeployCompleted]); const protocolVersion = data?.endpoint.protocolVersion; const isSandbox = data?.endpoint.scope === 'sandbox' || false; return ( <div className="deploy-manager"> { opHash && <ProgressCard className={`operation-card${!contractAddress ? ' warning' : ''}`} loading={!contractAddress} Icon={CloudServerOutlined} title={t('deployer.operationForged', { hash: opHash })} subtitle={t(`deployer.operationForged${!contractAddress ? 'Warning' : 'Info'}`)} /> } { !contractAddress ? <div className="call-to-action"> <Button type="primary" size="large" className="mega-button" onClick={handleDeployContract} disabled={!signer} loading={!!opHash} icon={<CloudUploadOutlined />} >{t('deployer.deploy', { name: contract?.name })}</Button> </div> : <ProgressCard className="contract-card" Icon={ContainerOutlined} title={t('deployer.contractDeployed', { address: contractAddress })} subtitle={t('deployer.contractDeployedInfo')} /> } { !isSandbox && <div className="call-to-action"> { opHash && <a rel="noreferrer" href={`https://${protocolVersion !== 'mainnet' ? `${protocolVersion}.` : ''}tzkt.io/${opHash}`} target="_blank">{t('deployer.external.viewOperationTzkt')}</a> } { contractAddress && <a rel="noreferrer" href={`https://better-call.dev/search?text=${contractAddress}`} target="_blank">{t('deployer.external.viewContractBcd')}</a> } </div> } </div> ); }
uconomy/tezos-builder-suite
frontend/src/shared/Router/Router.tsx
import React from 'react'; import { Redirect, Route, Switch, useRouteMatch, match } from 'react-router-dom'; import { RouteDefinition } from '../../routes/routes.types'; import { NotFound } from '../NotFound'; import { RouteComponent } from './RouteComponent'; export type RouterProps = { routes: RouteDefinition[]; routerRoot: string; // The URL the Switch is mounted defaultRoute: string; // Default subnav route } const computeRoute = (match: match<{}>, path: string) => (match.path === path) ? path : `${match.path}${match.path.endsWith('/') ? '' : '/'}${path}`; export const Router: React.FC<RouterProps> = ({ routes, routerRoot, defaultRoute }) => { const match = useRouteMatch(); return ( <Switch> {routes.map((route, index) => <RouteComponent key={`${match.path}${index}`} component={route.component} path={computeRoute(match, route.path)} /> )} {routerRoot !== defaultRoute && <Redirect from={routerRoot} to={computeRoute(match, defaultRoute)} exact={true} /> } <Route component={NotFound} /> </Switch> ) };
uconomy/tezos-builder-suite
backend/src/graphql/index.ts
<reponame>uconomy/tezos-builder-suite<gh_stars>1-10 import { buildFederatedSchema } from '@apollo/federation'; import { GraphQLSchema } from 'graphql'; import contract from './contract'; import endpoint from './endpoint'; export * from './server'; export const schema: GraphQLSchema = buildFederatedSchema([ contract, endpoint, ]);
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/PrepareStoragePage/storageImporter.ts
<filename>frontend/src/routes/Deployer/PrepareStoragePage/storageImporter.ts<gh_stars>1-10 import { MichelsonMap } from "@taquito/taquito"; import { BigNumber } from 'bignumber.js'; import { MichelsonStorageParser, UnwrappedMichelsonObject, UnwrappedSimpleMichelsonObject, UnwrappedComplexMichelsonObject, } from "./michelsonStorageParser"; export class StorageImporter { private unwrappedStorage: UnwrappedMichelsonObject[]; constructor(michelsonString: string) { const structure = new MichelsonStorageParser(michelsonString); this.unwrappedStorage = structure.unwrapStorage(); } private _buildList(el: any[], structure: UnwrappedSimpleMichelsonObject) { const { value } = structure; if (!value || !el || !el.length) { return []; } return el; } private _buildMap(el: any[], structure: UnwrappedComplexMichelsonObject) { const { prim, args, annots, value, key } = structure; // Provide typecheck to MichelsonMap const map = new MichelsonMap({ prim, args, annots }); if (!key || !value || !el || !el.length) { return map; } // Fill the map/big_map el.forEach((item) => { // Parse eventual sub-structures let iValue = this.fromJSON(item[1], structure.value, false); map.set(item[0], iValue); }); return map; } _buildOr(el: any, structure: UnwrappedComplexMichelsonObject) { if (structure.value) { const found = structure.value.find(x => x.prim === 'unit' && x.annots?.join(' ') === `${el}`); if (found) { return { [`${el}`.substring(1)]: Symbol() }; } throw new Error('OR processing failed, no valid option found'); } return null; } private _parse(el: any, structure: UnwrappedMichelsonObject): any { switch (structure.prim) { case 'list': case 'set': return this._buildList(el, structure as UnwrappedSimpleMichelsonObject); case 'map': case 'big_map': return this._buildMap(el, structure as UnwrappedComplexMichelsonObject); case 'or': return this._buildOr(el, structure as UnwrappedComplexMichelsonObject); case 'unit': return null; case 'nat': case 'int': case 'mutez': return new BigNumber(el); case 'record': return this.fromJSON(el, structure.args); default: return el; } } fromJSON(json: any, structure: UnwrappedMichelsonObject[] = this.unwrappedStorage, isFirstLevel: boolean = true) { const storage: any = {}; if (Array.isArray(json) || typeof json === 'object') { const firsLevelKeys = Object.keys(json); firsLevelKeys.forEach(prop => { let propStructure = structure.find(x => x.annots?.join(' ') === `%${prop}`); const asIndex = parseInt(prop); if (!isNaN(asIndex)) { propStructure = structure[asIndex]; } if (!propStructure) { console.log('Failed to find a strucure for prop', prop, structure); throw new Error('Invalid JSON provided.'); } storage[prop] = this._parse(json[prop], propStructure); }); } else { return this._parse(json, structure[0]); } if (isFirstLevel && typeof storage === 'object') { const keys = Object.keys(storage); // If we have a single-value storage, IT IS the storage (eg. example LIGO counter) if (keys.length === 1 && keys[0] === '0') { return storage[0]; } } return storage; } }
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/PreviewDeployPage/PreviewViewer/PreviewViewer.tsx
import React, { useState, useEffect, useCallback } from 'react'; import { useTranslation } from 'react-i18next'; import { Table, Button } from 'antd'; import { WarningOutlined, ReloadOutlined } from '@ant-design/icons'; import { useQuery } from '@apollo/client'; import "./PreviewViewer.css"; import { Tezos } from '../../../../shared/Tezos'; import { useDeployState } from '../../state'; import { ProgressCard } from '../../../../shared/ProgressCard'; import { Endpoint, GET_ENDPOINT } from '../../../../graphql/endpoint'; import { TezosToolkit } from '@taquito/taquito'; import { importKey } from '@taquito/signer'; type ResultLine = { key: string; value: number; name: string; type: 'tez'| 'mutez' | 'number' | 'bytes'; }; type Results = ResultLine[]; const types: { [x: string]: ResultLine['type'] } = { "baseFeeMutez": 'mutez', "minimalFeeMutez": 'mutez', "suggestedFeeMutez": 'mutez', "operationFeeMutez": 'mutez', "gasLimit": `number`, "consumedMilligas": 'number', "storageLimit": 'bytes', "opSize": 'bytes', "minimalFeePerStorageByteMutez": 'mutez', "burnFeeMutez": 'mutez', "totalCost": 'mutez', } export const PreviewViewer: React.FC = () => { const { t } = useTranslation(); const [contract] = useDeployState('contract'); const [initialStorage] = useDeployState('initialStorage'); const { data, loading, error } = useQuery<{ endpoint: Endpoint }>(GET_ENDPOINT); const [estimate, setEstimates] = useDeployState('estimates'); const [dataSource, setDataSource] = useState<Results>(); const [previewError, setPreviewError] = useState<Error>(); const handlePreviewRequest = useCallback(async () => { if (!contract || !initialStorage || !data || loading || error) { return; } setPreviewError(undefined); const LocalTezos = new TezosToolkit("https://granadanet.smartpy.io/"); const faucet = { "mnemonic": [ "hub", "table", "rough", "whale", "shield", "actor", "egg", "upgrade", "collect", "simple", "bicycle", "daughter", "catalog", "truth", "twice" ], "secret": "95718ff7a1512bdce2322d41642ff27d935bc334", "amount": "134592037796", "pkh": "tz1LNRBs1hxarBfxT7dCaTN8nYFAB1X7i93T", "password": "<PASSWORD>", "email": "<EMAIL>" }; try { importKey(LocalTezos, faucet.email, faucet.password, faucet.mnemonic.join(' '), faucet.secret); } catch(err) { console.log('FAILED TO IMPORT KEY', err); } try { const op = await LocalTezos.estimate.originate({ code: JSON.parse(contract.michelson), storage: initialStorage, }); setEstimates(op); } catch(err) { setPreviewError(err); } }, [contract, initialStorage, data, loading, error, setEstimates, setPreviewError]); useEffect(() => { if (!contract || !initialStorage || !data || loading || error) { return; } if(!estimate) { handlePreviewRequest(); return; } const estimatesData: Results = Object.keys(types) .map((name, index) => { let value = (estimate as any)[name] as number; let type = types[name]; if ((type === 'mutez' && value > 1000000) || name === 'totalCost') { type = 'tez'; value /= 1000000; } if (name === 'consumedMilligas') { value /= 1000; } return { key: `result-${index}`, name, value, type } }); setDataSource(estimatesData); }, [estimate, contract, initialStorage, data, loading, error, handlePreviewRequest]); const columns = [ { width: 150, render: ({ value, type, name }: ResultLine) => ( <div className={`estimate-${type} ${name}`}> { type === 'number' || type === 'bytes' ? <>{value}{type === 'bytes' ? ' bytes' : null}</> : <Tezos value={value} mutez={type === 'mutez'} /> } </div> ) }, { render: ({ name }: ResultLine) => <div className={`${name}`}>{t(`deployer.estimates.${name}`)}</div> } ]; if (error || previewError) { return ( <> <ProgressCard Icon={WarningOutlined} title={error ? t('deployer.signer.endpointSettingsError') : previewError?.message || ''} subtitle={error ? error.message : previewError?.stack || ''} /> <div className="call-to-action"> <Button onClick={handlePreviewRequest} type="primary" icon={<ReloadOutlined />}>{t('tryAgain')}</Button> </div> </> ); } return ( <div> { (!dataSource || !estimate) ? <ProgressCard loading={loading || !dataSource || !estimate} title={loading ? t('deployer.signer.loadingEndpointSettings') : t('deployer.retrievingEstimates')} subtitle={t('deployer.retrievingEstimatesInfo')} /> : <Table className="estimates" columns={columns} dataSource={dataSource} pagination={false} showHeader={false} bordered size="small" /> } </div> ); }
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/PrepareStoragePage/StorageBuilder/builders/Builder.tsx
import React from "react"; import { useTranslation } from "react-i18next"; import { Tag, TagProps, Form, FormItemProps } from 'antd'; import { MichelsonPrims, UnwrappedMichelsonObject } from "../../michelsonStorageParser"; import "../StorageBuilder.css"; type TagColor = TagProps['color']; const colors: { [x in UnwrappedMichelsonObject['prim']]: TagColor } = { [MichelsonPrims.UNIT]: 'magenta', [MichelsonPrims.BOOL]: 'yellow', [MichelsonPrims.BYTES]: 'blue', [MichelsonPrims.NAT]: 'red', [MichelsonPrims.INT]: 'gold', [MichelsonPrims.MUTEZ]: 'purple', [MichelsonPrims.TIMESTAMP]: 'volcano', [MichelsonPrims.STRING]: 'cyan', [MichelsonPrims.ADDRESS]: 'green', [MichelsonPrims.KEY]: 'orange', [MichelsonPrims.KEY_HASH]: 'orange', [MichelsonPrims.SIGNATURE]: 'orange', [MichelsonPrims.STORAGE]: 'lime', [MichelsonPrims.LIST]: 'volcano', [MichelsonPrims.SET]: 'volcano', [MichelsonPrims.MAP]: 'blue', [MichelsonPrims.BIG_MAP]: 'purple', [MichelsonPrims.PAIR]: 'lime', [MichelsonPrims.OR]: 'lime', "record": 'lime', }; export function extractAnnots(index: number, annots?: string[]) { if (!annots) return (Math.floor(index).toString()); return annots.join(' ').substring(1); } export interface BuilderProps { object: UnwrappedMichelsonObject; index: number; hidePrim?: boolean; itemProps?: FormItemProps; render?: (name: string, o: UnwrappedMichelsonObject) => React.ReactNode; className?: string; } export const Builder: React.FC<BuilderProps> = (props) => { const { className, object, index, hidePrim, itemProps, render, children, } = props; const { t } = useTranslation(); const name = extractAnnots(index, object.annots); return ( <div className={`builder-block${className ? ` ${className}` : ''}`}> {!hidePrim && <div className="builder-block-label"> <Tag className="type-tag" color={colors[object.prim]}> {t(`prim.${object.prim}`)} </Tag> { isNaN(parseInt(name)) && <label>{name}</label> } </div>} { !render ? ( <Form.Item name={name} rules={[{ required: true }]} {...itemProps}> {children} </Form.Item> ) : render(name, object) } </div> ); }
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/PrepareStoragePage/StorageBuilder/builders/StringBuilder.tsx
import { Input } from 'antd'; import React from "react"; import "../StorageBuilder.css"; import { Builder, BuilderProps } from "./Builder"; export const StringBuilder: React.FC<BuilderProps> = (props) => { const { object, index, itemProps, } = props; return ( <Builder object={object} index={index} itemProps={{ ...itemProps, className: "full-width" }}> <Input /> </Builder> ); }
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/PrepareStoragePage/StorageBuilder/builders/MutezBuilder.tsx
import { InputNumber } from 'antd'; import React from "react"; import "../StorageBuilder.css"; import { Builder, BuilderProps } from "./Builder"; export const MutezBuilder: React.FC<BuilderProps> = (props) => { const { object, index, itemProps, } = props; return ( <Builder object={object} index={index} itemProps={itemProps}> <InputNumber min={0} max={Number.MAX_SAFE_INTEGER} placeholder="0" /> </Builder> ); }
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/DeployPage/DeployConsole/SignerManager/SignerCard/index.ts
<gh_stars>1-10 export * from './SignerCard';
uconomy/tezos-builder-suite
backend/src/services/contract/index.ts
<gh_stars>1-10 export * from './contract.service';
uconomy/tezos-builder-suite
backend/src/services/endpoint/index.ts
<gh_stars>1-10 export * from './endpoint.service';
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/PrepareStoragePage/StorageBuilder/StorageBuilder.tsx
import React, { useEffect, useCallback, useState } from "react"; import { StopOutlined } from '@ant-design/icons'; import { useTranslation } from "react-i18next"; import { Form } from 'antd'; import { UnwrappedMichelsonObject } from "../michelsonStorageParser"; import "./StorageBuilder.css"; import { renderBuilder } from "./builders"; import { useDeployState } from "../../state"; import { StorageImporter } from "../storageImporter"; import { ProgressCard } from "../../../../shared/ProgressCard"; import { CodeViewer } from "../../../../shared/CodeViewer"; export interface StorageBuilderProps { unwrappedMichelson?: UnwrappedMichelsonObject[]; onFinish: () => void; } export const StorageBuilder: React.FC<StorageBuilderProps> = ({ unwrappedMichelson, onFinish }) => { const { t } = useTranslation(); const [storageForm] = Form.useForm(); const [contract] = useDeployState('contract'); const [, setActiveForm] = useDeployState('activeForm'); const [, setInitialStorage] = useDeployState('initialStorage'); const [storageContent, setStorageContent] = useDeployState('storageContent'); const [, setEstimates] = useDeployState('estimates'); const [error, setError] = useState<any>(); useEffect(() => { setActiveForm(storageForm); return () => { setActiveForm(undefined); } }, [storageForm, setActiveForm]); const handleFinish = useCallback((formValues: any) => { console.log('FORM FINISH', JSON.stringify(formValues, null, 2)); if (!contract) { return; } const importer = new StorageImporter(contract.michelson); setStorageContent(formValues); setEstimates(undefined); try { const storage = importer.fromJSON(formValues); console.log('GENERATED STORAGE', storage); setInitialStorage(storage); onFinish(); } catch (err) { if (err.name.endsWith('TypecheckError')) { setError(err); } console.log("STORAGE FAILED", err); } }, [contract, setStorageContent, setEstimates, setInitialStorage, onFinish]); return ( <> { error && <ProgressCard Icon={StopOutlined} className="validation-error" title={t('deployer.storageValidationError', { ...error })} subtitle={t('deployer.storageValidationErrorInfo')} > <CodeViewer code={JSON.stringify(error || '', null, 2)} language="json" /> </ProgressCard> } <Form onFieldsChange={() => setError(undefined)} form={storageForm} initialValues={storageContent} onFinish={handleFinish} > {unwrappedMichelson?.map((x, i) => renderBuilder(x, i))} </Form> </> ); }
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/PrepareStoragePage/StorageBuilder/builders/UnitBuilder.tsx
<reponame>uconomy/tezos-builder-suite<gh_stars>1-10 import React from "react"; import { Input } from 'antd'; import "../StorageBuilder.css"; import { Builder, BuilderProps } from "./Builder"; export const UnitBuilder: React.FC<BuilderProps> = (props) => { const { object, index, itemProps } = props; return ( <Builder object={object} index={index} itemProps={{ ...itemProps, rules: [] }}> <Input type="hidden" value={object.annots ? object.annots.join(' ') : ''} /> </Builder> ); }
uconomy/tezos-builder-suite
frontend/src/routes/routes.types.ts
export type RouteDefinition<T = any> = { path: string; component: React.ComponentType<T> | React.FC<T>; exact?: boolean; permissions?: {}; } export type BaseMenuItem = { route: RouteDefinition; label: string; icon?: any; order: number; }; export type MenuItem = BaseMenuItem & { children?: BaseMenuItem[]; }; export type MenuConfig = MenuItem[];
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/PrepareStoragePage/michelsonStorageParser.ts
<filename>frontend/src/routes/Deployer/PrepareStoragePage/michelsonStorageParser.ts export enum MichelsonPrims { UNIT = 'unit', BOOL = 'bool', BYTES = 'bytes', NAT = 'nat', INT = 'int', MUTEZ = 'mutez', TIMESTAMP = 'timestamp', STRING = 'string', ADDRESS = 'address', KEY = 'key', KEY_HASH = 'key_hash', SIGNATURE = 'signature', STORAGE = 'storage', LIST = 'list', SET = 'set', MAP = 'map', BIG_MAP = 'big_map', PAIR = 'pair', OR = 'or', } export type PlainMichelsonObject = { prim: 'unit' | 'bool' | 'bytes' | 'nat' | 'int' | 'mutez' | 'timestamp' | 'string' | 'address' | 'key' | 'key_hash' | 'signature'; annots?: string[]; } export type SimpleMichelsonObject = { prim: 'storage' | 'list' | 'set'; args: [MichelsonObject], annots?: string[]; } export type ComplexMichelsonObject = { prim: 'map' | 'big_map' | 'pair' | 'or'; args: [MichelsonObject, MichelsonObject], annots?: string[]; } export type MichelsonObject = (PlainMichelsonObject | SimpleMichelsonObject | ComplexMichelsonObject); /** * Unwrapped Michelson Objects */ export type UnwrappedSimpleMichelsonObject = SimpleMichelsonObject & { value: UnwrappedMichelsonObject[]; }; export type UnwrappedComplexMichelsonObject = ComplexMichelsonObject & { key: UnwrappedMichelsonObject[]; value: UnwrappedMichelsonObject[]; }; export type UnwrappedRecord = { prim: 'record'; args: UnwrappedMichelsonObject[], annots: string[]; }; export type UnwrappedMichelsonObject = MichelsonObject | UnwrappedSimpleMichelsonObject | UnwrappedComplexMichelsonObject | UnwrappedRecord; export class MichelsonStorageParser { michelsonStorage: SimpleMichelsonObject; constructor(michelson: string) { const json = JSON.parse(michelson); this.michelsonStorage = json.find((x: any) => x.prim === 'storage') as SimpleMichelsonObject; } getMichelsonStorage() { return JSON.stringify(this.michelsonStorage, null, 2); } private processBlock(block: UnwrappedMichelsonObject): UnwrappedMichelsonObject[] { switch(block.prim) { case 'list': case 'set': const list = block as SimpleMichelsonObject; const list_args = list.args; const list_value = Array.isArray(list_args[0]) ? this.unwrapBlock(list_args[0]) : this.unwrapBlock([list_args[0]]); return [{ ...list, value: list_value, }]; case 'map': case 'big_map': const big_map = block as ComplexMichelsonObject; const big_map_args = big_map.args; const big_map_key = Array.isArray(big_map_args[0]) ? this.unwrapBlock(big_map_args[0]) : this.unwrapBlock([big_map_args[0]]); const big_map_value = Array.isArray(big_map_args[1]) ? this.unwrapBlock(big_map_args[1]) : this.unwrapBlock([big_map_args[1]]); return [{ ...big_map, key: big_map_key, value: big_map_value, }]; case 'or': const or = block as ComplexMichelsonObject; const or_args = or.args; const or_args1 = Array.isArray(or_args[0]) ? this.unwrapBlock(or_args[0]) : this.unwrapBlock([or_args[0]]); const or_args2 = Array.isArray(or_args[1]) ? this.unwrapBlock(or_args[1]) : this.unwrapBlock([or_args[1]]); return [{ ...or, value: [...or_args1, ...or_args2], }]; default: return [block]; } } private unwrapPair(block: ComplexMichelsonObject): UnwrappedMichelsonObject[] { if (block.annots) { return [{ prim: 'record', annots: block.annots, args: [ ...this.unwrapBlock([ block.args[0] ]), ...this.unwrapBlock([ block.args[1] ]), ] }] } else { return this.unwrapBlock(block.args); } } private unwrapBlock(block: UnwrappedMichelsonObject[]): UnwrappedMichelsonObject[] { let res: UnwrappedMichelsonObject[] = []; block.forEach(x => { if (x.prim === 'pair') { res.push(...this.unwrapPair(x)) } else { res.push(...this.processBlock(x)); } }); return res; } unwrapStorage() { const res = this.unwrapBlock(this.michelsonStorage.args); return res; } }
uconomy/tezos-builder-suite
backend/src/services/endpoint/endpoint.service.ts
import { Endpoint } from "../../domain/endpoint"; import { ApolloContext } from "../../graphql/context"; export async function getEndpoint(context: ApolloContext): Promise<Endpoint> { const endpoint: any = Object.assign({}, context.endpoint); if (endpoint.signerPrivateKey && endpoint.faucet) { throw new Error('You cannot specify both a signer Private Key AND a Faucet account, please remove one.'); } if (endpoint.scope === 'sandbox' && !endpoint.faucet && !endpoint.signerPrivateKey) { throw new Error('Sandbox requires either signer Private Key or a Faucet account, please set one of those.'); } const faucet = context.endpoint.faucet; if (faucet && Array.isArray(faucet.mnemonic)) { switch (faucet.mnemonic.length) { case 12: case 15: case 18: case 21: case 24: endpoint.faucet.mnemonic = faucet.mnemonic.join(' '); break; default: throw new Error(`Invalid mnemonic with ${faucet.mnemonic.length} words provided to Faucet account, it must contain 12, 15, 18, 21 or 24 words`); } } if (!context.endpoint.scope) { endpoint.scope = 'testnet'; } return endpoint; }
uconomy/tezos-builder-suite
backend/src/graphql/server.ts
<gh_stars>1-10 import { ApolloServer, ExpressContext, Config } from 'apollo-server-express'; import express from 'express'; import { GraphQLSchema } from 'graphql'; import { ApolloContext } from './context'; export async function createApolloServer( app: express.Application, schema: GraphQLSchema, context?: ApolloContext | (() => ApolloContext) | (() => Promise<ApolloContext>), ): Promise<ApolloServer<ExpressContext>> { // Same ApolloServer initialization as before const server = new ApolloServer({ schema, context, }); // Required logic for integrating with Express await server.start(); server.applyMiddleware({ app, // By default, apollo-server hosts its GraphQL endpoint at the // server root. However, *other* Apollo Server packages host it at // /graphql. Optionally provide this to match apollo-server. path: '/graphql' }); return server; }
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/CheckContractPage/index.ts
<filename>frontend/src/routes/Deployer/CheckContractPage/index.ts<gh_stars>1-10 export * from './CheckContractPage';
uconomy/tezos-builder-suite
frontend/src/shared/NotFound/NotFound.tsx
import { ArrowLeftOutlined } from '@ant-design/icons'; import { Button, Empty, Layout } from 'antd'; import React from 'react'; import { useHistory } from 'react-router-dom'; import './NotFound.css'; export const NotFound = () => { const history = useHistory(); return ( <Layout className="not-found-container"> <Empty className="not-found" description="Sorry, we can't find the content you were looking for." /> <p>This URL does not point to anything on this website.</p> <Button type='primary' className="not-found-action" onClick={() => history.goBack()} > <ArrowLeftOutlined /> Go back </Button> </Layout> ); }; export default NotFound;
uconomy/tezos-builder-suite
backend/src/domain/tezos/index.ts
<reponame>uconomy/tezos-builder-suite export * from './tezos.types';
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/DeployPage/DeployConsole/DeployConsole.tsx
import React from 'react'; import { GlobalOutlined } from '@ant-design/icons'; import { useQuery } from '@apollo/client'; import { useTranslation } from 'react-i18next'; import { Endpoint, GET_ENDPOINT } from '../../../../graphql/endpoint'; import { ProgressCard } from '../../../../shared/ProgressCard'; import { DeployManager } from './DeployManager'; import { SignerManager } from './SignerManager'; import "./DeployConsole.css"; export const DeployConsole: React.FC = () => { const { data, loading, error } = useQuery<{ endpoint: Endpoint }>(GET_ENDPOINT); const { t } = useTranslation(); if (!data || loading || error) { return null; } const endpoint = data?.endpoint; return ( <div className="deploy-console"> <ProgressCard className="network" loading={loading} Icon={GlobalOutlined} title={t('deployer.networkWarning', { scope: t(`deployer.network.scope.${endpoint.scope}`) })} subtitle={t('deployer.networkEndpoint', { endpoint: endpoint.url })} /> <SignerManager /> <DeployManager /> </div> ); }
uconomy/tezos-builder-suite
frontend/src/routes/Deployer/CheckContractPage/CheckContractPage.tsx
<filename>frontend/src/routes/Deployer/CheckContractPage/CheckContractPage.tsx<gh_stars>1-10 import React, { useCallback } from "react"; import { useTranslation } from "react-i18next"; import { Layout, PageHeader } from 'antd'; import { useHistory } from 'react-router-dom'; import "./CheckContractPage.css"; import { CodeViewer } from "../../../shared/CodeViewer"; import { useDeployState } from "../state"; const { Header, Content, } = Layout; export const CheckContractPage: React.FC = () => { const { t } = useTranslation(); const history = useHistory(); const [contract] = useDeployState('contract'); const goBack = useCallback(() => { history.push('choose-contract'); }, [history]); if (!contract) { goBack(); return null; } return ( <Layout> <Header className="page-header"> <PageHeader title={t(`deployer.titles.checkContract`, { name: contract.name })} onBack={goBack} /> </Header> <Content className="page-content"> <CodeViewer className="code-viewer" fileName={contract.name} code={contract.code} /> </Content> </Layout> ); }
uconomy/tezos-builder-suite
frontend/src/shared/ProgressCard/ProgressCard.tsx
<reponame>uconomy/tezos-builder-suite import AntdIcon, { LoadingOutlined } from '@ant-design/icons'; import React from 'react'; import "./ProgressCard.css"; export interface ProgressCardProps { className?: string; Icon?: typeof AntdIcon; loading?: boolean; title: string; subtitle?: string; }; export const ProgressCard: React.FC<ProgressCardProps> = (props) => { const { className,Icon, loading, title, subtitle, children } = props; return ( <div className={`progress-card${className ? ` ${className}` : ''}`}> {loading ? <LoadingOutlined className="big-icon" /> : (Icon && <Icon className="big-icon icon-color" />) } <div className="progress-card-message"> <label className="title">{title}</label> {subtitle && <span className="subtitle">{subtitle}</span>} {children} </div> </div> ); }
uconomy/tezos-builder-suite
backend/src/graphql/contract/contract.typedefs.ts
<filename>backend/src/graphql/contract/contract.typedefs.ts<gh_stars>1-10 import { gql } from "apollo-server-express"; export const typeDefs = gql` extend type Query { contracts: [Contract!]! } extend type Mutation { deployCompleted(contract: ContractInput!, address: String!): Boolean! } type Contract @key(fields: "name") { name: String! code: String! michelson: String! } input ContractInput { name: String! code: String! michelson: String! } `;