repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
carlosrojaso/chapter | client/src/modules/dashboard/Sponsors/pages/SponsorsPage.tsx | <gh_stars>10-100
import { VStack, Flex, Heading, Text } from '@chakra-ui/react';
import { DataTable } from 'chakra-data-table';
import { LinkButton } from 'chakra-next-link';
import { NextPage } from 'next';
import Head from 'next/head';
import React from 'react';
import { Layout } from '../../shared/components/Layout';
import { useSponsorsQuery } from 'generated/graphql';
export const SponsorsPage: NextPage = () => {
const { loading, error, data } = useSponsorsQuery();
return (
<>
<Head>
<title>Sponsors</title>
</Head>
<Layout>
<VStack>
<Flex w="full" justify="space-between">
<Heading id="page-heading">Sponsors</Heading>
<LinkButton href="/dashboard/sponsors/new">Add new</LinkButton>
</Flex>
{loading ? (
<Heading> Loading Sponsors...</Heading>
) : error || !data?.sponsors ? (
<>
<Heading>Error while loading sponsors</Heading>
<Text>
{error?.name}:{error?.message}
</Text>
</>
) : (
<DataTable
tableProps={{ table: { 'aria-labelledby': 'page-heading' } }}
data={data.sponsors}
keys={['name', 'type', 'website', 'actions'] as const}
mapper={{
name: (sponsor) => (
<LinkButton href={`/dashboard/sponsors/${sponsor.id}`}>
{sponsor.name}
</LinkButton>
),
type: (sponsor) => sponsor.type,
website: (sponsor) => sponsor.website,
actions: (sponsor) => (
<LinkButton
colorScheme="green"
size="xs"
href={`/dashboard/sponsors/${sponsor.id}/edit`}
>
Edit
</LinkButton>
),
}}
/>
)}
</VStack>
</Layout>
</>
);
};
|
carlosrojaso/chapter | server/src/graphql-types/UserChapterRole.ts | import { ObjectType, Field, Int } from 'type-graphql';
import { User } from './User';
// registerEnumType(ChapterRoles, { name: 'ChapterRoles' });
// TODO: Make this enum
export type ChapterRoles = 'organizer' | 'member';
@ObjectType()
export class UserChapterRole {
@Field(() => Int)
user_id: number;
@Field(() => Int)
chapter_id: number;
@Field(() => User)
user: User;
@Field(() => Boolean)
interested: boolean;
}
|
carlosrojaso/chapter | server/prisma/generator/factories/venues.factory.ts | <reponame>carlosrojaso/chapter
import { faker } from '@faker-js/faker';
import { Prisma } from '@prisma/client';
import { prisma } from '../../../src/prisma';
const { company, address } = faker;
const createVenues = async (): Promise<number[]> => {
const venueIds: number[] = [];
for (let i = 0; i < 4; i++) {
const venueData: Prisma.venuesCreateInput = {
name: company.companyName(),
city: address.city(),
region: address.state(),
postal_code: address.zipCode(),
country: address.country(),
street_address: Math.random() > 0.5 ? address.streetAddress() : undefined,
};
// TODO: batch this once createMany returns the records.
const venue = await prisma.venues.create({ data: venueData });
venueIds.push(venue.id);
}
return venueIds;
};
export default createVenues;
|
carlosrojaso/chapter | server/src/graphql-types/Rsvp.ts | import { ObjectType, Field, Int } from 'type-graphql';
import { User } from '.';
@ObjectType()
export class Rsvp {
@Field(() => Int)
user_id: number;
@Field(() => Int)
event_id: number;
@Field(() => Date)
date: Date;
@Field(() => Boolean)
on_waitlist: boolean;
@Field(() => Date, { nullable: true })
confirmed_at: Date | null;
@Field(() => Boolean)
canceled: boolean;
}
@ObjectType()
export class RsvpWithUser extends Rsvp {
@Field(() => User)
user: User;
}
|
carlosrojaso/chapter | server/src/controllers/Messages/resolver.ts | <reponame>carlosrojaso/chapter<filename>server/src/controllers/Messages/resolver.ts
import { Resolver, Mutation, Arg } from 'type-graphql';
import MailerService from '../../services/MailerService';
import { Email } from './Email';
import { SendEmailInputs } from './inputs';
@Resolver()
export class EmailResolver {
@Mutation(() => Email) async sendEmail(
@Arg('data') data: SendEmailInputs,
): Promise<Email> {
const email = new MailerService(data.to, data.subject, data.html);
await email.sendEmail();
return {
ourEmail: email.ourEmail,
emailList: email.emailList,
subject: email.subject,
htmlEmail: email.htmlEmail,
backupText: email.backupText,
};
}
}
|
carlosrojaso/chapter | server/prisma/generator/factories/rsvps.factory.ts | import { faker } from '@faker-js/faker';
import { Prisma } from '@prisma/client';
import { sub } from 'date-fns';
import { prisma } from '../../../src/prisma';
import { random, randomItems } from '../lib/random';
import { makeBooleanIterator } from '../lib/util';
const { date } = faker;
const createRsvps = async (eventIds: number[], userIds: number[]) => {
const rsvps: Prisma.rsvpsCreateManyInput[] = [];
const userEventRoles: Prisma.user_event_rolesCreateManyInput[] = [];
const eventReminders: Prisma.event_remindersCreateManyInput[] = [];
const eventIterator = makeBooleanIterator();
for (const eventId of eventIds) {
const eventUserIds = randomItems(userIds, userIds.length / 2);
const numberWaiting = 1 + random(eventUserIds.length - 2);
const numberCanceled = 1 + random(eventUserIds.length - numberWaiting - 1);
// makes sure half of each event's users are organisers, but
// alternates which half.
const organizerIterator = makeBooleanIterator(eventIterator.next().value);
for (let i = 0; i < eventUserIds.length; i++) {
const on_waitlist = i < numberWaiting;
const canceled = !on_waitlist && i < numberWaiting + numberCanceled;
const rsvp = {
event_id: eventId,
user_id: eventUserIds[i],
date: date.future(),
on_waitlist,
canceled,
confirmed_at: new Date(),
};
const role = {
user_id: eventUserIds[i],
event_id: eventId,
role_name: organizerIterator.next().value ? 'organizer' : 'attendee',
subscribed: true, // TODO: have some unsubscribed users
};
if (role.subscribed && !rsvp.on_waitlist && !rsvp.canceled) {
const event = await prisma.events.findUnique({
where: { id: eventId },
});
if (!event.canceled) {
const reminder = {
event_id: eventId,
user_id: eventUserIds[i],
notifying: false,
remind_at: sub(event.start_at, { days: 1 }),
};
eventReminders.push(reminder);
}
}
rsvps.push(rsvp);
userEventRoles.push(role);
}
}
try {
await prisma.rsvps.createMany({ data: rsvps });
} catch (e) {
console.error(e);
throw new Error('Error seeding rsvps');
}
try {
await prisma.event_reminders.createMany({ data: eventReminders });
} catch (e) {
console.error(e);
throw new Error('Error seeding event reminders');
}
try {
await prisma.user_event_roles.createMany({ data: userEventRoles });
} catch (e) {
console.error(e);
throw new Error('Error seeding user-event-roles');
}
};
export default createRsvps;
|
carlosrojaso/chapter | server/tests/Mailer.test.ts | import assert from 'assert';
import chai, { expect } from 'chai';
import { stub, restore } from 'sinon';
import sinonChai from 'sinon-chai';
import MailerService from '../src/services/MailerService';
import Utilities from '../src/util/Utilities';
chai.use(sinonChai);
beforeEach(() => {
stub(console, 'warn');
});
afterEach(() => {
// Restore the default sandbox here
restore();
});
// Setup
const emailAddresses = [
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
];
const subject = 'Welcome To Chapter!';
const htmlEmail = '<div><h1>Hello Test</h1></div>';
const backupText = 'Email html failed to load';
describe('MailerService Class', () => {
it('Should assign the email username, password, and service to transporter', () => {
const mailer = new MailerService(
emailAddresses,
subject,
htmlEmail,
backupText,
);
const { auth, service } = mailer.transporter.options as any;
assert.equal(service, mailer.emailService);
assert.equal(auth.user, mailer.emailUsername);
assert.equal(auth.pass, mailer.emailPassword);
});
it('Should correctly instantiate values', () => {
const mailer = new MailerService(
emailAddresses,
subject,
htmlEmail,
backupText,
);
assert.equal(subject, mailer.subject);
assert.equal(htmlEmail, mailer.htmlEmail);
assert.equal(backupText, mailer.backupText);
expect(emailAddresses).to.have.members(mailer.emailList);
});
it('Should provide a blank string if backup text is undefined', () => {
const mailer = new MailerService(emailAddresses, subject, htmlEmail);
assert.equal(mailer.backupText, '');
});
it('Should log a warning if emailUsername, emailPassword, or emailService is not specified', () => {
stub(Utilities, 'allValuesAreDefined').callsFake(() => false);
new MailerService(emailAddresses, subject, htmlEmail);
expect(console.warn).to.have.been.calledOnce;
});
});
|
carlosrojaso/chapter | server/prisma/generator/factories/sponsors.factory.ts | import { faker } from '@faker-js/faker';
import { Prisma } from '@prisma/client';
import { prisma } from '../../../src/prisma';
import { randomEnum } from '../lib/random';
const { company, internet, system } = faker;
enum SponsorTypes {
'FOOD',
'VENUE',
'OTHER',
}
const createSponsors = async (): Promise<number[]> => {
const sponsors: number[] = [];
for (let i = 0; i < 4; i++) {
const name = company.companyName();
const website = internet.url();
const logo_path = system.commonFileName('png');
const type = String(randomEnum(SponsorTypes));
const sponsorData: Prisma.sponsorsCreateInput = {
name,
website,
logo_path,
type,
};
// TODO: batch this once createMany returns the records.
const sponsor = await prisma.sponsors.create({ data: sponsorData });
sponsors.push(sponsor.id);
}
return sponsors;
};
export default createSponsors;
|
carlosrojaso/chapter | server/src/graphql-types/Venue.ts | import { Field, ObjectType, Float } from 'type-graphql';
import { BaseObject } from './BaseObject';
@ObjectType()
export class Venue extends BaseObject {
@Field(() => String)
name: string;
@Field(() => String, { nullable: true })
street_address?: string | null;
@Field(() => String)
city: string;
@Field(() => String)
postal_code: string;
@Field(() => String)
region: string;
@Field(() => String)
country: string;
@Field(() => Float, { nullable: true })
latitude?: number | null;
@Field(() => Float, { nullable: true })
longitude?: number | null;
}
|
carlosrojaso/chapter | client/src/modules/dashboard/Events/components/EventFormUtils.ts | import {
Event,
Venue,
SponsorsQuery,
EventTag,
} from '../../../../generated/graphql';
export interface Field {
key: keyof EventFormData;
label: string;
placeholder?: string;
type: string;
defaultValue?: string;
isRequired: boolean;
}
export type sponsorType = {
name: string;
logo_path: string;
website: string;
type: string;
id: number;
};
export interface EventSponsorTypeInput {
name: string;
type: string;
}
export const sponsorTypes: EventSponsorTypeInput[] = [
{
name: 'Food',
type: 'FOOD',
},
{
name: 'Venue',
type: 'VENUE',
},
{
name: 'Other',
type: 'OTHER',
},
];
export interface EventSponsorInput {
id: number;
type: string;
}
export const fields: Field[] = [
{
key: 'name',
type: 'text',
label: 'Event title',
placeholder: '<NAME>',
isRequired: true,
},
{
key: 'description',
type: 'textarea',
label: 'Description',
placeholder: '',
isRequired: true,
},
{
key: 'image_url',
type: 'text',
label: 'Event Image Url',
placeholder: 'https://www.example.image/url',
isRequired: true,
},
{
key: 'url',
type: 'url',
label: 'Url',
placeholder: '',
isRequired: true,
},
{
key: 'streaming_url',
type: 'url',
label: 'Streaming Url',
placeholder: '',
isRequired: true,
},
{
key: 'capacity',
type: 'number',
label: 'Capacity',
placeholder: '50',
isRequired: true,
},
{
key: 'tags',
type: 'text',
label: 'Tags (separated by a comma)',
placeholder: 'Foo, bar',
isRequired: false,
},
{
key: 'start_at',
type: 'datetime-local',
label: 'Start at',
defaultValue: new Date().toISOString().slice(0, 16),
isRequired: true,
},
{
key: 'ends_at',
type: 'datetime-local',
label: 'End at',
defaultValue: new Date(Date.now() + 1000 * 60 * 60)
.toISOString()
.slice(0, 16),
isRequired: true,
},
];
export interface EventFormData {
name: string;
description: string;
url?: string | null;
image_url: string;
streaming_url?: string | null;
capacity: number;
tags: string;
start_at: string;
ends_at: string;
venue_id?: number | null;
invite_only?: boolean;
sponsors: Array<EventSponsorInput>;
canceled: boolean;
}
export type IEventData = Pick<
Event,
keyof Omit<EventFormData, 'venue_id' | 'tags' | 'sponsors'> | 'id'
> & {
venue_id?: number;
tags: EventTag[];
venue?: Omit<Venue, 'events'> | null;
sponsors: EventSponsorInput[];
};
export interface EventFormProps {
onSubmit: (data: EventFormData, chapterId: number) => void;
loading: boolean;
data?: IEventData;
submitText: string;
chapterId: number;
}
export const formatValue = (field: Field, store?: IEventData): any => {
const { key } = field;
if (!store || !Object.keys(store).includes(key)) {
return field.defaultValue;
}
if (key.endsWith('_at')) {
return new Date(store[field.key]).toISOString().slice(0, 16);
}
if (key === 'tags') {
const tags = store[key];
if (tags) {
return tags.map(({ tag }) => tag.name).join(', ');
}
}
return store[key];
};
export const getAllowedSponsorTypes = (
sponsorData: SponsorsQuery,
sponsorTypes: EventSponsorTypeInput[],
watchSponsorsArray: EventSponsorInput[],
sponsorFieldId: number,
) =>
sponsorTypes.filter(
({ type }) =>
getAllowedSponsorsForType(
sponsorData,
type,
watchSponsorsArray,
sponsorFieldId,
).length,
);
export const getAllowedSponsorsForType = (
sponsorData: SponsorsQuery,
sponsorType: string,
watchSponsorsArray: EventSponsorInput[],
sponsorFieldId?: number,
) =>
sponsorData.sponsors.filter(
(sponsor) =>
sponsor.type === sponsorType &&
!isSponsorSelectedElsewhere(sponsor, watchSponsorsArray, sponsorFieldId),
);
export const getAllowedSponsors = (
sponsorData: SponsorsQuery,
watchSponsorsArray: EventSponsorInput[],
sponsorFieldId?: number,
) =>
sponsorData.sponsors.filter(
(sponsor) =>
!isSponsorSelectedElsewhere(sponsor, watchSponsorsArray, sponsorFieldId),
);
const getSelectedFieldIdForSponsor = (
sponsor: EventSponsorInput,
watchSponsorsArray: EventSponsorInput[],
) =>
watchSponsorsArray.findIndex(
(selectedSponsor) => selectedSponsor.id === sponsor.id,
);
const isSponsorSelectedElsewhere = (
sponsor: EventSponsorInput,
watchSponsorsArray: EventSponsorInput[],
sponsorFieldId?: number,
) => {
const selectedFieldId = getSelectedFieldIdForSponsor(
sponsor,
watchSponsorsArray,
);
return (
selectedFieldId !== -1 &&
(sponsorFieldId === undefined || selectedFieldId !== sponsorFieldId)
);
};
|
carlosrojaso/chapter | server/prisma/generator/factories/instanceRoles.factory.ts | <reponame>carlosrojaso/chapter<filename>server/prisma/generator/factories/instanceRoles.factory.ts
import { prisma } from '../../../src/prisma';
const instancePermissions = ['chapter-create', 'chapter-edit'] as const;
type Permissions = typeof instancePermissions[number];
interface InstanceRole {
name: string;
permissions: Permissions[];
}
const roles: InstanceRole[] = [
{ name: 'administrator', permissions: ['chapter-create', 'chapter-edit'] },
{ name: 'member', permissions: [] },
];
const createRole = async ({ name, permissions }: InstanceRole) => {
const permissionsData = permissions.map((permission) => ({
instance_permission: {
connect: { name: permission },
},
}));
const createdRole = await prisma.instance_roles.create({
data: {
name: name,
instance_role_permissions: { create: permissionsData },
},
});
return { [name]: { name: createdRole.name, id: createdRole.id } };
};
const createInstanceRoles = async () => {
await prisma.instance_permissions.createMany({
data: instancePermissions.map((permission) => ({ name: permission })),
});
return Object.assign({}, ...(await Promise.all(roles.map(createRole))));
};
export default createInstanceRoles;
|
carlosrojaso/chapter | server/src/graphql-types/EventSponsor.ts | import { ObjectType, Field } from 'type-graphql';
import { Sponsor } from './Sponsor';
@ObjectType()
export class EventSponsor {
@Field(() => Sponsor)
sponsor: Sponsor;
}
|
carlosrojaso/chapter | server/src/controllers/Sponsors/resolver.ts | <gh_stars>10-100
import { Prisma } from '@prisma/client';
import { Resolver, Query, Arg, Int, Mutation } from 'type-graphql';
import { Sponsor } from '../../graphql-types/Sponsor';
import { prisma } from '../../prisma';
import { CreateSponsorInputs, UpdateSponsorInputs } from './inputs';
@Resolver()
export class SponsorResolver {
@Query(() => [Sponsor])
sponsors(): Promise<Sponsor[]> {
return prisma.sponsors.findMany();
}
@Query(() => Sponsor, { nullable: true })
sponsor(@Arg('id', () => Int) id: number): Promise<Sponsor | null> {
return prisma.sponsors.findUnique({ where: { id } });
}
@Mutation(() => Sponsor)
createSponsor(@Arg('data') data: CreateSponsorInputs): Promise<Sponsor> {
const sponsorData: Prisma.sponsorsCreateInput = data;
return prisma.sponsors.create({ data: sponsorData });
}
@Mutation(() => Sponsor)
updateSponsor(
@Arg('id', () => Int) id: number,
@Arg('data') data: UpdateSponsorInputs,
): Promise<Sponsor> {
return prisma.sponsors.update({ where: { id }, data });
}
}
|
carlosrojaso/chapter | client/src/pages/dashboard/sponsors/[id]/index.tsx | import { SponsorPage } from '../../../../modules/dashboard/Sponsors/pages/SponsorPage';
export default SponsorPage;
|
carlosrojaso/chapter | client/src/modules/events/index.ts | export { EventPage } from './pages/eventPage';
export { EventsPage } from './pages/eventsPage';
|
carlosrojaso/chapter | client/src/components/ChapterCard.tsx | <reponame>carlosrojaso/chapter<filename>client/src/components/ChapterCard.tsx
import {
Stack,
Heading,
Box,
Center,
Image,
Text,
useColorModeValue,
} from '@chakra-ui/react';
import { Link } from 'chakra-next-link';
import React from 'react';
import { Chapter } from 'generated/graphql';
type ChapterCardProps = {
chapter: Pick<
Chapter,
'id' | 'name' | 'description' | 'category' | 'imageUrl'
>;
};
export const ChapterCard: React.FC<ChapterCardProps> = ({ chapter }) => {
return (
<Center m={2} data-cy="chapter-card">
<Link href={`/chapters/${chapter.id}`} _hover={{}}>
<Box
w={'full'}
bg={useColorModeValue('white', 'gray.800')}
rounded={'md'}
overflow={'hidden'}
>
<Image
h={'168px'}
w={'full'}
src={chapter.imageUrl}
objectFit={'cover'}
/>
<Box>
<Stack spacing={0} align={'center'} mb={5} mt={-20}>
<Heading
data-cy="chapter-heading"
fontSize={'xl'}
fontWeight={500}
fontFamily={'body'}
color={'white'}
textShadow={'1px 1px #000'}
>
{chapter.name}
</Heading>
<Text color={'white'} textShadow={'1px 1px #000'}>
{chapter.category}
</Text>
</Stack>
</Box>
</Box>
</Link>
</Center>
);
};
|
tinovyatkin/typescript-jest-template | src/index.ts | <filename>src/index.ts
/**
* Bolerplate Typescript files
*/
console.log('Hello world!');
|
blamb102/personal-aws-console | src/app/app.routes.ts | import {Routes, RouterModule} from "@angular/router";
import {ModuleWithProviders} from "@angular/core";
import {HomeLandingComponent, AboutComponent, HomeComponent} from "./public/home.component";
import {SecureHomeComponent} from "./secure/landing/securehome.component";
import {MyProfileComponent} from "./secure/profile/myprofile.component";
import {MyS3ObjectComponent} from "./secure/buckets/mys3objects.component";
import {MyInstancesComponent} from "./secure/instances/myinstances.component";
import {JwtComponent} from "./secure/jwttokens/jwt.component";
import {UseractivityComponent} from "./secure/useractivity/useractivity.component";
import {AppComponent} from "./app.component";
import {LoginComponent} from "./public/auth/login/login.component";
import {LogoutComponent} from "./public/auth/logout/logout.component";
const homeRoutes: Routes = [
{
path: '',
redirectTo: '/home/login',
pathMatch: 'full'
},
{
path: 'home',
component: HomeComponent,
children: [
{path: 'about', component: AboutComponent},
{path: 'login', component: LoginComponent},
{path: '', component: HomeLandingComponent}
]
},
];
const secureHomeRoutes: Routes = [
{
path: '',
redirectTo: '/securehome',
pathMatch: 'full'
},
{
path: 'securehome', component: SecureHomeComponent, children: [
{path: 'logout', component: LogoutComponent},
{path: 'jwttokens', component: JwtComponent},
{path: 'myprofile', component: MyProfileComponent},
{path: 'mys3objects', component: MyS3ObjectComponent},
{path: 'myinstances', component: MyInstancesComponent},
{path: 'useractivity', component: UseractivityComponent},
{path: '', component: MyInstancesComponent}]
}
];
const routes: Routes = [
{
path: '',
children: [
...homeRoutes,
...secureHomeRoutes,
{
path: '',
component: HomeComponent
}
]
},
];
export const appRoutingProviders: any[] = [];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
|
blamb102/personal-aws-console | src/app/service/ec2.service.ts | import {environment} from "../../environments/environment";
import {Injectable, Inject} from "@angular/core";
/**
* Created by <NAME>
*/
declare var AWS: any;
export interface Callback {
callback(): void;
callbackWithParam(result: any): void;
}
@Injectable()
export class EC2Service {
constructor() {
}
private getEC2(): any {
AWS.config.update({
region: environment.ec2region
});
var ec2 = new AWS.EC2({
region: environment.ec2region
});
return ec2
}
listInstances(callback: Callback) {
this.getEC2().describeInstances(function (err, result) {
if (err) {
console.log("EC2Service: in listInstances: " + err);
} else {
callback.callbackWithParam(result.Reservations);
}
});
}
getInstanceDnsName(instanceId: string, callback: Callback) {
this.getEC2().describeInstances({InstanceIds: [instanceId]}, function(err, result) {
if (err) {
console.log("EC2Service: in getInstanceDnsName: " + err);
} else {
callback.callbackWithParam(result.Reservations[0].Instances[0].PublicDnsName);
}
});
}
startInstance(instanceId: string, callback: Callback) {
this.getEC2().startInstances({InstanceIds: [instanceId]}, function (err, result) {
if (err) {
console.log("EC2Service: in startInstance: " + err);
} else {
callback.callback();
}
});
}
stopInstance(instanceId: string, callback: Callback) {
this.getEC2().stopInstances({InstanceIds: [instanceId]}, function (err, result) {
if (err) {
console.log("EC2Service: in stopInstance: " + err);
} else {
callback.callback();
}
});
}
checkIfRunning(instanceId: string, isRunningCallback: Callback, notRunningCallback: Callback) {
this.getEC2().describeInstances({InstanceIds: [instanceId]}, function(err, result) {
if (err) {
console.log("EC2Service: in checkIfRunning: " + err);
} else {
if (result.Reservations[0].Instances[0].State.Name=='running') {
isRunningCallback.callback();
} else {
notRunningCallback.callback();
}
}
});
}
checkIfStopped(instanceId: string, isStoppedCallback: Callback, notStoppedCallback: Callback) {
this.getEC2().describeInstances({InstanceIds: [instanceId]}, function(err, result) {
if (err) {
console.log("EC2Service: in checkIfRunning: " + err);
} else {
if (result.Reservations[0].Instances[0].State.Name=='stopped') {
isStoppedCallback.callback();
} else {
notStoppedCallback.callback();
}
}
});
}
describeVolume(volumeId: string, callback: Callback) {
this.getEC2().describeVolumes({VolumeIds: [volumeId]}, function (err, result) {
if (err) {
console.log("EC2Service: in listInstances: " + err);
} else {
if(result.Volumes[0].Attachments.length>0) {
callback.callbackWithParam({
InstanceId: result.Volumes[0].Attachments[0].InstanceId,
State: result.Volumes[0].Attachments[0].State,
Availability: result.Volumes[0].State
});
} else {
callback.callbackWithParam({
InstanceId: 'none',
State: 'none',
Availability: result.Volumes[0].State});
}
}
});
}
attachVolume(volumeId: string, instanceId: string, callback: Callback) {
this.getEC2().attachVolume({VolumeId: volumeId, InstanceId: instanceId, Device: '/dev/sdh'}, function (err, result) {
if (err) {
console.log("EC2Service: in attachVolume: " + err);
} else {
callback.callback();
}
});
}
detachVolume(volumeId: string, callback: Callback) {
this.getEC2().detachVolume({VolumeId: volumeId}, function (err, result) {
if (err) {
console.log("EC2Service: in detachVolume: " + err);
} else {
callback.callback();
}
});
}
checkIfDetached(volumeId: string, isDetachedCallback: Callback, notDetachedCallback: Callback) {
this.getEC2().describeVolumes({VolumeIds: [volumeId]}, function(err, result) {
if (err) {
console.log("EC2Service: in checkIfRunning: " + err);
} else {
if (result.Volumes[0].State=='available') {
isDetachedCallback.callback();
} else {
notDetachedCallback.callback();
}
}
});
}
checkIfAttached(volumeId: string, isAttachedCallback: Callback, notAttachedCallback: Callback) {
this.getEC2().describeVolumes({VolumeIds: [volumeId]}, function(err, result) {
if (err) {
console.log("EC2Service: in checkIfRunning: " + err);
} else {
if (result.Volumes[0].Attachments.length > 0) {
if (result.Volumes[0].Attachments[0].State=='attached') {
isAttachedCallback.callback();
} else {
notAttachedCallback.callback();
}
} else {
notAttachedCallback.callback();
}
}
});
}
}
|
blamb102/personal-aws-console | src/app/public/auth/login/login.component.ts | <gh_stars>0
import {Component, OnInit} from "@angular/core";
import {Router} from "@angular/router";
import {CognitoCallback, UserLoginService, LoggedInCallback} from "../../../service/cognito.service";
import {DynamoDBService} from "../../../service/ddb.service";
@Component({
selector: 'my-aws-console-app',
templateUrl: './login.html'
})
export class LoginComponent implements CognitoCallback, LoggedInCallback, OnInit {
password: string;
errorMessage: string;
constructor(public router: Router,
public ddb: DynamoDBService,
public userService: UserLoginService) {
console.log("LoginComponent constructor");
}
ngOnInit() {
this.errorMessage = null;
console.log("Checking if the user is already authenticated. If so, then redirect to the secure site");
this.userService.isAuthenticated(this);
}
onLogin() {
if (this.password == null) {
this.errorMessage = "Password required";
return;
}
let email = "<EMAIL>"
this.errorMessage = null;
this.userService.authenticate(email, this.password, this);
}
cognitoCallback(message: string, result: any) {
if (message != null) { //error
this.errorMessage = message;
console.log("result: " + this.errorMessage);
} else { //success
this.ddb.writeLogEntry("login");
this.router.navigate(['/securehome']);
}
}
isLoggedIn(message: string, isLoggedIn: boolean) {
if (isLoggedIn)
this.router.navigate(['/securehome']);
}
}
|
blamb102/personal-aws-console | src/app/app.module.ts | <gh_stars>0
import {BrowserModule} from "@angular/platform-browser";
import {NgModule} from "@angular/core";
import {FormsModule} from "@angular/forms";
import {HttpModule} from "@angular/http";
import {AppComponent} from "./app.component";
import {UserLoginService, UserParametersService, CognitoUtil} from "./service/cognito.service";
import {routing} from "./app.routes";
import {HomeComponent, AboutComponent, HomeLandingComponent} from "./public/home.component";
import {AwsUtil} from "./service/aws.service";
import {UseractivityComponent} from "./secure/useractivity/useractivity.component";
import {MyProfileComponent} from "./secure/profile/myprofile.component";
import {MyS3ObjectComponent} from "./secure/buckets/mys3objects.component";
import {MyInstancesComponent} from "./secure/instances/myinstances.component";
import {SecureHomeComponent} from "./secure/landing/securehome.component";
import {JwtComponent} from "./secure/jwttokens/jwt.component";
import {DynamoDBService} from "./service/ddb.service";
import {S3Service} from "./service/s3.service";
import {EC2Service} from "./service/ec2.service";
import {CFService} from "./service/cloudflare.service"
import {LoginComponent} from "./public/auth/login/login.component";
import {LogoutComponent} from "./public/auth/logout/logout.component";
@NgModule({
declarations: [
LoginComponent,
LogoutComponent,
AboutComponent,
HomeLandingComponent,
HomeComponent,
UseractivityComponent,
MyProfileComponent,
MyS3ObjectComponent,
MyInstancesComponent,
SecureHomeComponent,
JwtComponent,
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing
],
providers: [
CognitoUtil,
AwsUtil,
DynamoDBService,
S3Service,
EC2Service,
CFService,
UserLoginService,
UserParametersService],
bootstrap: [AppComponent]
})
export class AppModule {
}
|
blamb102/personal-aws-console | src/app/service/s3.service.ts | <filename>src/app/service/s3.service.ts
import {environment} from "../../environments/environment";
import {Injectable, Inject} from "@angular/core";
/**
* Created by <NAME>
*/
declare var AWS: any;
export interface Callback {
callback(): void;
callbackWithParam(result: any): void;
}
@Injectable()
export class S3Service {
constructor() {
}
private getS3(): any {
AWS.config.update({
region: environment.bucketRegion
});
var s3 = new AWS.S3({
region: environment.bucketRegion,
apiVersion: '2006-03-01',
params: {Bucket: environment.appBucket}
});
return s3
}
listObjects(callback: Callback) {
this.getS3().listObjects(function (err, result) {
if (err) {
console.log("S3Service: in listObjects: " + err);
} else {
callback.callbackWithParam(result.Contents);
}
});
}
getBucketTags(bucket: string, callback: Callback) {
this.getS3().getBucketTagging({Bucket: bucket}, function (err, result) {
if (err) {
console.log("S3Service: in getBucketTagging: " + err);
} else {
callback.callbackWithParam(result.TagSet);
}
});
}
}
|
blamb102/personal-aws-console | src/app/service/cloudflare.service.ts | import {Injectable, Inject} from "@angular/core";
import {S3Service} from "./s3.service";
import {EC2Service} from "./ec2.service";
import {environment} from "../../environments/environment";
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
export interface Callback {
callback(): void;
callbackWithParam(result: any): void;
}
export class CFAPI {
result: Object;
success: Boolean;
}
export class DNS {
user: string;
key: string;
zone: string;
record: string;
has_alt_record: Boolean;
alt_record: string;
}
@Injectable()
export class CFService {
constructor(public s3: S3Service, public ec2: EC2Service, public http: Http) {
}
updateCnameRecord(instanceId: string, application: string) {
console.log("CFService: in updateCnameRecord()");
this.ec2.getInstanceDnsName(instanceId, new CnameTargetReceivedCallback(this, application));
}
restoreDefaultCnameRecord(application: string) {
console.log("CFService: in restoreDefaultCnameRecord()");
this.getCfCredentials(application, new CfCredentialsReceivedCallback(this, application+'.'+environment.defaultURL, application));
}
getCfCredentials(application: string, callback: Callback) {
this.s3.getBucketTags(application+'.'+environment.baseURL, callback);
}
makeCfApiCall(dns: DNS, cname_target: string, application, proxied: Boolean): Observable<CFAPI>{
let headers = new Headers({'X-Auth-Email':dns.user, 'X-Auth-Key': dns.key, 'Content-Type': 'application/json'});
let url = `https://api.cloudflare.com/client/v4/zones/${dns.zone}/dns_records/${dns.record}`;
let api_data = {
type: 'CNAME',
name: application+'.'+environment.baseURL,
content: cname_target,
ttl: 1,
proxied: proxied
}
url = environment.corsProxy+url;
return this.http
.put(url, JSON.stringify(api_data), {headers: headers})
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
if(body.success) {
console.log('DNS update successful')
}
return body || { };
}
private handleError (error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
export class CnameTargetReceivedCallback implements Callback {
constructor(public me: CFService, public application: string) {}
callback() {}
callbackWithParam(cname_target: string) {
this.me.getCfCredentials(this.application, new CfCredentialsReceivedCallback(this.me, cname_target, this.application));
}
}
export class CfCredentialsReceivedCallback implements Callback {
constructor(public me: CFService, public cname_target: string, public application: string) {}
callback() {}
callbackWithParam(result: any) {
var dns = new DNS();
dns.has_alt_record = false;
for (let i = 0; i < result.length; i++) {
if (result[i].Key=='dns_user') {
dns.user = result[i].Value;
} else if (result[i].Key=='dns_key') {
dns.key = result[i].Value;
} else if (result[i].Key=='dns_zone') {
dns.zone = result[i].Value;
} else if (result[i].Key=='dns_record') {
dns.record = result[i].Value;
} else if (result[i].Key=='dns_alt_record') {
dns.has_alt_record = true;
dns.alt_record = result[i].Value;
}
}
this.me.makeCfApiCall(dns, this.cname_target, this.application, true).subscribe();
if(dns.has_alt_record) {
dns.record = dns.alt_record;
this.me.makeCfApiCall(dns, this.cname_target, 'tensorboard', false).subscribe();
}
}
}
|
blamb102/personal-aws-console | src/app/secure/buckets/mys3objects.component.ts | import {Component} from "@angular/core";
import {LoggedInCallback, UserLoginService, Callback} from "../../service/cognito.service";
import {S3Service} from "../../service/s3.service";
import {Router} from "@angular/router";
export class Objects {
key: string;
}
declare var AWS: any;
@Component({
selector: 'my-aws-console-app',
templateUrl: './mys3objects.html'
})
export class MyS3ObjectComponent implements LoggedInCallback {
public objects: Array<Objects> = [];
public cognitoId: String;
constructor(public router: Router, public userService: UserLoginService, public s3: S3Service) {
this.userService.isAuthenticated(this);
console.log("In MyS3ObjectsComponent");
}
isLoggedIn(message: string, isLoggedIn: boolean) {
if (!isLoggedIn) {
this.router.navigate(['/home/login']);
} else {
this.s3.listObjects(new GetS3ObjectsCallback(this));
}
}
}
export class GetS3ObjectsCallback implements Callback {
constructor(public me: MyS3ObjectComponent) {
}
callback() {
}
callbackWithParam(result: any) {
console.log("Result 1: " + result[0].Key)
for (let i = 0; i < result.length; i++) {
let object = new Objects();
object.key = result[i].Key;
this.me.objects.push(object);
}
}
}
|
blamb102/personal-aws-console | src/app/public/auth/logout/logout.component.ts | <gh_stars>0
import {Component, OnInit, OnDestroy} from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {UserLoginService, LoggedInCallback} from "../../../service/cognito.service";
@Component({
selector: 'my-aws-console-app',
template: ''
})
export class LogoutComponent implements LoggedInCallback {
constructor(public router: Router,
public userService: UserLoginService) {
this.userService.isAuthenticated(this)
}
isLoggedIn(message: string, isLoggedIn: boolean) {
if (isLoggedIn) {
this.userService.logout();
this.router.navigate(['']);
}
this.router.navigate(['']);
}
}
|
blamb102/personal-aws-console | src/app/secure/instances/myinstances.component.ts | import {Component} from "@angular/core";
import {LoggedInCallback, UserLoginService, Callback} from "../../service/cognito.service";
import {EC2Service} from "../../service/ec2.service";
import {CFService} from "../../service/cloudflare.service";
import {Router} from "@angular/router";
import {environment} from "../../../environments/environment";
export class Instances {
name: string;
id: string;
type: string;
state: string;
ip: string;
}
export class Volume {
volumeId: string;
state: string;
availability: string;
attachment: string;
}
declare var AWS: any;
@Component({
selector: 'my-aws-console-app',
templateUrl: './myinstances.html'
})
export class MyInstancesComponent implements LoggedInCallback {
public nb_instances: Array<Instances> = [];
public che_instances: Array<Instances> = [];
public volume: Volume = new Volume();
public cognitoId: String;
public liveInstances: Boolean = false;
public disableVolumeInputs: Boolean = false;
constructor(public router: Router, public userService: UserLoginService, public ec2: EC2Service, public cf: CFService) {
this.volume.volumeId = environment.jupyterVolumeId;
this.userService.isAuthenticated(this);
console.log("In MyInstancesComponent");
}
isLoggedIn(message: string, isLoggedIn: boolean) {
if (!isLoggedIn) {
this.router.navigate(['/home/login']);
} else {
this.ec2.listInstances(new GetInstancesCallback(this));
this.ec2.describeVolume(this.volume.volumeId, new DescribeVolumeCallback(this));
}
}
onAction(instance: Instances, application: string) {
if (instance.state=='stopped') {
this.ec2.startInstance(instance.id, new StartInstanceCallback(this, instance, application));
}
if (instance.state=='running') {
this.ec2.stopInstance(instance.id, new StopInstanceCallback(this, instance));
this.cf.restoreDefaultCnameRecord(application);
}
}a
onConnect(application: string) {
if (application=='jupyter') {
var newWindow = window.open(`http://jupyter.brianlambson.com`);
} else if (application=='che') {
var newWindow = window.open(`http://che.brianlambson.com/dashboard`);
}
}
onMoveVolume(instanceId: string) {
this.disableVolumeInputs = true;
if (this.volume.availability=='in-use') {
this.ec2.detachVolume(this.volume.volumeId, new DetachVolumeCallback(this, instanceId));
} else {
this.ec2.attachVolume(this.volume.volumeId, instanceId, new VolumeAttachedCallback(this));
}
}
}
export class GetInstancesCallback implements Callback {
constructor(public me: MyInstancesComponent) {}
callback() {}
callbackWithParam(result: any) {
this.me.nb_instances = [];
this.me.che_instances = [];
this.me.liveInstances = false;
for (let i = 0; i < result.length; i++) {
for (let j = 0; j < result[i].Instances.length; j++){
if (result[i].Instances[j].State.Name == 'terminated') { continue; }
let instance = new Instances();
instance.id = result[i].Instances[j].InstanceId;
instance.type = result[i].Instances[j].InstanceType;
instance.state = result[i].Instances[j].State.Name;
instance.ip = result[i].Instances[j].PublicIpAddress;
instance.name = 'no-name';
let application = 'none';
for(let k = 0; k < result[i].Instances[j].Tags.length; k++) {
if (result[i].Instances[j].Tags[k].Key=='Name'){
instance.name = result[i].Instances[j].Tags[k].Value;
} else if (result[i].Instances[j].Tags[k].Key=='application') {
application = result[i].Instances[j].Tags[k].Value;
}
}
if (application == 'jupyter') {
if (instance.state != 'stopped') { this.me.liveInstances = true }
this.me.nb_instances.push(instance);
} else if (application == 'che') {
this.me.che_instances.push(instance);
}
}
}
}
}
export class StartInstanceCallback implements Callback {
constructor(public me: MyInstancesComponent, public instance: Instances, public application: string) {}
callback() {
let irc = new InstanceRunningCallback(this.me, this.instance, this.application);
let wfrc = new WaitForRunningCallback(this.me, this.instance, irc)
this.me.ec2.checkIfRunning(this.instance.id, irc, wfrc);
this.me.ec2.listInstances(new GetInstancesCallback(this.me));
}
callbackWithParam(result: any) {}
}
export class WaitForRunningCallback implements Callback {
constructor(public me: MyInstancesComponent, public instance: Instances, public irc: InstanceRunningCallback) {}
private sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async callback() {
await this.sleep(2000);
this.me.ec2.checkIfRunning(this.instance.id, this.irc, this);
}
callbackWithParam(result: any) {}
}
export class InstanceRunningCallback implements Callback {
constructor(public me: MyInstancesComponent, public instance: Instances, public application: string) {}
callback() {
this.me.cf.updateCnameRecord(this.instance.id, this.application);
this.me.ec2.listInstances(new GetInstancesCallback(this.me));
}
callbackWithParam() {}
}
export class StopInstanceCallback implements Callback {
constructor(public me: MyInstancesComponent, public instance: Instances) {}
callback() {
let isc = new InstanceStoppedCallback(this.me);
let wfsc = new WaitForStoppedCallback(this.me, this.instance, isc)
this.me.ec2.checkIfStopped(this.instance.id, isc, wfsc);
this.me.ec2.listInstances(new GetInstancesCallback(this.me));
}
callbackWithParam(result: any) {}
}
export class WaitForStoppedCallback implements Callback {
constructor(public me: MyInstancesComponent, public instance: Instances, public isc: InstanceStoppedCallback) {}
private sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async callback() {
await this.sleep(2000);
this.me.ec2.checkIfStopped(this.instance.id, this.isc, this);
}
callbackWithParam(result: any) {}
}
export class InstanceStoppedCallback implements Callback {
constructor(public me: MyInstancesComponent) {}
callback() {
this.me.ec2.listInstances(new GetInstancesCallback(this.me));
}
callbackWithParam(result: any) {}
}
export class DescribeVolumeCallback implements Callback {
constructor(public me: MyInstancesComponent) {}
callback() {}
callbackWithParam(result: any) {
this.me.volume.attachment = result.InstanceId;
this.me.volume.state = result.State;
this.me.volume.availability = result.Availability;
}
}
export class DetachVolumeCallback implements Callback {
constructor(public me: MyInstancesComponent, public instanceId: string) {}
callback() {
let vdc = new VolumeDetachedCallback(this.me, this.instanceId);
let wfdc = new WaitForDetachedCallback(this.me, vdc)
this.me.ec2.checkIfDetached(this.me.volume.volumeId, vdc, wfdc);
this.me.ec2.describeVolume(this.me.volume.volumeId, new DescribeVolumeCallback(this.me));
}
callbackWithParam(result: any) {}
}
export class WaitForDetachedCallback implements Callback {
constructor(public me: MyInstancesComponent, public vdc: VolumeDetachedCallback) {}
private sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async callback() {
await this.sleep(2000);
this.me.ec2.checkIfDetached(this.me.volume.volumeId , this.vdc, this);
}
callbackWithParam(result: any) {}
}
export class VolumeDetachedCallback implements Callback {
constructor(public me: MyInstancesComponent, public instanceId: string) {}
callback() {
this.me.ec2.attachVolume(this.me.volume.volumeId, this.instanceId, new AttachVolumeCallback(this.me));
this.me.ec2.describeVolume(this.me.volume.volumeId, new DescribeVolumeCallback(this.me));
}
callbackWithParam(result: any) {}
}
export class AttachVolumeCallback implements Callback {
constructor(public me: MyInstancesComponent) {}
callback() {
let vac = new VolumeAttachedCallback(this.me);
let wfac = new WaitForAttachedCallback(this.me, vac)
this.me.ec2.checkIfAttached(this.me.volume.volumeId, vac, wfac);
this.me.ec2.describeVolume(this.me.volume.volumeId, new DescribeVolumeCallback(this.me));
}
callbackWithParam(result: any) {}
}
export class WaitForAttachedCallback implements Callback {
constructor(public me: MyInstancesComponent, public vac: VolumeAttachedCallback) {}
private sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async callback() {
await this.sleep(2000);
this.me.ec2.checkIfAttached(this.me.volume.volumeId, this.vac, this);
}
callbackWithParam(result: any) {}
}
export class VolumeAttachedCallback implements Callback {
constructor(public me: MyInstancesComponent) {}
callback() {
console.log('MyInstancesComponent: Volume Attached to Instance')
this.me.ec2.describeVolume(this.me.volume.volumeId, new DescribeVolumeCallback(this.me))
this.me.disableVolumeInputs = false;
}
callbackWithParam(result: any) {}
}
|
blamb102/personal-aws-console | src/environments/environment.ts | export const environment = {
production: false,
region: 'us-west-2',
identityPoolId: 'us-west-2:09114ff0-a193-4d71-8e75-6ed12e3ede1b',
userPoolId: 'us-west-2_Tr3dvlT5B',
clientId: '4galnav88qp60eicu9f17bjf3f',
appBucket: 'my-aws-console-app',
bucketRegion: 'us-west-2',
ec2region: 'us-west-2',
jupyterVolumeId: 'vol-0d1867e98dc62503e',
ddbTableName: 'brianlambson-angular2-app',
corsProxy: 'https://cors-anywhere.herokuapp.com/',
baseURL: 'brianlambson.com',
defaultURL: 'brianlambson.com.s3-website-us-west-2.amazonaws.com'
};
|
1-aquila-1/typescript | 01-curso/cod3r-01/Introducao/funcoes.ts | <gh_stars>0
// string
let nome: string = 'João'
function retornaMeuNome(): string {
// return minhaIdade
return nome
}
// console.log(retornaMeuNome())
function digaOi(): void {
console.log('Oi')
}
// digaOi()
function multiplicar(numA: any, numB: any): number {
return numA * numB
}
function soma(numA: number, numB: number): number {
return numA + numB
}
// console.log(soma(2, 2))
// console.log(multiplicar(4.7, 9))
// tipo função
let calculo: (x: number, y: number) => number
calculo = multiplicar
console.log(calculo(5, 6)) |
1-aquila-1/typescript | 01-curso/cod3r-01/Introducao/tipos/tuplas.ts | <gh_stars>0
let endereco: [string, number] = ['Av. Principal', 99]
console.log(endereco) |
1-aquila-1/typescript | 01-curso/cod3r-01/Introducao/tipos/enums.ts | enum Cor {
Cinza,
Verde,
Azul
}
let minhaCor: Cor = Cor.Verde
// console.log(minhaCor)
enum UF {
PA = "Pará",
SP = "São Paulo"
}
let meuEstado: UF = UF.PA
console.log(meuEstado) |
1-aquila-1/typescript | 01-curso/cod3r-01/Introducao/tipos/tipos.ts | <gh_stars>0
enum Cor{
verde = 10,
azul = 15
}
let cor: Cor = Cor.verde
console.log(cor)
|
1-aquila-1/typescript | 01-curso/01-curso/interfaces/interfaces.ts | interface Humano {
nome: string,
idade?: number
saudar(sobrenome: string):void
}
function saudarComOla(pessoa: Humano){
console.log('Olá', pessoa.nome)
}
function mudarNome(pessoa: Humano){
pessoa.nome = 'Pedro'
}
const pedro: Humano = {
nome: 'Áquila',
idade: 30,
saudar(sobrenome: string){
console.log("Olá, " + this.nome + " " + sobrenome)
}
}
saudarComOla(pedro)
mudarNome(pedro)
saudarComOla(pedro)
pedro.saudar('Tavares')
class Cliente implements Humano{
nome: string = ''
saudar(sobrenome: string): void {
console.log("Olá, " + this.nome + " " + sobrenome)
}
}
const joao = new Cliente()
joao.nome = "João"
saudarComOla(joao)
interface FuncaoCalculo{
(a: number, b: number): number
}
let potencia: FuncaoCalculo
potencia = function(base: number, exp: number): number{
return Math.pow(base, exp)
}
console.log(potencia(3, 2)) |
1-aquila-1/typescript | 01-curso/cod3r-01/Introducao/tipos/arry.ts | let hobbies: any[] = [1, 2]
console.log(hobbies)
hobbies = ['a', 'b', 'c', 2]
|
TheDancingCode/craft | tailoff/js/components/toggle.component.ts | <gh_stars>0
import { DOMHelper } from '../utils/domHelper';
import { ScrollHelper } from '../utils/scroll';
export class ToggleComponent {
private animationSpeed = 400;
private scrollSpeed = 400;
constructor() {
const targets = document.querySelectorAll('[data-s-toggle]');
Array.from(targets).forEach((t: HTMLElement) => {
this.initToggleTarget(t);
});
DOMHelper.onDynamicContent(document.documentElement, '[data-s-toggle]', (targets) => {
Array.from(targets).forEach((t: HTMLElement) => {
if (!t.classList.contains('toggle-initialized')) {
this.initToggleTarget(t);
}
});
});
}
private initToggleTarget(target: HTMLElement) {
const triggers = document.querySelectorAll(`[data-s-toggle-target="${target.id}"]`);
const height = parseInt(target.getAttribute('data-s-toggle-height'));
const margin = parseInt(target.getAttribute('data-s-toggle-margin')) ?? 0;
if (height) {
if (target.scrollHeight > height + (height * margin) / 100) {
target.style.maxHeight = `${height}px`;
} else {
Array.from(triggers).forEach((trigger: HTMLElement) => {
trigger.parentElement.removeChild(trigger);
})
}
}
Array.from(triggers).forEach((trigger: HTMLElement) => {
this.initToggleTrigger(trigger, target);
})
}
private initToggleTrigger(trigger: HTMLElement, target) {
const animation = target.getAttribute('data-s-toggle-animation');
const changeClass = target.getAttribute('data-s-toggle-class') ?? 'hidden';
const defaultExpanded = target.getAttribute('data-s-toggle-default-expanded');
const group = target.getAttribute('data-s-toggle-group');
if (defaultExpanded) {
trigger.setAttribute('aria-expanded', 'true');
} else {
trigger.setAttribute('aria-expanded', 'false');
}
trigger.setAttribute('aria-controls', target.id);
trigger.setAttribute('tabindex', '0');
trigger.addEventListener('click', (e) => {
e.preventDefault();
if (group) {
const groupElement = document.querySelector(`#${group}`) as HTMLElement;
const activeEl = groupElement.querySelector('[data-s-toggle-target][aria-expanded="true"]');
if (activeEl && activeEl !== trigger) {
const activeTarget = document.querySelector(`#${activeEl.getAttribute('data-s-toggle-target')}`);
this.toggleAction(activeEl, activeTarget, changeClass, animation);
}
}
this.toggleAction(trigger, target, changeClass, animation);
});
trigger.addEventListener('open', () => {
this.toggleAction(trigger, target, changeClass, animation);
});
}
private toggleAction(trigger, target, changeClass, animation) {
const expanded = trigger.getAttribute('aria-expanded') === 'true';
const linkedButtons = document.querySelectorAll(`[data-s-toggle-target='${target.id}']`);
Array.from(linkedButtons).forEach((b) => {
this.switchButtonState(b);
});
if (trigger.getAttribute('data-s-toggle-scroll')) {
const scrollToElement = document.querySelector(`${trigger.getAttribute('data-s-toggle-scroll')}`) as HTMLElement;
if (scrollToElement) {
ScrollHelper.scrollToY(scrollToElement, this.scrollSpeed);
}
}
if (expanded) {
if (animation) {
this.hideAnimated(target, changeClass, animation);
} else {
target.classList.add(changeClass);
}
} else {
if (target.hasAttribute('data-s-toggle-height')) {
trigger.parentElement.removeChild(trigger);
}
if (animation) {
this.showAnimated(target, changeClass, animation);
} else {
target.style.maxHeight = 'none';
target.classList.remove(changeClass);
}
}
}
private switchButtonState(button) {
const expanded = button.getAttribute('aria-expanded') === 'true';
button.setAttribute('aria-expanded', expanded ? 'false' : 'true');
}
private showAnimated(el, changeClass, animation) {
let speed = this.animationSpeed;
if (parseInt(animation)) {
speed = parseInt(animation);
el.style.transitionDuration = `${speed}ms`;
}
const height = this.getHeight(el); // Get the natural height
el.classList.remove(changeClass); // Make the element visible
el.style.maxHeight = height; // Update the max-height
// Once the transition is complete, remove the inline max-height so the content can scale responsively
window.setTimeout(function () {
el.style.maxHeight = 'none';
}, speed);
}
// Hide an element
private hideAnimated(el, changeClass, animation) {
let speed = this.animationSpeed;
if (parseInt(animation)) {
speed = parseInt(animation);
el.style.transitionDuration = `${speed}ms`;
}
// Give the element a height to change from
el.style.maxHeight = el.scrollHeight + 'px';
// Set the height back to 0
window.setTimeout(function () {
el.style.maxHeight = '0';
}, 1);
// When the transition is complete, hide it
window.setTimeout(function () {
el.classList.add(changeClass);
}, speed);
}
private getHeight(el) {
el.style.display = 'block'; // Make it visible
var height = el.scrollHeight + 'px'; // Get it's height
el.style.display = ''; // Hide it again
return height;
}
}
|
TheDancingCode/craft | tailoff/js/utils/scroll.ts | <filename>tailoff/js/utils/scroll.ts
export class ScrollHelper {
constructor() {}
public static scrollToY(elementY: HTMLElement, duration: number) {
const rect = elementY.getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const startingY =
(window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0);
const diff = rect.top + scrollTop - startingY;
let start;
window.requestAnimationFrame(function step(timestamp) {
if (!start) start = timestamp;
var time = timestamp - start;
var percent = Math.min(time / duration, 1);
window.scrollTo(0, startingY + diff * percent);
if (time < duration) {
window.requestAnimationFrame(step);
}
});
}
}
|
TheDancingCode/craft | tailoff/js/plugins/modal/image.plugin.ts | import { ModalComponent } from '../../components/modal.component';
import { AnimationHelper } from '../../utils/animationHelper';
import { ArrayPrototypes } from '../../utils/prototypes/array.prototypes';
import { ModalPlugin } from './plugin.interface';
ArrayPrototypes.activateFrom();
export class ImageModalPlugin implements ModalPlugin {
private triggerClass = 'js-modal-image';
private modalComponent: ModalComponent;
private galleryType: string;
private image: HTMLImageElement;
private imageResizeListener;
private imageTabTrapListener;
private caption: HTMLDivElement;
private captionGroup: Array<string>;
private options = {
imageMargin: 20,
imageMarginNav: 80,
imageMarginNoneBreakPoint: 820,
resizeDuration: 100,
fadeDuration: 100,
};
constructor(modalComponent: ModalComponent, options: Object = {}) {
this.options = { ...this.options, ...options };
this.modalComponent = modalComponent;
}
public initElement() {
const imageTriggers = document.querySelectorAll(`.${this.triggerClass}`);
Array.from(imageTriggers).forEach((trigger) => {
this.initImageTrigger(trigger);
});
}
public afterCreateModal() {
this.caption = document.createElement('div');
this.caption.classList.add('hidden');
this.caption.classList.add('modal__caption');
this.modalComponent.modalContent.insertAdjacentElement('beforeend', this.caption);
}
public getTriggerClass() {
return this.triggerClass;
}
public openModalClick(trigger: HTMLElement) {
this.modalComponent.trigger = trigger;
if (trigger.classList.contains(this.triggerClass)) {
const src = this.modalComponent.getTriggerSrc(trigger);
const caption = trigger.getAttribute('data-caption');
src ? this.openImageModal(src, caption) : console.log('No modal src is provided on the trigger');
}
}
public gotoNextAction() {
this.changeGroupIndex();
}
public gotoPrevAction() {
this.changeGroupIndex();
}
public closeModal() {
document.removeEventListener('keydown', this.imageTabTrapListener);
window.removeEventListener('resize', this.imageResizeListener);
}
private changeGroupIndex() {
this.image.classList.add('hidden');
this.modalComponent.modalLoader.classList.remove('hidden');
this.image.setAttribute('src', this.modalComponent.galleryGroup[this.modalComponent.currentGroupIndex]);
if (this.captionGroup[this.modalComponent.currentGroupIndex]) {
this.caption.innerText = this.captionGroup[this.modalComponent.currentGroupIndex];
this.caption.classList.remove('hidden');
} else {
this.caption.classList.add('hidden');
}
}
public openImageModal(src: string, caption: string = null) {
this.galleryType = 'image';
this.modalComponent.createOverlay();
this.modalComponent.createModal('modal__dialog--image', 'modal__image');
this.modalComponent.galleryGroup = [];
this.captionGroup = [];
this.caption.style.opacity = '0';
const group = this.modalComponent.trigger.getAttribute('data-group');
if (group) {
this.modalComponent.galleryGroup = Array.from(document.querySelectorAll(`[data-group=${group}]`)).map((t) =>
this.modalComponent.getTriggerSrc(t)
);
const captions = document.querySelectorAll(`[data-group=${group}][data-caption]`);
if (captions.length > 0) {
this.captionGroup = Array.from(document.querySelectorAll(`[data-group=${group}]`)).map((t) =>
t.getAttribute('data-caption')
);
}
this.modalComponent.currentGroupIndex = this.modalComponent.galleryGroup.indexOf(src);
this.modalComponent.addNavigation();
if (this.captionGroup[this.modalComponent.currentGroupIndex]) {
this.caption.innerText = this.captionGroup[this.modalComponent.currentGroupIndex];
this.caption.classList.remove('hidden');
} else {
this.caption.classList.add('hidden');
}
} else {
if (caption) {
this.caption.innerText = caption;
this.caption.classList.remove('hidden');
} else {
this.caption.classList.add('hidden');
}
}
this.modalComponent.modalLoader = document.createElement('div');
this.modalComponent.modalLoader.classList.add('modal__loader-wrapper');
this.modalComponent.modalLoader.insertAdjacentHTML('afterbegin', `<div class="modal__loader"></div>`);
this.modalComponent.modalContent.insertAdjacentElement('afterbegin', this.modalComponent.modalLoader);
this.image = document.createElement('img');
this.image.addEventListener('load', (e) => {
this.modalComponent.modalLoader.classList.add('hidden');
this.setImageSize(null, true);
});
this.image.setAttribute('src', src);
this.image.classList.add('hidden');
this.modalComponent.modalContent.insertAdjacentElement('afterbegin', this.image);
this.imageResizeListener = this.setImageSize.bind(this);
window.addEventListener('resize', this.imageResizeListener);
this.initGalleryTabTrap();
}
private initGalleryTabTrap() {
this.modalComponent.updateGalleryTabIndexes();
this.imageTabTrapListener = this.imagesTrapTab.bind(this);
document.addEventListener('keydown', this.imageTabTrapListener);
this.modalComponent.modalContent.focus();
}
private imagesTrapTab(event) {
const keyCode = event.which || event.keyCode; // Get the current keycode
// If it is TAB
if (keyCode === 9) {
// Move focus to first element that can be tabbed if Shift isn't used
if (event.target === this.modalComponent.lastTabbableElement && !event.shiftKey) {
event.preventDefault();
(this.modalComponent.firstTabbableElement as HTMLElement).focus();
// Move focus to last element that can be tabbed if Shift is used
} else if (event.target === this.modalComponent.firstTabbableElement && event.shiftKey) {
event.preventDefault();
(this.modalComponent.lastTabbableElement as HTMLElement).focus();
}
}
}
private setImageSize(_, newImage = false) {
let imageWidth = this.image.naturalWidth;
let imageHeight = this.image.naturalHeight;
let maxWidth = window.innerWidth;
let maxHeight = window.innerHeight;
if (window.innerWidth > this.options.imageMarginNoneBreakPoint) {
maxWidth = this.modalComponent.galleryGroup.length
? window.innerWidth - this.options.imageMarginNav * 2
: window.innerWidth - this.options.imageMargin * 2;
maxHeight = window.innerHeight - this.options.imageMargin * 2;
}
if (imageWidth > maxWidth || imageHeight > maxHeight) {
if (imageWidth / maxWidth >= imageHeight / maxHeight) {
imageHeight *= maxWidth / imageWidth;
imageWidth = maxWidth;
} else {
imageWidth *= maxHeight / imageHeight;
imageHeight = maxHeight;
}
}
if (this.options.resizeDuration === 0 || !newImage) {
this.modalComponent.modalContent.style.width = `${Math.round(imageWidth)}px`;
this.modalComponent.modalContent.style.height = `${Math.round(imageHeight)}px`;
this.image.classList.remove('hidden');
} else {
AnimationHelper.cssPropertyAnimation(
this.modalComponent.modalContent,
'width',
Math.round(imageWidth),
'px',
this.options.resizeDuration
);
AnimationHelper.cssPropertyAnimation(
this.modalComponent.modalContent,
'height',
Math.round(imageHeight),
'px',
this.options.resizeDuration,
() => {
this.image.style.opacity = '0';
this.image.classList.remove('hidden');
AnimationHelper.cssPropertyAnimation(this.image, 'opacity', 1, '', this.options.fadeDuration);
AnimationHelper.cssPropertyAnimation(this.caption, 'opacity', 1, '', this.options.fadeDuration);
}
);
}
}
private initImageTrigger(trigger: Element) {
trigger.setAttribute('role', 'button');
trigger.classList.add('modal__image-trigger');
}
}
|
TheDancingCode/craft | tailoff/js/components/indeterminateChecks.component.ts | <reponame>TheDancingCode/craft
export class IndeterminateChecksComponent {
constructor() {
Array.from(document.querySelectorAll('ul.js-indeterminate-checks')).forEach((list: HTMLUListElement, index) => {
new IndeterminateChecks(list, index);
});
}
}
class IndeterminateChecks {
private mainList: HTMLUListElement;
private mainListIndex = 0;
private jsChange;
constructor(element: HTMLUListElement, index) {
this.mainList = element;
this.mainListIndex = index;
this.jsChange = document.createEvent('HTMLEvents');
this.jsChange.initEvent('jschange', false, true);
this.init();
}
private init() {
this.initSubLists();
this.initToggles();
this.initCheckboxes();
}
private initCheckboxes() {
Array.from(this.mainList.querySelectorAll('input[type=checkbox]')).forEach((checkbox: HTMLInputElement) => {
checkbox.addEventListener('change', this.onCheckboxChange.bind(this));
if (checkbox.checked) {
this.checkUp(checkbox);
}
});
}
private initSubLists() {
Array.from(this.mainList.querySelectorAll('ul.js-indeterminate-sub-list')).forEach(
(list: HTMLUListElement, index) => {
const subLevelID = `jsIndeterminateSubList${this.mainListIndex}-${index}`;
list.setAttribute('id', subLevelID);
}
);
}
private onCheckboxChange(e) {
this.checkUp(e.target);
this.checkDown(e.target);
if (e.target.checked) {
const listItem = e.target.closest('li') as HTMLLIElement;
const subList = listItem.querySelector('ul');
if (subList && subList.classList.contains('hidden')) {
subList.classList.remove('hidden');
const toggle = listItem.querySelector('.js-indeterminate-toggle');
toggle.setAttribute('aria-expanded', 'true');
}
}
}
private checkUp(check: HTMLInputElement) {
const list = check.closest('ul.js-indeterminate-sub-list');
if (list) {
let nbrOfUnchecked = 0;
let nbrOfChecked = 0;
let nbrOfIndeterminate = 0;
Array.from(this.mainList.querySelectorAll(`#${list.getAttribute('id')} > li > *:not(ul) input`)).forEach(
(input: HTMLInputElement) => {
if (input.checked || input.indeterminate) {
if (input.indeterminate) {
nbrOfIndeterminate++;
} else {
nbrOfChecked++;
}
} else {
nbrOfUnchecked++;
}
}
);
const parentInput = list.closest('li').querySelector('input[type=checkbox]') as HTMLInputElement;
if (nbrOfUnchecked === 0 && nbrOfIndeterminate === 0 && nbrOfChecked > 0) {
parentInput.indeterminate = false;
parentInput.checked = true;
} else {
if (nbrOfChecked > 0 || nbrOfIndeterminate > 0) {
parentInput.indeterminate = true;
parentInput.checked = false;
} else {
parentInput.indeterminate = false;
parentInput.checked = false;
}
}
parentInput.dispatchEvent(this.jsChange);
this.checkUp(parentInput);
}
}
private checkDown(check: HTMLInputElement) {
const subList = check.closest('li').querySelector('ul');
if (subList) {
Array.from(subList.querySelectorAll('input[type=checkbox]')).forEach((input: HTMLInputElement) => {
input.checked = check.checked;
input.dispatchEvent(this.jsChange);
});
}
}
private initToggles() {
const toggles = Array.from(this.mainList.querySelectorAll('.js-indeterminate-toggle'));
if (toggles.length > 0) {
toggles.forEach((toggle, index) => {
toggle.addEventListener('click', this.onToggleClick.bind(this));
toggle.setAttribute('aria-expanded', 'false');
// toggle.setAttribute(
// "aria-controls",
// toggle.closest("li").querySelector("ul").getAttribute("id")
// );
});
if (this.mainList.getAttribute('data-s-indeterminate-toggle-open') != null) {
if (this.mainList.getAttribute('data-s-indeterminate-toggle-open') == 'false') {
Array.from(this.mainList.querySelectorAll('ul')).forEach((list) => {
const toggle = list.closest('li').querySelector('.js-indeterminate-toggle');
toggle.setAttribute('aria-expanded', 'true');
if (this.mainList.getAttribute('data-s-indeterminate-open-checked')) {
if (list.querySelectorAll('input:checked').length === 0) {
list.classList.add('hidden');
toggle.setAttribute('aria-expanded', 'false');
}
} else {
list.classList.add('hidden');
toggle.setAttribute('aria-expanded', 'false');
}
});
}
}
}
}
private onToggleClick(e) {
e.preventDefault();
this.toggleLevel(e.target);
}
private toggleLevel(toggle: HTMLElement) {
if (!toggle.classList.contains('js-indeterminate-toggle')) {
toggle = toggle.closest('.js-indeterminate-toggle');
}
const listItem = toggle.closest('li') as HTMLLIElement;
const subList = listItem.querySelector('ul');
if (subList.classList.contains('hidden')) {
subList.classList.remove('hidden');
toggle.setAttribute('aria-expanded', 'true');
} else {
subList.classList.add('hidden');
toggle.setAttribute('aria-expanded', 'false');
}
}
}
|
TheDancingCode/craft | tailoff/js/components/tooltip.component.ts | import tippy from 'tippy.js';
export class TooltipComponent {
constructor() {
if (document.querySelectorAll('[data-tippy-content]').length > 0) {
this.initTippy();
}
}
private async initTippy() {
// @ts-ignore
const tippy = await import('tippy.js');
tippy.default('[data-tippy-content]');
tippy.default('[data-tippy-template]', {
content(reference) {
const id = reference.getAttribute('data-tippy-template');
const template = document.getElementById(id);
return template.innerHTML;
},
allowHTML: true,
});
}
}
|
TheDancingCode/craft | tailoff/js/components/pullOut.component.ts | import { DOMHelper } from '../utils/domHelper';
export class PullOutComponent {
constructor() {
if (document.querySelectorAll('.js-pull-out').length > 0) {
this.pullOutBlocks();
window.addEventListener('resize', this.pullOutBlocks.bind(this));
}
DOMHelper.onDynamicContent(document.documentElement, '.js-pull-out', (pullOuts) => {
this.pullOutBlocks();
});
}
private pullOutBlocks() {
Array.from(document.querySelectorAll('.js-pull-out')).forEach((block: HTMLElement) => {
const noContent = block.getAttribute('data-no-content') ? block.getAttribute('data-no-content') == 'true' : false;
const direction = block.getAttribute('data-direction');
const queryObject = block.getAttribute('data-query');
if (direction) {
const max = block.getAttribute('data-max') ? parseInt(block.getAttribute('data-max')) : window.innerWidth;
const breakpoint = block.getAttribute('data-breakpoint') ? parseInt(block.getAttribute('data-breakpoint')) : 0;
this.pullOutBlock(block, direction, breakpoint, max, noContent);
} else if (queryObject) {
const query = JSON.parse(queryObject);
let queryHit = null;
query.forEach((q) => {
if (q.breakpoint < window.innerWidth) {
queryHit = q;
}
});
if (queryHit) {
queryHit['direction'] = queryHit.direction ?? 'both';
queryHit['breakpoint'] = queryHit.breakpoint ?? 0;
queryHit['max'] = queryHit.max ?? window.innerWidth;
this.pullOutBlock(block, queryHit.direction, queryHit.breakpoint, queryHit.max, noContent);
}
} else {
console.error(
"You must have a data element with name 'data-direction' or 'data-query' defined in order for the pull out plugin to work."
);
}
});
}
private pullOutBlock(block: HTMLElement, direction: string, breakpoint: number, max: number, noContent = false) {
const rect = block.parentElement.getBoundingClientRect();
const offset = {
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft,
};
const paddingLeft = parseInt(window.getComputedStyle(block.parentElement, null).getPropertyValue('padding-left'));
const paddingRight = parseInt(window.getComputedStyle(block.parentElement, null).getPropertyValue('padding-right'));
if (window.innerWidth > breakpoint) {
block.style.marginLeft = '';
block.style.marginRight = '';
block.style.width = '';
switch (direction) {
case 'both':
case 'left':
block.style.marginLeft = `-${Math.min(offset.left, max) + paddingLeft}px`;
if (noContent) {
block.style.width = `${Math.min(offset.left, max) + rect.width}px`;
}
if (direction != 'both') break;
case 'both':
case 'right':
const rightOffset = window.innerWidth - (offset.left + block.parentElement.clientWidth);
block.style.marginRight = `-${Math.min(rightOffset, max) + paddingRight}px`;
if (noContent) {
block.style.width = `${Math.min(rightOffset, max) + rect.width}px`;
}
if (direction != 'both') break;
case 'both':
if (noContent) {
block.style.width = `${Math.min(rightOffset, max) * 2 + rect.width}px`;
}
default:
break;
}
} else {
if (block.style.marginLeft) {
block.style.marginLeft = '';
}
if (block.style.marginRight) {
block.style.marginRight = '';
}
if (noContent) {
block.style.width = `${rect.width}px`;
}
}
}
}
|
TheDancingCode/craft | tailoff/js/ie/ieBanner.component.ts | import { A11yUtils } from './a11y';
export class IEBannerComponent {
private mainContentBlock: HTMLElement;
constructor() {
this.mainContentBlock = document.getElementById('mainContentBlock');
window.addEventListener('cookie-closed', () => {
const banner = document.querySelector('.ie-banner') as HTMLElement;
const overlay = document.querySelector('.ie-banner-overlay') as HTMLElement;
banner.classList.remove('hidden');
overlay.classList.remove('hidden');
A11yUtils.keepFocus(banner);
banner.focus();
const closeBtn = document.querySelector('.js-ie-banner-close') as HTMLElement;
closeBtn.addEventListener('click', (e) => {
e.preventDefault();
banner.classList.add('hidden');
overlay.classList.add('hidden');
this.setMainContentInert(false);
});
this.setMainContentInert();
});
}
private setMainContentInert(set = true) {
if (this.mainContentBlock && set) {
this.mainContentBlock.setAttribute('inert', '');
document.documentElement.classList.add('overflow-hidden');
}
if (this.mainContentBlock && !set) {
this.mainContentBlock.removeAttribute('inert');
document.documentElement.classList.remove('overflow-hidden');
}
}
}
|
TheDancingCode/craft | tailoff/js/components/leaflet.component.ts | <reponame>TheDancingCode/craft
import { Ajax } from '../utils/ajax';
export class LeafletComponent {
// private L = window['L'];
constructor() {
const maps = document.querySelectorAll('.leaflet-map');
if (maps.length > 0) {
Array.from(maps).forEach((map: HTMLElement) => {
this.initMap(map);
});
}
}
private async initMap(map: HTMLElement) {
// @ts-ignore
const leaflet = await import('leaflet/dist/leaflet.js');
const lmap = leaflet.map(map, {
// center: [data[0].locations[0].lat, data[0].locations[0].lng],
zoom: 13,
tap: false,
scrollWheelZoom: false,
});
if (map.getAttribute('data-address')) {
Ajax.call({
url: `https://nominatim.openstreetmap.org/search/${map.getAttribute(
'data-address'
)}?format=json&addressdetails=1&limit=1`,
success: (data) => {
leaflet.marker([data[0].lat, data[0].lon]).addTo(lmap);
lmap.setView([data[0].lat, data[0].lon], 14);
},
});
}
if (map.getAttribute('data-points-obj')) {
const data = JSON.parse(map.getAttribute('data-points-obj'));
lmap.fitBounds(data.map((p) => [...p.locations.map((m) => [m.lat, m.lng])]));
data.forEach((marker) => {
const pin = leaflet.marker([marker.lat, marker.lng]).addTo(lmap);
const address = marker.address != '' ? `<div class="">${marker.address}</div>` : '';
const popupContent = `${address}`;
pin.bindPopup(popupContent);
});
}
leaflet
.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>',
})
.addTo(lmap);
}
}
|
TheDancingCode/craft | tailoff/js/components/scrollToAnchor.component.ts | import { DOMHelper } from '../utils/domHelper';
import { ScrollHelper } from '../utils/scroll';
export class ScrollToAnchorComponent {
constructor() {
const scrollLinks = document.querySelectorAll('a.js-smooth-scroll');
Array.from(scrollLinks).forEach((link: HTMLAnchorElement) => {
this.initScrollTo(link);
});
DOMHelper.onDynamicContent(document.documentElement, 'a.js-smooth-scroll', (scrollLinks) => {
Array.from(scrollLinks).forEach((link: HTMLAnchorElement) => {
this.initScrollTo(link);
});
});
}
private initScrollTo(link: HTMLAnchorElement) {
link.classList.remove('js-smooth-scroll');
link.addEventListener('click', (e) => {
const hash = link.getAttribute('href').split('#');
if (hash.length > 1) {
const target = document.querySelector(`#${hash[1]}`) as HTMLElement;
if (target) {
e.preventDefault();
ScrollHelper.scrollToY(target, 400);
}
}
});
}
}
|
TheDancingCode/craft | tailoff/js/components/dropdown.component.ts | <filename>tailoff/js/components/dropdown.component.ts<gh_stars>10-100
import { DOMHelper } from '../utils/domHelper';
export class DropdownComponent {
constructor() {
const dropdowns = Array.from(document.querySelectorAll('.js-dropdown'));
dropdowns.forEach((dropdown, index) => {
new DropdownElement(dropdown as HTMLElement, index);
});
DOMHelper.onDynamicContent(document.documentElement, '.js-dropdown', (dropdowns) => {
Array.from(dropdowns).forEach((dropdown, index) => {
new DropdownElement(dropdown as HTMLElement, index);
});
});
}
}
class DropdownElement {
private clickListener;
private keydownListener;
private scrollListener;
private buttonElement: HTMLElement;
private menuElement: HTMLElement;
private menuItems: Array<HTMLElement>;
private popper;
private open = false;
private TAB_KEYCODE = 9;
private ESC_KEYCODE = 27;
private UP_ARROW_KEYCODE = 38;
private DOWN_ARROW_KEYCODE = 40;
constructor(element: HTMLElement, index) {
element.style.position = 'relative';
element.classList.remove('js-dropdown');
this.buttonElement = element.querySelector('.js-dropdown-toggle');
this.menuElement = element.querySelector('.js-dropdown-menu');
this.menuItems = Array.from(this.menuElement.querySelectorAll('a[href],button:not([disabled])'));
this.menuElement.classList.add('hidden');
this.buttonElement.setAttribute('role', 'button');
this.buttonElement.setAttribute('aria-expanded', 'false');
this.clickListener = this.clickAction.bind(this);
this.keydownListener = this.keydownAction.bind(this);
this.scrollListener = this.scrollAction.bind(this);
this.buttonElement.addEventListener('click', this.clickListener);
}
private toggleMenu() {
if (this.menuElement.classList.contains('hidden')) {
// Open
this.open = true;
this.menuElement.classList.remove('hidden');
this.buttonElement.setAttribute('aria-expanded', 'true');
this.positionMenu();
document.addEventListener('click', this.clickListener);
document.addEventListener('keydown', this.keydownListener);
document.addEventListener('scroll', this.scrollListener);
} else {
// Close
this.open = false;
this.menuElement.classList.add('hidden');
this.buttonElement.setAttribute('aria-expanded', 'false');
document.removeEventListener('click', this.clickListener);
document.removeEventListener('keydown', this.keydownListener);
document.removeEventListener('scroll', this.scrollListener);
}
}
private clickAction(e: Event) {
e.stopPropagation();
this.toggleMenu();
}
private scrollAction(e: Event) {
this.positionMenu();
}
private keydownAction(event) {
if (event.keyCode === this.ESC_KEYCODE) {
event.preventDefault();
this.buttonElement.focus();
this.toggleMenu();
}
if (event.keyCode === this.UP_ARROW_KEYCODE) {
event.preventDefault();
if (this.menuItems[0] !== document.activeElement) {
const activeMenuIndex = this.menuItems.findIndex((i) => i === document.activeElement);
if (activeMenuIndex > 0) {
this.menuItems[activeMenuIndex - 1].focus();
}
}
}
if (event.keyCode === this.DOWN_ARROW_KEYCODE) {
event.preventDefault();
if (this.menuItems[this.menuItems.length - 1] !== document.activeElement) {
const activeMenuIndex = this.menuItems.findIndex((i) => i === document.activeElement);
console.log(activeMenuIndex);
if (activeMenuIndex < this.menuItems.length - 1) {
this.menuItems[activeMenuIndex + 1].focus();
}
}
}
if (event.keyCode === this.TAB_KEYCODE && event.shiftKey && this.buttonElement === document.activeElement) {
this.toggleMenu();
}
if (
event.keyCode === this.TAB_KEYCODE &&
!event.shiftKey &&
this.menuItems[this.menuItems.length - 1] === document.activeElement
) {
this.toggleMenu();
}
}
private positionMenu() {
this.menuElement.style.position = 'absolute';
this.menuElement.style.top = '0px';
this.menuElement.style.left = '0px';
this.menuElement.style.willChange = 'transform';
const buttonRect = this.buttonElement.getBoundingClientRect();
const menuRect = this.menuElement.getBoundingClientRect();
let leftPos = this.buttonElement.offsetLeft;
if (buttonRect.left + menuRect.width > window.screen.width) {
leftPos = this.buttonElement.offsetLeft + buttonRect.width - menuRect.width;
}
if (buttonRect.height + menuRect.height + buttonRect.top > window.screen.height) {
this.menuElement.style.transform = `translate(${leftPos}px, ${-menuRect.height}px)`;
} else {
this.menuElement.style.transform = `translate(${leftPos}px, ${
this.buttonElement.offsetTop + buttonRect.height
}px)`;
}
}
}
|
TheDancingCode/craft | tailoff/js/plugins/modal/plugin.interface.ts | import { ModalComponent } from '../../components/modal.component';
export interface ModalPluginConstructor {
new (modalComponent?: ModalComponent, options?: {}): ModalPlugin;
}
export interface ModalPlugin {
initElement(): void;
afterCreateModal(): void;
getTriggerClass(): string;
openModalClick(trigger: HTMLElement): void;
closeModal(): void;
gotoNextAction(): void;
gotoPrevAction(): void;
}
|
TheDancingCode/craft | tailoff/js/components/table.component.ts | export class TableComponent {
constructor() {
//add data-header to td's in custom table.
Array.from(document.querySelectorAll('.custom-table table')).forEach((table: HTMLTableElement) => {
this.initCustomTable(table);
});
}
private initCustomTable(table: HTMLTableElement) {
Array.from(table.querySelectorAll('td')).forEach((td: HTMLTableDataCellElement) => {
const newDiv = document.createElement('div');
newDiv.innerHTML = td.innerHTML;
td.innerHTML = newDiv.outerHTML;
});
const tableHead = table.querySelector('thead');
if (tableHead) {
const headings = Array.from(tableHead.querySelectorAll('th')).map((th) => th.innerText);
Array.from(table.querySelectorAll('td')).forEach((td, index) => {
td.setAttribute('data-label', headings[index % headings.length]);
});
}
}
}
|
TheDancingCode/craft | tailoff/js/components/loadmore.component.ts | <gh_stars>10-100
import { DOMHelper } from '../utils/domHelper';
export class LoadMoreComponent {
private xhr: XMLHttpRequest;
private infiniteScroll = false;
constructor() {
document.addEventListener(
'click',
(e) => {
// loop parent nodes from the target to the delegation node
for (let target = <Element>e.target; target && !target.isSameNode(document); target = target.parentElement) {
if (target.matches('.js-load-more')) {
e.preventDefault();
this.initAction(target);
break;
}
}
},
false
);
if (this.infiniteScroll || document.querySelector('.js-infinite-scroll')) {
this.initInfiniteScroll();
DOMHelper.onDynamicContent(document.documentElement, '.js-pagination', () => {
this.initInfiniteScroll();
});
}
}
private initInfiniteScroll() {
Array.from(document.querySelectorAll('.js-pagination.js-infinite-scroll')).forEach((el) => {
const observer = new IntersectionObserver(
(entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const loadMoreButton = entry.target.querySelector('.js-load-more');
if (loadMoreButton) {
this.initAction(loadMoreButton);
}
}
});
},
{
rootMargin: '10% 0% 10% 0%',
threshold: [0, 0.5, 1],
}
);
observer.observe(el);
});
}
private initAction(el: Element) {
el.classList.add('hidden');
const wrapper = el.getAttribute('data-load-wrapper');
if (wrapper) {
this.getNextPage(el.getAttribute('href'), wrapper);
document.querySelector(`#${wrapper} .js-pagination-loader`).classList.remove('hidden');
} else {
this.getNextPage(el.getAttribute('href'));
document.querySelector('.js-pagination-loader').classList.remove('hidden');
}
}
private getNextPage(url, wrapper: string = '') {
const _self = this;
if (this.xhr) {
this.xhr.abort();
}
this.xhr = new XMLHttpRequest();
this.xhr.open('GET', url, true);
this.xhr.onload = function () {
if (this.status >= 200 && this.status < 400) {
const responseElement = document.implementation.createHTMLDocument('');
responseElement.body.innerHTML = this.response;
const children = responseElement.querySelector(`#${wrapper} .js-pagination-container`).children;
let container = document.querySelector('.js-pagination-container');
if (wrapper !== '') {
document.querySelector(`#${wrapper} .js-pagination`).innerHTML = responseElement.querySelector(
`#${wrapper} .js-pagination`
).innerHTML;
container = document.querySelector(`#${wrapper} .js-pagination-container`);
} else {
document.querySelector('.js-pagination').innerHTML =
responseElement.querySelector('.js-pagination').innerHTML;
}
const elements = Array.from(children);
Array.from(children).forEach((child) => {
container.appendChild(child);
});
document.querySelector('.js-pagination-container').dispatchEvent(
new CustomEvent('pagination.loaded', {
detail: { elements: elements },
})
);
// history.pushState("", "New URL: " + url, url);
} else {
console.log('Something went wrong when fetching data');
}
};
this.xhr.onerror = function () {
console.log('There was a connection error');
};
this.xhr.send();
}
}
|
TheDancingCode/craft | tailoff/js/components/pageFind.component.ts | //You can borrow code and inspiration from http://www.calilighting.com/assets/js/filter/find5.js
import { Helper } from '../utils/helper';
export class PageFindComponent {
private inputElement: HTMLInputElement;
private resultsElement: HTMLElement;
private nextElement: HTMLElement;
private previousElement: HTMLElement;
private clearElement: HTMLElement;
private currentElement: HTMLElement;
private totalElement: HTMLElement;
private searchText: string = '';
private searchElement: HTMLElement;
private highlights = [];
private currentIndex = 1;
private searchTotal = 0;
private options = {
highlightClasses: ['bg-yellow-500'],
currentHighlightClasses: ['bg-red-500'],
};
constructor() {
const findForm = document.querySelector('form.js-find-form') as HTMLFormElement;
if (findForm) {
this.initFind(findForm);
}
// Uncomment to test the hidden event callback.
Array.from(document.querySelectorAll('p.hidden')).forEach((el) => {
el.addEventListener('show', () => {
el.classList.remove('hidden');
});
});
}
private initFind(form: HTMLFormElement) {
this.inputElement = document.querySelector('.js-find-input');
this.resultsElement = document.querySelector('.js-page-find-results');
this.nextElement = document.querySelector('.js-page-find-next');
this.previousElement = document.querySelector('.js-page-find-prev');
this.clearElement = document.querySelector('.js-page-find-clear');
this.currentElement = this.resultsElement.querySelector('.js-current-find');
this.totalElement = this.resultsElement.querySelector('.js-total-find');
const searchElementId = form.getAttribute('data-s-search-block');
if (searchElementId) {
this.searchElement = document.querySelector(`#${searchElementId}`) as HTMLElement;
if (this.searchElement) {
this.searchText = this.searchElement.textContent;
}
} else {
this.searchElement = document.body;
this.searchText = document.body.textContent;
}
this.resultsElement.classList.add('hidden');
this.inputElement.addEventListener(
'keyup',
Helper.debounce((event) => {
let key = event.keyCode;
if (key === 13) return;
this.onFind(event);
}, 500)
);
this.nextElement.addEventListener('click', this.gotoNext.bind(this));
this.previousElement.addEventListener('click', this.gotoPrev.bind(this));
this.clearElement.addEventListener('click', this.onClear.bind(this));
form.addEventListener('submit', (event) => {
event.preventDefault();
this.gotoNext();
});
}
private onFind(event: Event) {
this.clearHighlights();
const findValue = this.searchText.toLowerCase().includes(this.inputElement.value.toLowerCase());
if (!findValue || this.inputElement.value.trim().length == 0) {
this.resultsElement.classList.add('hidden');
return false;
}
let query = this.inputElement.value;
query = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
this.searchTotal = (this.searchText.match(new RegExp(query, 'gi')) || []).length;
this.resultsElement.classList.remove('hidden');
this.totalElement.innerText = `${this.searchTotal}`;
this.currentElement.innerText = `1`;
this.currentIndex = 1;
this.highlightWord(this.inputElement.value);
this.scrollToQuery(this.highlights[this.currentIndex - 1]);
}
private highlightWord(word: string, node?: any) {
if (!node) node = this.searchElement;
for (let childNode = node.firstChild; childNode; childNode = childNode.nextSibling) {
if (childNode.nodeType == 3) {
// text node
let n = childNode;
let match_pos = 0;
match_pos = n.nodeValue.toLowerCase().indexOf(word.toLowerCase()); // Ver 5.3b - Using toLowerCase().indexOf instead
if (match_pos > -1) {
// if we found a match
let before = n.nodeValue.substr(0, match_pos); // split into a part before the match
let middle = n.nodeValue.substr(match_pos, word.length); // the matched word to preserve case
let after = document.createTextNode(n.nodeValue.substr(match_pos + word.length)); // and the part after the match
let highlightSpan = document.createElement('span'); // create a span in the middle
highlightSpan.classList.add(...this.options.highlightClasses);
highlightSpan.appendChild(document.createTextNode(middle)); // insert word as textNode in new span
n.nodeValue = before; // Turn node data into before
n.parentNode.insertBefore(after, n.nextSibling); // insert after
n.parentNode.insertBefore(highlightSpan, n.nextSibling); // insert new span
this.highlights.push(highlightSpan); // add new span to highlightWords array
highlightSpan.id = 'highlight_span' + this.highlights.length;
childNode = childNode.nextSibling; // Advance to next node or we get stuck in a loop because we created a span (child)
}
} // if not text node then it must be another element
else {
// nodeType 1 = element
if (childNode.nodeType == 1) {
this.highlightWord(word, childNode);
}
}
}
}
private clearHighlights() {
this.highlights.forEach((highlight) => {
highlight.outerHTML = highlight.innerText;
});
this.highlights = [];
}
private onClear() {
this.clearHighlights();
this.inputElement.value = '';
this.resultsElement.classList.add('hidden');
}
private gotoNext() {
this.highlights[this.currentIndex - 1].classList.add(...this.options.highlightClasses);
this.highlights[this.currentIndex - 1].classList.remove(...this.options.currentHighlightClasses);
this.currentIndex++;
if (this.currentIndex > this.searchTotal) {
this.currentIndex = 1;
}
this.currentElement.innerText = `${this.currentIndex}`;
this.scrollToQuery(this.highlights[this.currentIndex - 1]);
}
private gotoPrev() {
this.highlights[this.currentIndex - 1].classList.add(...this.options.highlightClasses);
this.highlights[this.currentIndex - 1].classList.remove(...this.options.currentHighlightClasses);
this.currentIndex--;
if (this.currentIndex < 1) {
this.currentIndex = this.searchTotal;
}
this.currentElement.innerText = `${this.currentIndex}`;
this.scrollToQuery(this.highlights[this.currentIndex - 1]);
}
private scrollToQuery(element: HTMLElement) {
const hiddenElement = this.isElementHidden(element);
if (hiddenElement) {
let event;
if (typeof Event === 'function') {
event = new Event('show');
} else {
event = document.createEvent('Event');
event.initEvent('show', true, true);
}
hiddenElement.dispatchEvent(event);
}
const wrapper = element.closest('.js-open-on-find');
if (wrapper) {
wrapper.dispatchEvent(new Event('open'));
}
element.classList.add(...this.options.currentHighlightClasses);
element.classList.remove(...this.options.highlightClasses);
const top = window.pageYOffset || document.documentElement.scrollTop;
const windowHeight = window.innerHeight;
const elementTopOffset = element.getBoundingClientRect().top;
if (elementTopOffset > windowHeight || elementTopOffset < 0) {
window.scrollTo(0, elementTopOffset + top - windowHeight / 2);
}
}
private isElementHidden(element) {
if (window.getComputedStyle(element).display === 'none') {
return element;
} else {
if (element.parentElement) {
return this.isElementHidden(element.parentElement);
} else {
return false;
}
}
}
}
|
TheDancingCode/craft | tailoff/js/components/webfont.component.ts | export class WebfontComponent {
private urls: Array<string>;
private key = 'fonts';
private cache;
constructor(urls: Array<string> = []) {
this.urls = urls;
this.cache = window.localStorage.getItem(this.key);
if (this.cache) {
this.insertFonts(this.cache);
this.cacheFonts();
} else {
this.cacheFonts(true);
}
}
private cacheFonts(isInsertFonts: boolean = false) {
const _self = this;
window.addEventListener('load', function () {
const promises = [];
for (let i = 0; i < _self.urls.length; i++) {
const request = _self.get(_self.urls[i]).then(
function (response) {
return response;
},
function (error) {
console.error('Failed!', error);
return false;
}
);
promises.push(request);
}
Promise.all(promises).then((arrayOfResults) => {
let fonts = '';
for (let i = 0; i < arrayOfResults.length; i++) {
if (arrayOfResults[i]) {
fonts = fonts + ' ' + arrayOfResults[i];
}
}
if (isInsertFonts) {
_self.insertFonts(fonts);
}
window.localStorage.setItem(_self.key, fonts);
});
});
}
private insertFonts(value) {
const style = document.createElement('style');
style.innerHTML = value;
document.head.appendChild(style);
}
private get(url) {
return new Promise(function (resolve, reject) {
const req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function () {
if (req.status == 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function () {
reject(Error('Network Error'));
};
req.send();
});
}
}
|
TheDancingCode/craft | tailoff/js/components/masonry.component.ts | export class MasonryComponent {
constructor() {
if ('CSS' in window && CSS.supports('display', 'grid')) {
this.initGridMasonry();
} else {
/**
* Remove the code below when we decide not to support sucky browsers like IE11
* And also remove all the related functions
*/
this.initFlexMasonry();
}
}
private initGridMasonry() {
window.addEventListener('load', this.resizeAllMasonryItems.bind(this));
let timeoutDelay = null;
window.addEventListener('resize', () => {
clearTimeout(timeoutDelay);
timeoutDelay = setTimeout(() => {
this.resizeAllMasonryItems();
}, 250);
});
}
private resizeAllMasonryItems() {
const allItems = document.querySelectorAll('.js-masonry-item');
Array.from(allItems).forEach((item) => {
this.resizeMasonryItem(item as HTMLElement);
});
}
private resizeMasonryItem(element: HTMLElement) {
/* Get the grid object, its row-gap, and the size of its implicit rows */
var grid = element.closest('.js-masonry');
if (grid) {
const rowGap = parseInt(window.getComputedStyle(grid).getPropertyValue('grid-row-gap')),
rowHeight = parseInt(window.getComputedStyle(grid).getPropertyValue('grid-auto-rows')),
gridContent = element.querySelector('.js-masonry-content') as HTMLImageElement;
if (gridContent) {
gridContent.style.height = 'auto';
}
const rowSpan = Math.ceil(
(element.querySelector('.js-masonry-content').getBoundingClientRect().height + rowGap) / (rowHeight + rowGap)
);
element.style.gridRowEnd = 'span ' + rowSpan;
if (gridContent) {
gridContent.style.height = element.getBoundingClientRect().height + 'px';
}
}
}
private initFlexMasonry() {
window.addEventListener('load', this.rerenderFlexMasonry.bind(this));
let timeoutDelay = null;
window.addEventListener('resize', () => {
clearTimeout(timeoutDelay);
timeoutDelay = setTimeout(() => {
this.rerenderFlexMasonry();
}, 250);
});
}
private rerenderFlexMasonry() {
Array.from(document.querySelectorAll('.js-masonry')).forEach((masonry: HTMLElement) => {
masonry.style.height = null;
const items = Array.from(masonry.querySelectorAll('.js-masonry-item'));
items.forEach((item: HTMLElement) => {
item.style.height = null;
item.style.flexBasis = null;
});
const NrOfColumns = Math.round(masonry.offsetWidth / items[0].clientWidth);
const columns = Array.from(new Array(NrOfColumns)).map(() => {
return {
items: new Array(),
outerHeight: 0,
};
});
items.forEach((item: HTMLElement) => {
const style = getComputedStyle(item);
item.style.height = `${
parseInt(style.paddingTop) +
(item.querySelector('.js-masonry-content') as HTMLElement).offsetHeight +
parseInt(style.paddingBottom)
}px`;
const minOuterHeight = Math.min(...columns.map((c) => c.outerHeight));
const column = columns.find((c) => c.outerHeight == minOuterHeight);
column.items.push(item);
column.outerHeight += parseInt(item.style.height) + parseInt(style.paddingTop) + parseInt(style.paddingBottom);
});
const masonryHeight = Math.max(...columns.map((c) => c.outerHeight));
let order = 0;
columns.forEach((col) => {
col.items.forEach((item: HTMLElement) => {
item.style.order = `${order++}`;
});
// set flex-basis of the last cell to fill the
// leftover space at the bottom of the column
// to prevent the first cell of the next column
// to be rendered at the bottom of this column
col.items[col.items.length - 1].style.flexBasis =
col.items[col.items.length - 1].offsetHeight + masonryHeight - col.outerHeight - 1 + 'px';
});
masonry.style.height = masonryHeight + 1 + 'px';
});
}
}
|
TheDancingCode/craft | tailoff/js/components/general.component.ts | <gh_stars>10-100
export class GeneralComponent {
constructor() {
this.addOutlineForTabbers();
}
// This adds a class if the user is tabbing and thus using the keyboard, so the focus style will be visible. Otherwise if it's a clicker the focus is removed.
private addOutlineForTabbers() {
function handleFirstTab(e) {
if (e.keyCode === 9) {
// the "I am a keyboard user" key
document.body.classList.add('user-is-tabbing');
window.removeEventListener('keydown', handleFirstTab);
}
}
window.addEventListener('keydown', handleFirstTab);
}
}
|
TheDancingCode/craft | tailoff/js/components/formie.component.ts | <filename>tailoff/js/components/formie.component.ts<gh_stars>10-100
import { SiteLang } from '../utils/site-lang';
import { ArrayPrototypes } from '../utils/prototypes/array.prototypes';
ArrayPrototypes.activateFrom();
declare global {
interface Window {
FormieTranslations: any;
}
}
export class FormieComponent {
public lang = require(`../i18n/formie-${SiteLang.getLang()}.json`);
constructor() {
window.FormieTranslations = this.lang;
Array.from(document.querySelectorAll('select.fui-select')).forEach((element) => {
const container = element.closest('.fui-input-container');
container.classList.add('fui-select-container');
});
}
}
|
TheDancingCode/craft | tailoff/js/components/glide.component.ts | <reponame>TheDancingCode/craft
import { DOMHelper } from '../utils/domHelper';
import { Info } from '../utils/info';
export class GlideComponent {
constructor() {
const sliders = Array.from(document.querySelectorAll('.js-slider'));
if (sliders.length > 0) {
this.processSliders(sliders);
}
DOMHelper.onDynamicContent(document.documentElement, '.js-slider', (sliders) => {
this.processSliders(Array.from(sliders));
});
}
private async processSliders(sliders: Array<Element>) {
// @ts-ignore
const Glide = await import('@glidejs/glide');
sliders.forEach((slider) => {
slider.classList.remove('js-slider');
const sliderID = slider.getAttribute('id');
if (sliderID.indexOf('carousel') >= 0) {
const glide = new Glide.default('#' + sliderID, {
type: 'carousel',
perView: 1,
});
glide.mount();
}
if (sliderID.indexOf('slider') >= 0) {
const idealWidth = parseInt(slider.getAttribute('data-ideal-width')) || 200;
const glide = new Glide.default('#' + sliderID, {
type: 'slider',
perView: 1,
animationDuration: 800,
gap: 20,
peek: 100,
perTouch: 1,
perSwipe: 1,
});
glide.on(['mount.after', 'resize'], function (e) {
const slider = document.getElementById(sliderID);
const slides = slider.querySelectorAll('.glide__slide');
if (window.innerWidth < 480) {
glide.update({ peek: 40 });
} else {
glide.update({ peek: 100 });
}
const availableWidth = slider.offsetWidth - 2 * glide.settings.peek;
let possiblePerView = Math.floor(availableWidth / idealWidth);
if (possiblePerView <= 0) {
possiblePerView = 1;
}
glide.update({ perView: possiblePerView });
const controles = slider.querySelector("div[data-glide-el='controls']");
if ((controles && Info.isTouchDevice() && Info.isMobile()) || possiblePerView >= slides.length) {
controles.classList.add('hidden');
} else {
controles.classList.remove('hidden');
}
if (possiblePerView >= slides.length) {
if (glide.index > 0) {
glide.go('<<');
}
glide.disable();
} else {
glide.enable();
}
});
glide.on(['run.before', 'resize'], (event) => {
const slider = document.getElementById(sliderID);
const slides = slider.querySelectorAll('.glide__slide');
let amount = glide.settings.perView;
if (slides.length - (glide.index + glide.settings.perView) < amount) {
amount = slides.length - glide.settings.perView;
}
event.steps = event.direction === '>' ? -amount : amount;
Array.from(slides).forEach((slide) => {
slide.classList.remove('opacity-50');
slide.classList.remove('opacity-25');
slide.classList.remove('opacity-0');
slide.classList.remove('pointer-events-none');
});
});
glide.on(['mount.after', 'run.after', 'resize'], (event) => {
const slider = document.getElementById(sliderID);
const slides = slider.querySelectorAll('.glide__slide');
let start = glide.index;
let end = start + glide.settings.perView;
Array.from(slides).forEach((slide, i) => {
if (i < start || i >= end) {
if (i + 1 == start || i == end) {
slide.classList.add('opacity-50');
} else if (i + 2 == start || i - 1 == end) {
slide.classList.add('opacity-25');
} else {
slide.classList.add('opacity-0');
}
slide.classList.add('pointer-events-none');
}
});
const prevController = slider.querySelector("div[data-glide-el='controls'] .glide__arrow--left");
const nextController = slider.querySelector("div[data-glide-el='controls'] .glide__arrow--right");
if (glide.index == 0) {
prevController.classList.add('opacity-25');
prevController.classList.add('pointer-events-none');
prevController.classList.remove('pointer-events-auto');
} else {
prevController.classList.remove('opacity-25');
prevController.classList.remove('pointer-events-none');
prevController.classList.add('pointer-events-auto');
}
if (glide.index + glide.settings.perView >= slides.length) {
nextController.classList.add('opacity-25');
nextController.classList.add('pointer-events-none');
nextController.classList.remove('pointer-events-auto');
} else {
nextController.classList.remove('opacity-25');
nextController.classList.remove('pointer-events-none');
nextController.classList.add('pointer-events-auto');
}
});
glide.mount();
}
});
}
}
|
TheDancingCode/craft | tailoff/js/components/ajaxSearch.component.ts | <reponame>TheDancingCode/craft
// based on: https://adamsilver.io/articles/building-an-accessible-autocomplete-control/
// import Promise from "promise-polyfill";
import { Ajax } from '../utils/ajax';
import { DOMHelper } from '../utils/domHelper';
import { SiteLang } from '../utils/site-lang';
import { Formatter } from '../utils/formater';
export class AjaxSearchComponent {
constructor() {
Array.from(document.querySelectorAll('[data-s-ajax-search], [data-s-ajax-search-callback]')).forEach(
(search, index) => {
if (search.tagName === 'INPUT') {
new AjaxSearch(search as HTMLInputElement, index);
}
}
);
DOMHelper.onDynamicContent(
document.documentElement,
'select[data-s-ajax-search], select[data-s-ajax-search-callback]',
(search) => {
Array.from(search).forEach((s: HTMLInputElement, index) => {
new AjaxSearch(s, index);
});
}
);
}
}
class AjaxSearch {
private lang = require(`../i18n/s-ajax-search-${SiteLang.getLang()}.json`);
private ajaxSearchElement: HTMLDivElement;
private inputElement: HTMLInputElement;
private formElement: HTMLFormElement;
private ajaxURL: string;
private options: Array<HTMLElement> = [];
private searchCallback = '';
private ajaxMethod = 'GET';
private ajaxQueryName = 'data';
private dataArray = '';
private resultTemplate = '';
private noresultTemplate = '';
private typedTextTemplate = '';
private noresultText = this.lang.nothingFound;
private noTypedOption = false;
private autocompleteInputWrapper: HTMLDivElement;
private ajaxSearchListElement: HTMLUListElement;
private statusElement: HTMLDivElement;
private inputKeyUpListener;
private inputFocusListener;
private inputKeyDownListener;
private documentClickListener;
private hoverOption: HTMLElement;
private isDisabled = false;
private keys = {
esc: 27,
up: 38,
left: 37,
right: 39,
space: 32,
enter: 13,
tab: 9,
shift: 16,
down: 40,
backspace: 8,
};
constructor(input: HTMLInputElement, index) {
this.inputElement = input;
this.ajaxURL = this.inputElement.getAttribute('data-s-ajax-search');
this.searchCallback = this.inputElement.getAttribute('data-s-ajax-search-callback');
this.formElement = this.inputElement.closest('form');
if (this.ajaxURL || this.searchCallback) {
if (this.ajaxURL) {
this.ajaxMethod =
this.inputElement.getAttribute('data-s-ajax-search-methode') != null
? this.inputElement.getAttribute('data-s-ajax-search-methode')
: this.ajaxMethod;
this.ajaxQueryName =
this.inputElement.getAttribute('data-s-ajax-search-query') != null
? this.inputElement.getAttribute('data-s-ajax-search-query')
: this.ajaxQueryName;
}
this.noresultText =
this.inputElement.getAttribute('data-s-ajax-search-no-result-text') != null
? this.inputElement.getAttribute('data-s-ajax-search-no-result-text')
: this.noresultText;
if (this.inputElement.getAttribute('data-s-ajax-search-result-template') != null) {
const template = document.getElementById(this.inputElement.getAttribute('data-s-ajax-search-result-template'));
this.resultTemplate = template != null ? template.innerHTML : '';
}
if (this.inputElement.getAttribute('data-s-ajax-search-typed-text-template') != null) {
const template = document.getElementById(
this.inputElement.getAttribute('data-s-ajax-search-typed-text-template')
);
this.typedTextTemplate = template != null ? template.innerHTML : '';
}
if (this.inputElement.getAttribute('data-s-ajax-search-no-result-template') != null) {
const template = document.getElementById(
this.inputElement.getAttribute('data-s-ajax-search-no-result-template')
);
this.noresultTemplate = template != null ? template.innerHTML : '';
}
if (this.inputElement.getAttribute('data-s-ajax-search-no-typed-option') != null) {
this.noTypedOption = this.inputElement.getAttribute('data-s-ajax-search-no-typed-option') ? true : false;
}
this.dataArray = this.inputElement.getAttribute('data-s-ajax-search-data');
this.inputElement.removeAttribute('data-s-ajax-search');
this.inputElement.setAttribute('aria-controls', `ajaxSearchList${index}`);
this.inputElement.setAttribute('autocapitalize', 'none');
this.inputElement.setAttribute('autocomplete', 'off');
this.inputElement.setAttribute('aria-autocomplete', 'list');
this.inputElement.setAttribute('aria-expanded', 'false');
this.isDisabled = this.inputElement.getAttribute('disabled') != null ? true : false;
this.ajaxSearchElement = document.createElement('div');
this.ajaxSearchElement.classList.add('ajax-search');
if (this.isDisabled) {
this.ajaxSearchElement.classList.add('disabled');
}
this.inputElement.insertAdjacentElement('afterend', this.ajaxSearchElement);
this.autocompleteInputWrapper = document.createElement('div');
this.autocompleteInputWrapper.classList.add('ajax-search__input-wrapper');
this.autocompleteInputWrapper.insertAdjacentElement('beforeend', this.inputElement);
this.ajaxSearchElement.insertAdjacentElement('afterbegin', this.autocompleteInputWrapper);
this.inputKeyUpListener = this.onKeyUp.bind(this);
this.inputElement.addEventListener('keyup', this.inputKeyUpListener);
this.inputKeyDownListener = this.onKeyDown.bind(this);
this.inputElement.addEventListener('keydown', this.inputKeyDownListener);
this.inputFocusListener = this.onFocus.bind(this);
this.inputElement.addEventListener('focus', this.inputFocusListener);
this.ajaxSearchListElement = document.createElement('ul');
this.ajaxSearchListElement.setAttribute('id', `ajaxSearchList${index}`);
this.ajaxSearchListElement.setAttribute('role', 'listbox');
this.ajaxSearchListElement.classList.add('ajax-search__list');
this.ajaxSearchListElement.classList.add('hidden');
this.ajaxSearchElement.insertAdjacentElement('beforeend', this.ajaxSearchListElement);
this.statusElement = document.createElement('div');
this.statusElement.setAttribute('aria-live', 'polite');
this.statusElement.setAttribute('role', 'status');
this.statusElement.classList.add('sr-only');
this.ajaxSearchElement.insertAdjacentElement('beforeend', this.statusElement);
this.documentClickListener = this.onDocumentClick.bind(this);
document.addEventListener('click', this.documentClickListener);
} else {
console.error(
'No URL defined to make the ajax call for the search. Make sure you give the attribute data-s-ajax-search a value!'
);
}
}
private onKeyUp(e) {
switch (e.keyCode) {
case this.keys.left:
case this.keys.right:
case this.keys.space:
case this.keys.shift:
break;
case this.keys.esc:
this.hideMenu();
break;
case this.keys.enter:
e.preventDefault();
if (this.hoverOption) {
const link = this.hoverOption.querySelector('a');
if (link) {
link.click();
}
}
break;
case this.keys.up:
e.preventDefault();
// If the first option is focused, set focus to the text box. Otherwise set focus to the previous option.
if (this.hoverOption) {
let previousSib = this.hoverOption.previousElementSibling;
if (this.hoverOption && previousSib) {
this.highlightOption(previousSib as HTMLElement);
} else {
this.highlightOption(this.ajaxSearchListElement.lastChild as HTMLElement);
}
}
break;
case this.keys.down:
e.preventDefault();
if (this.ajaxSearchListElement.classList.contains('hidden') && this.options.length > 0) {
this.onTextBoxDownPressed(e);
} else {
// Focus the next menu option. If it’s the last menu option, do nothing.
if (this.hoverOption) {
let nextSib = this.hoverOption.nextElementSibling;
if (this.hoverOption && nextSib) {
this.highlightOption(nextSib as HTMLElement);
} else {
this.highlightOption(this.ajaxSearchListElement.firstChild as HTMLElement);
}
} else {
this.highlightOption(this.ajaxSearchListElement.firstChild as HTMLElement);
}
}
break;
default:
this.onTextBoxType(e);
}
}
private onKeyDown(e) {
switch (e.keyCode) {
case this.keys.tab:
// Hide the menu.
this.hideMenu();
break;
}
}
private onFocus(e) {
if (this.inputElement.value.trim().length > 0) {
if (this.searchCallback) {
window[this.searchCallback](this.inputElement.value.trim().toLowerCase()).then((data) => {
this.showData(data);
});
} else {
this.getData(this.inputElement.value.trim().toLowerCase());
}
}
}
private onDocumentClick(e) {
if (!this.ajaxSearchElement.contains(e.target)) {
this.hideMenu();
}
}
private onTextBoxType(e) {
// only show options if user typed something
if (this.inputElement.value.trim().length > 0) {
if (this.searchCallback) {
if (window[this.searchCallback]) {
window[this.searchCallback](this.inputElement.value.trim().toLowerCase()).then((data) => {
this.showData(data);
});
}
} else {
this.getData(this.inputElement.value.trim().toLowerCase());
}
} else {
this.hideMenu();
}
}
private onTextBoxDownPressed(e) {
this.showMenu();
if (this.options.length > 0) {
this.highlightOption(this.options[0] as HTMLElement);
}
}
private showMenu() {
this.ajaxSearchListElement.classList.remove('hidden');
this.inputElement.setAttribute('aria-expanded', 'true');
}
private hideMenu() {
this.ajaxSearchListElement.classList.add('hidden');
this.inputElement.setAttribute('aria-expanded', 'false');
this.inputElement.removeAttribute('aria-activedescendant');
}
private getData(query: string, callback: Function = null) {
let xhr = null;
let data = null;
let url = this.ajaxURL;
if (this.ajaxMethod == 'GET') {
if (this.ajaxQueryName === '') {
url += query;
} else {
if (url.indexOf('?') < 0) {
url += `?${this.ajaxQueryName}=${query}`;
} else {
url += `&${this.ajaxQueryName}=${query}`;
}
}
}
if (this.ajaxMethod == 'POST') {
data = {};
data[this.ajaxQueryName] = query;
}
xhr = Ajax.call({
url: url,
data: data,
method: this.ajaxMethod,
xhr: xhr,
success: (data) => {
if (!Array.isArray(data)) {
data = [data];
}
this.showData(data);
},
error: (e) => {
console.error(e);
},
});
}
private showData(data) {
this.ajaxSearchListElement.innerHTML = '';
if (this.dataArray) {
this.dataArray.split('.').forEach((param) => {
if (data) {
data = data[param];
}
});
}
data.forEach((info) => {
const li = document.createElement('li');
li.setAttribute('role', 'option');
if (this.resultTemplate == '') {
li.innerText = info;
} else {
li.innerHTML = Formatter.parseTemplate(this.resultTemplate, info);
}
const link = li.querySelector('a');
if (link) {
link.setAttribute('tabindex', '-1');
}
this.ajaxSearchListElement.insertAdjacentElement('beforeend', li);
});
this.updateStatus(data.length);
if (data.length == 0) {
const li = document.createElement('li');
li.setAttribute('role', 'option');
if (this.noresultTemplate == '') {
li.innerText = this.noresultText;
} else {
li.innerHTML = this.noresultTemplate;
}
this.ajaxSearchListElement.insertAdjacentElement('beforeend', li);
}
if (!this.noTypedOption) {
const li = document.createElement('li');
li.setAttribute('role', 'option');
let template = this.typedTextTemplate;
if (template) {
const matches = this.typedTextTemplate.match(/%%(.*)%%/gi);
if (matches) {
matches.forEach((match) => {
template = template.replace(match, this.inputElement.value.trim());
});
}
} else {
template = `${this.lang.showResultsForQuery} ${this.inputElement.value.trim()}`;
}
const link = document.createElement('a');
link.href =
this.formElement.action + '?' + this.inputElement.name + '=' + this.inputElement.value.trim().toLowerCase();
link.insertAdjacentHTML('afterbegin', template);
li.insertAdjacentElement('afterbegin', link);
this.ajaxSearchListElement.insertAdjacentElement('beforeend', li);
}
this.showMenu();
}
private updateStatus(nbr: number) {
if (this.statusElement) {
this.statusElement.innerText = `${nbr} ${this.lang.resultsAvailable}`;
}
}
private highlightOption(option: HTMLElement) {
if (this.hoverOption) {
this.hoverOption.classList.remove('highlight');
}
if (option) {
option.classList.add('highlight');
this.ajaxSearchListElement.scrollTop = option.offsetTop;
this.inputElement.setAttribute('aria-activedescendant', option.id);
}
this.hoverOption = option;
}
}
|
TheDancingCode/craft | tailoff/js/components/videoBackground.component.ts | <reponame>TheDancingCode/craft
declare global {
interface Window {
onYouTubeIframeAPIReady: any;
YT: any;
}
}
export class VideoBackgroundComponent {
constructor() {
const videos = document.querySelectorAll('.js-video-bg');
Array.from(videos).forEach((video) => {
this.initVideo(video as HTMLElement);
});
const videoRatios = document.querySelectorAll('.js-video-container');
Array.from(videoRatios).forEach((video) => {
this.initVideoRatio(video as HTMLElement);
});
}
private initVideo(video: HTMLElement) {
//Idea from: https://unicorntears.dev/posts/how-to-implement-a-seamless-responsive-video-background-using-youtube-and-wordpress/
const parent = video.parentElement;
const videoId = video.getAttribute('data-youtube-id');
const youtubeApi = document.getElementById('youtubeAPI');
if (!youtubeApi) {
const tag = document.createElement('script');
tag.id = 'youtubeAPI';
tag.src = 'https://www.youtube.com/iframe_api';
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
window.onYouTubeIframeAPIReady = () => {
const player = new window.YT.Player(video, {
videoId: videoId,
playerVars: {
autoplay: 1,
rel: 0,
showinfo: 0,
modestbranding: 1,
playsinline: 1,
controls: 0,
color: 'white',
loop: 1,
mute: 1,
playlist: videoId,
},
events: {
onReady: () => {
player.playVideo();
player.mute();
},
onError: (e) => {
parent.closest('.js-video-container').classList.add('hidden');
},
},
});
};
}
private initVideoRatio(video: HTMLElement) {
const wrapper = video.querySelector('.js-video-wrapper') as HTMLElement;
if (wrapper) {
this.onResize(video, wrapper);
window.addEventListener('resize', () => {
this.onResize(video, wrapper);
});
}
}
private onResize(video: HTMLElement, wrapper: HTMLElement) {
if (video.clientWidth / 16 < video.clientHeight / 9) {
wrapper.style.width = `${Math.ceil((((video.clientHeight / 9) * 16) / video.clientWidth) * 100)}%`;
wrapper.style.paddingBottom = `${Math.ceil((video.clientHeight / video.clientWidth) * 100)}%`;
} else {
wrapper.style.width = '';
wrapper.style.paddingBottom = '';
}
}
}
|
TheDancingCode/craft | tailoff/js/components/datepicker.component.ts | <gh_stars>0
// import flatpickr from 'flatpickr';
import { DOMHelper } from '../utils/domHelper';
import { SiteLang } from '../utils/site-lang';
const lang = SiteLang.getLang();
export class DatePickerComponent {
constructor() {
const pickers = document.querySelectorAll('.js-date-picker');
if (pickers.length > 0) {
this.initDatePickers(pickers);
}
DOMHelper.onDynamicContent(document.documentElement, '.js-date-picker', (pickers) => {
this.initDatePickers(pickers);
});
}
private async initDatePickers(pickers) {
// @ts-ignore
const flatpickr = await import('flatpickr');
switch (lang) {
case 'nl':
const Dutch = require('flatpickr/dist/l10n/nl.js').default.nl;
flatpickr.default.localize(Dutch);
break;
case 'fr':
const French = require('flatpickr/dist/l10n/fr.js').default.fr;
flatpickr.default.localize(French);
break;
}
Array.from(pickers).forEach((picker: HTMLElement) => {
picker.classList.remove('js-time-picker');
flatpickr.default(picker, {
dateFormat: 'd/m/Y',
onChange: function (selectedDates, dateStr, instance) {
instance.input.dispatchEvent(new Event('check-validation'));
instance.altInput.dispatchEvent(new Event('check-validation'));
},
});
});
}
}
|
TheDancingCode/craft | tailoff/js/ie.ts | <filename>tailoff/js/ie.ts
import '../css/ie.css';
import { IEBannerComponent } from './ie/ieBanner.component';
new IEBannerComponent();
|
TheDancingCode/craft | tailoff/js/components/modal.component.ts | import { SiteLang } from '../utils/site-lang';
import { A11yUtils } from '../utils/a11y';
import 'wicg-inert';
import { ModalPlugin, ModalPluginConstructor } from '../plugins/modal/plugin.interface';
export class ModalComponent {
private lang = require(`../i18n/s-modal-${SiteLang.getLang()}.json`);
private options = {
closeHTML: `<span class="close-icon"></span>`,
nextHTML: `<span class="next-icon"></span>`,
prevHTML: `<span class="prev-icon"></span>`,
initTriggers: true,
allowClose: true,
onClose: null,
plugins: [],
};
private bodyElement: HTMLBodyElement;
private modalOverlay: HTMLDivElement;
private modal: HTMLDivElement;
private modalClose: HTMLButtonElement;
public modalContent: HTMLDivElement;
private closeListener;
public trigger: HTMLElement;
public modalLoader: HTMLDivElement;
public galleryGroup: Array<string>;
private nextButton: HTMLButtonElement;
private prevButton: HTMLButtonElement;
public currentGroupIndex: number = 0;
private navListener;
private inlineContentWrapper: HTMLElement;
private mainContentBlock: HTMLElement;
public firstTabbableElement: Element;
public lastTabbableElement: Element;
private plugins: Array<ModalPlugin> = new Array<ModalPlugin>();
private startTouchX = 0;
private startTouchY = 0;
constructor(options: Object = {}) {
this.options = { ...this.options, ...options };
this.mainContentBlock = document.getElementById('mainContentBlock');
this.bodyElement = document.getElementsByTagName('BODY')[0] as HTMLBodyElement;
if (this.options.initTriggers) {
const triggers = document.querySelectorAll('.js-modal');
Array.from(triggers).forEach((trigger) => {
this.initTrigger(trigger);
});
this.options.plugins.forEach(
(plugin: ModalPluginConstructor | { plugin: ModalPluginConstructor; options: {} }) => {
const p = typeof plugin == 'function' ? new plugin(this) : new plugin.plugin(this);
p.initElement();
this.plugins.push(p);
}
);
this.initTriggerClick();
}
}
private initTrigger(trigger: Element) {
trigger.setAttribute('role', 'button');
}
private initTriggerClick() {
document.addEventListener(
'click',
(e) => {
// loop parent nodes from the target to the delegation node
for (let target = <Element>e.target; target && !target.isSameNode(document); target = target.parentElement) {
if (target.matches('.js-modal')) {
e.preventDefault();
this.openModalClick(target as HTMLElement);
break;
}
this.plugins.forEach((p) => {
if (target.matches(`.${p.getTriggerClass()}`)) {
e.preventDefault();
p.openModalClick(target as HTMLElement);
}
});
}
},
false
);
}
private openModalClick(trigger: HTMLElement) {
this.trigger = trigger;
if (trigger.classList.contains('js-modal')) {
if (trigger.tagName === 'A') {
this.openInlineModal((trigger as HTMLAnchorElement).getAttribute('href'));
} else {
const id = trigger.getAttribute('data-modal-id');
id ? this.openInlineModal(id) : console.log('No modal id is provided on the trigger');
}
}
document.body.classList.add('has-open-modal');
}
public getTriggerSrc(trigger: Element) {
if (trigger.tagName === 'A') {
return (trigger as HTMLAnchorElement).getAttribute('href');
} else {
const src = trigger.getAttribute('data-modal-src');
return src ? src : null;
}
}
public openInlineModal(id: string) {
this.createOverlay();
this.createModal();
this.inlineContentWrapper = document.querySelector(id);
if (this.inlineContentWrapper) {
// this.modalContent.insertAdjacentHTML("afterbegin", content.innerHTML);
Array.from(this.inlineContentWrapper.children).forEach((element) => {
this.modalContent.insertAdjacentElement('beforeend', element);
});
this.linkAccesebilityToDialog();
} else {
this.modalContent.insertAdjacentHTML('afterbegin', `<h1>Error</h1><p>${this.lang.contentError}</p>`);
}
this.trapTab();
}
public createOverlay() {
this.modalOverlay = document.createElement('div');
this.modalOverlay.classList.add('modal__overlay');
if (this.options.allowClose) {
this.modalOverlay.addEventListener('click', () => {
this.closeModal();
});
}
this.bodyElement.insertAdjacentElement('beforeend', this.modalOverlay);
}
public createModal(dialogClass = '', modalContentClass = 'modal__content') {
this.modal = document.createElement('div');
this.modal.classList.add('modal__dialog');
dialogClass != '' && this.modal.classList.add(dialogClass);
this.modal.setAttribute('role', 'dialog');
// this.modal.setAttribute("aria-selected", "true");
this.modal.setAttribute('aria-label', this.lang.dialogLabel);
if (this.options.allowClose) {
this.modalClose = document.createElement('button');
this.modalClose.classList.add('modal__close');
this.modalClose.setAttribute('type', 'button');
// this.modalClose.setAttribute("aria-label", this.lang.closeLabel);
this.modalClose.insertAdjacentHTML('beforeend', `<span class="sr-only">${this.lang.closeLabel}</span>`);
this.modalClose.insertAdjacentHTML('beforeend', this.options.closeHTML);
this.modalClose.addEventListener('click', () => {
this.closeModal();
});
this.modal.insertAdjacentElement('afterbegin', this.modalClose);
}
this.modalContent = document.createElement('div');
this.modalContent.classList.add(modalContentClass);
this.modalContent.setAttribute('tabindex', '-1');
this.modal.insertAdjacentElement('beforeend', this.modalContent);
if (this.options.allowClose) {
this.closeListener = this.escKeyAction.bind(this);
document.addEventListener('keydown', this.closeListener);
}
this.plugins.forEach((p) => {
if (this.trigger.matches(`.${p.getTriggerClass()}`)) {
p.afterCreateModal();
}
});
this.bodyElement.insertAdjacentElement('beforeend', this.modal);
this.setMainContentInert();
}
private linkAccesebilityToDialog() {
let label = this.modalContent.querySelector('.js-modal-label');
label = label ? label : this.modalContent.querySelector('h1,h2,h3,h4,h5,h6');
if (label) {
label.setAttribute('id', 'js-modal-label');
this.modal.setAttribute('aria-labelledby', 'js-modal-label');
}
}
public addNavigation() {
this.nextButton = document.createElement('button');
this.nextButton.classList.add('modal__navigation');
this.nextButton.classList.add('modal__next-button');
this.nextButton.setAttribute('type', 'button');
this.nextButton.setAttribute('aria-label', this.lang.nextLabel);
this.nextButton.insertAdjacentHTML('beforeend', `<span class="sr-only">${this.lang.nextText}</span>`);
this.nextButton.insertAdjacentHTML('beforeend', this.options.nextHTML);
this.nextButton.addEventListener('click', this.gotoNextItem.bind(this));
if (this.currentGroupIndex === this.galleryGroup.length - 1) {
this.nextButton.classList.add('hidden');
this.nextButton.setAttribute('disabled', '');
}
this.modalContent.insertAdjacentElement('beforeend', this.nextButton);
this.prevButton = document.createElement('button');
this.prevButton.classList.add('modal__navigation');
this.prevButton.classList.add('modal__prev-button');
this.prevButton.setAttribute('type', 'button');
this.prevButton.setAttribute('aria-label', this.lang.prevLabel);
this.prevButton.insertAdjacentHTML('beforeend', `<span class="sr-only">${this.lang.prevText}</span>`);
this.prevButton.insertAdjacentHTML('beforeend', this.options.prevHTML);
this.prevButton.addEventListener('click', this.gotoPrevItem.bind(this));
if (this.currentGroupIndex === 0) {
this.prevButton.classList.add('hidden');
this.prevButton.setAttribute('disabled', '');
}
this.modalContent.insertAdjacentElement('beforeend', this.prevButton);
this.navListener = this.keyBoardNavigation.bind(this);
document.addEventListener('keydown', this.navListener);
this.modalContent.addEventListener('touchstart', (e) => {
this.startTouchX = e.changedTouches[0].pageX;
this.startTouchY = e.changedTouches[0].pageY;
});
this.modalContent.addEventListener('touchend', (e) => {
const swipeThreshold = 10;
let moved;
if (this.startTouchX - e.changedTouches[0].pageX > swipeThreshold) {
this.gotoNextItem();
moved = true;
}
if (this.startTouchX - e.changedTouches[0].pageX < swipeThreshold) {
this.gotoPrevItem();
moved = true;
}
if (this.startTouchY - e.changedTouches[0].pageY > swipeThreshold && !moved) {
this.gotoNextItem();
}
if (this.startTouchY - e.changedTouches[0].pageY < swipeThreshold && !moved) {
this.gotoPrevItem();
}
});
}
public gotoNextItem() {
this.prevButton.classList.remove('hidden');
this.prevButton.removeAttribute('disabled');
if (this.currentGroupIndex < this.galleryGroup.length - 1) {
this.currentGroupIndex++;
this.plugins.forEach((p) => {
if (this.trigger.matches(`.${p.getTriggerClass()}`)) {
p.gotoNextAction();
}
});
}
if (this.currentGroupIndex === this.galleryGroup.length - 1) {
this.nextButton.classList.add('hidden');
this.nextButton.setAttribute('disabled', '');
this.prevButton.focus();
}
this.updateGalleryTabIndexes();
}
public gotoPrevItem() {
this.nextButton.classList.remove('hidden');
this.nextButton.removeAttribute('disabled');
if (this.currentGroupIndex > 0) {
this.currentGroupIndex--;
this.plugins.forEach((p) => {
if (this.trigger.matches(`.${p.getTriggerClass()}`)) {
p.gotoPrevAction();
}
});
}
if (this.currentGroupIndex === 0) {
this.prevButton.classList.add('hidden');
this.prevButton.setAttribute('disabled', '');
this.nextButton.focus();
}
this.updateGalleryTabIndexes();
}
private keyBoardNavigation(event) {
if (
event.keyCode === 39 ||
event.key === 'ArrowRight' ||
(event.code === 'ArrowRight' && this.currentGroupIndex < this.galleryGroup.length - 1)
) {
this.gotoNextItem();
}
if (
event.keyCode === 37 ||
event.key === 'ArrowLeft' ||
(event.code === 'ArrowLeft' && this.currentGroupIndex > 0)
) {
this.gotoPrevItem();
}
}
private trapTab() {
A11yUtils.keepFocus(this.modal);
this.modalContent.focus();
}
private escKeyAction(event) {
if (event.keyCode === 27 || event.key === 'Escape' || event.code === 'Escape') {
this.closeModal();
}
}
public updateGalleryTabIndexes() {
const tabbableElements = `a[href], area[href], input:not([disabled]),
select:not([disabled]), textarea:not([disabled]),
button:not([disabled]), iframe, object, embed, *[tabindex],
*[contenteditable]`;
const allTabbableElements = this.modal.querySelectorAll(tabbableElements);
this.firstTabbableElement = allTabbableElements[0];
this.lastTabbableElement = allTabbableElements[allTabbableElements.length - 1];
}
public closeModal() {
document.body.classList.remove('has-open-modal');
if (this.inlineContentWrapper) {
Array.from(this.modalContent.children).forEach((element) => {
this.inlineContentWrapper.insertAdjacentElement('beforeend', element);
});
}
this.bodyElement.removeChild(this.modalOverlay);
this.bodyElement.removeChild(this.modal);
document.removeEventListener('keydown', this.closeListener);
document.removeEventListener('keydown', this.navListener);
this.plugins.forEach((p) => {
if (this.trigger.matches(`.${p.getTriggerClass()}`)) {
p.closeModal();
}
});
this.setMainContentInert(false);
if (this.trigger) {
setTimeout(() => {
//To make sure this is the last focus. Otherwise the inert plugin fucks it up.
this.trigger.focus();
}, 0);
}
if (this.options.onClose && typeof this.options.onClose == 'function') {
this.options.onClose();
}
}
private setMainContentInert(set = true) {
if (this.mainContentBlock && set) {
this.mainContentBlock.setAttribute('inert', '');
document.documentElement.classList.add('overflow-hidden');
}
if (this.mainContentBlock && !set) {
this.mainContentBlock.removeAttribute('inert');
document.documentElement.classList.remove('overflow-hidden');
}
}
}
|
RadarRadarRadar/practice-template | scripts/build.ts | <reponame>RadarRadarRadar/practice-template
import { build } from "esbuild";
/**
* Generic options passed during build.
*/
interface BuildOptions {
env: "production" | "development";
}
/**
* A builder function for the app package.
*/
export async function buildApp(options: BuildOptions) {
const { env } = options;
await build({
entryPoints: ["packages/app/src/index.tsx"],
outfile: "packages/app/public/script.js",
define: {
"process.env.NODE_ENV": `"${env}"`,
},
bundle: true,
minify: env === "production",
sourcemap: env === "development",
});
}
/**
* A builder function for the server package.
*/
export async function buildServer(options: BuildOptions) {
const { env } = options;
await build({
entryPoints: ["packages/server/src/index.ts"],
outfile: "packages/server/dist/index.js",
define: {
"process.env.NODE_ENV": `"${env}"`,
},
external: ["express"],
platform: "node",
target: "node14.15.5",
bundle: true,
minify: env === "production",
sourcemap: env === "development",
});
}
/**
* A builder function for all packages.
*/
async function buildAll() {
await Promise.all([
buildApp({
env: "production",
}),
buildServer({
env: "production",
}),
]);
}
// This method is executed when we run the script from the terminal with ts-node
buildAll();
|
RadarRadarRadar/practice-template | packages/common/src/index.ts | <gh_stars>10-100
export const APP_TITLE = "tutorial-app";
|
Lusito/typed-undomanager | src/UndoableEdit.ts | <filename>src/UndoableEdit.ts
/* eslint-disable @typescript-eslint/no-unused-vars */
/**
* The base class for undoables
*/
export abstract class UndoableEdit {
/**
* This action reverts the changes of the edit.
*/
public abstract undo(): void;
/**
* This action re-applies the changes of the edit.
*/
public abstract redo(): void;
/**
* Try to merge a new edit into an existing one. This can be used to merge smaller edits into larger edits.
* For example a text editor can merge multiple changes into one, rather than having one edit per character change.
*
* @param edit The new edit
* @returns true if the edit was merged, false otherwise
*/
public merge(edit: UndoableEdit): boolean {
return false;
}
/**
* Try to replace an existing edit with a new one
*
* @param edit The new edit
* @returns true if this edit should be replaced with the new one, false otherwise
*/
public replace(edit: UndoableEdit): boolean {
return false;
}
/**
* A significant edit is worthy to be saved and to be displayed to the user as undoable.
* A typical insignificant edit would be if two edits got merged into one, ending up with the original.
* Another example is when selection changes have been done, which don't change the data.
*
* @return true if the edit was significant
*/
public isSignificant(): boolean {
return true;
}
}
|
Lusito/typed-undomanager | src/index.ts | <reponame>Lusito/typed-undomanager
export * from "./UndoManager";
export * from "./UndoableEdit";
|
Lusito/typed-undomanager | src/UndoManager.ts | import { UndoableEdit } from "./UndoableEdit";
/**
* The UndoManager keeps track of all editables.
*/
export class UndoManager {
private edits: UndoableEdit[] = [];
private position = 0;
private unmodifiedPosition = 0;
private limit: number;
private listener: null | (() => void) = null;
/**
* Create a new UndoManager
*
* @param limit The maximum amount of editables to remember
*/
public constructor(limit = 100) {
this.limit = limit;
}
/**
* The listener will be called when changes have been done (adding an edit, or undoing/redoing it)
*
* @param listener The new callback or null to remove the existing one.
*/
public setListener(listener: null | (() => void)) {
this.listener = listener;
}
/**
* Test if there is anything to be saved
*/
public isModified() {
if (this.unmodifiedPosition === -1) return true;
if (this.position === this.unmodifiedPosition) return false;
if (this.edits.length <= this.unmodifiedPosition) return true;
let from = this.testUndo(this.unmodifiedPosition);
from = from === false ? this.unmodifiedPosition : from + 1;
let to = this.testRedo(this.unmodifiedPosition);
to = to === false ? this.unmodifiedPosition + 1 : to - 1;
return this.position < from || this.position > to;
}
/**
* Mark the point when the data has been saved.
*/
public setUnmodified() {
this.unmodifiedPosition = this.position;
}
/**
* Get the maximum amount of editables to remember
*/
public getLimit(): number {
return this.limit;
}
/**
* Set the maximum amount of editables to remember.
* The new limit will be applied instantly.
*
* @param value The maximum amount of editables to remember
*/
public setLimit(value: number): void {
this.applyLimit((this.limit = value));
}
/**
* Clear all edits
*/
public clear(): void {
this.edits.length = 0;
this.position = 0;
this.unmodifiedPosition = 0;
this.listener?.();
}
private applyLimit(limit: number) {
const diff = this.edits.length - limit;
if (diff > 0) {
this.position = Math.max(0, this.position - diff);
if (this.unmodifiedPosition !== -1) this.unmodifiedPosition = Math.max(0, this.unmodifiedPosition - diff);
this.edits.splice(0, diff);
}
}
/**
* Test to see the new position after an undo would happen.
*
* @param position The start position
* @return False if no significant edit can be undone.
* Otherwise the new position.
*/
private testUndo(position: number): number | false {
for (let i = position - 1; i >= 0; i--) {
if (this.edits[i].isSignificant()) return i;
}
return false;
}
/**
* @returns true if there is anything to be undone (only significant edits count)
*/
public canUndo(): boolean {
return this.testUndo(this.position) !== false;
}
/**
* Undo the last significant edit.
* This will undo all insignificant edits up to the edit to be undone.
*
* @throws Error if no edit can be undone.
*/
public undo(): void {
const newPosition = this.testUndo(this.position);
if (newPosition === false) throw new Error("Cannot undo");
while (this.position > newPosition) {
const next = this.edits[--this.position];
next.undo();
}
this.listener?.();
}
/**
* Test to see the new position after an redo would happen.
*
* @param position The start position
* @return False if no significant edit can be redone.
* Otherwise the new position.
*/
private testRedo(position: number): number | false {
for (let i = position; i < this.edits.length; i++) {
if (this.edits[i].isSignificant()) return i + 1;
}
return false;
}
/**
* @returns true if there is anything to be redone (only significant edits count)
*/
public canRedo(): boolean {
return this.testRedo(this.position) !== false;
}
/**
* Redo the next significant edit.
* This will redo all insignificant edits up to the edit to be redone.
*
* @throws Error if no edit can be redone.
*/
public redo(): void {
const newPosition = this.testRedo(this.position);
if (newPosition === false) throw new Error("Cannot redo");
while (this.position < newPosition) {
const next = this.edits[this.position++];
next.redo();
}
this.listener?.();
}
/**
* Add a new edit. Will try to merge or replace existing edits.
*
* @param edit The new edit to add.
*/
public add(edit: UndoableEdit) {
if (this.edits.length > this.position) this.edits.length = this.position;
if (this.edits.length === 0 || this.unmodifiedPosition === this.edits.length) this.edits.push(edit);
else {
const last = this.edits[this.edits.length - 1];
if (!last.merge(edit)) {
if (edit.replace(last)) this.edits.pop();
this.edits.push(edit);
}
}
this.applyLimit(this.limit);
this.position = this.edits.length;
if (this.unmodifiedPosition >= this.position) this.unmodifiedPosition = -1;
this.listener?.();
}
}
|
Lusito/typed-undomanager | src/UndoManager.spec.ts | <gh_stars>1-10
import { UndoableEdit } from "./UndoableEdit";
import { UndoManager } from "./UndoManager";
class UndoableSpy extends UndoableEdit {
public undoneCount = 0;
public redoneCount = 0;
public undo(): void {
this.undoneCount++;
}
public redo(): void {
this.redoneCount++;
}
}
class UndoableMergeSpy extends UndoableSpy {
public mergeCalls = 0;
public mergeCount = 0;
public merge(edit: UndoableEdit): boolean {
this.mergeCalls++;
if (edit instanceof UndoableMergeSpy) {
this.mergeCount++;
return true;
}
return false;
}
}
class UndoableReplaceSpy extends UndoableSpy {
public replaceCalls = 0;
public replace(edit: UndoableEdit): boolean {
this.replaceCalls++;
return edit instanceof UndoableReplaceSpy;
}
}
class UndoableInsignificantSpy extends UndoableSpy {
public isSignificant(): boolean {
return false;
}
}
class UndoableMerge extends UndoableSpy {
private readonly oldValue: number;
private newValue: number;
public constructor(oldValue: number, newValue: number) {
super();
this.oldValue = oldValue;
this.newValue = newValue;
}
public merge(edit: UndoableEdit): boolean {
if (edit instanceof UndoableMerge) {
this.newValue = edit.newValue;
return true;
}
return false;
}
public isSignificant(): boolean {
return this.newValue !== this.oldValue;
}
}
describe("UndoManager", () => {
test("add_undo_and_redo", () => {
const manager = new UndoManager();
const undoable = new UndoableSpy();
manager.add(undoable);
expect(undoable.undoneCount).toBe(0);
expect(undoable.redoneCount).toBe(0);
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(false);
manager.undo();
expect(undoable.undoneCount).toBe(1);
expect(undoable.redoneCount).toBe(0);
manager.redo();
expect(undoable.undoneCount).toBe(1);
expect(undoable.redoneCount).toBe(1);
});
test("add_two_undo_and_redo", () => {
const manager = new UndoManager();
const undoable1 = new UndoableSpy();
const undoable2 = new UndoableSpy();
manager.add(undoable1);
manager.add(undoable2);
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(false);
manager.undo();
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(true);
manager.undo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
manager.redo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(1);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
manager.redo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(1);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(1);
});
test("add_undo_and_redo_middle", () => {
const manager = new UndoManager();
const undoable1 = new UndoableSpy();
const undoable2 = new UndoableSpy();
const undoable3 = new UndoableSpy();
manager.add(undoable1);
manager.add(undoable2);
manager.undo();
manager.add(undoable3);
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(false);
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(0);
expect(undoable3.redoneCount).toBe(0);
manager.undo();
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(0);
manager.undo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(0);
manager.redo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(1);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(0);
manager.redo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(1);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(1);
});
test("merge_undo_redo", () => {
const manager = new UndoManager();
const undoable1 = new UndoableSpy();
const undoable2 = new UndoableMergeSpy();
const undoable3 = new UndoableMergeSpy();
const undoable4 = new UndoableSpy();
manager.add(undoable1);
manager.add(undoable2);
manager.add(undoable3);
manager.add(undoable4);
expect(undoable2.mergeCalls).toBe(2);
expect(undoable2.mergeCount).toBe(1);
expect(undoable3.mergeCalls).toBe(0);
manager.undo();
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(0);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(0);
expect(undoable3.redoneCount).toBe(0);
expect(undoable4.undoneCount).toBe(1);
expect(undoable4.redoneCount).toBe(0);
manager.undo();
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(0);
expect(undoable3.redoneCount).toBe(0);
expect(undoable4.undoneCount).toBe(1);
expect(undoable4.redoneCount).toBe(0);
manager.undo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(0);
expect(undoable3.redoneCount).toBe(0);
expect(undoable4.undoneCount).toBe(1);
expect(undoable4.redoneCount).toBe(0);
manager.redo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(1);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(0);
expect(undoable3.redoneCount).toBe(0);
expect(undoable4.undoneCount).toBe(1);
expect(undoable4.redoneCount).toBe(0);
manager.redo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(1);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(1);
expect(undoable3.undoneCount).toBe(0);
expect(undoable3.redoneCount).toBe(0);
expect(undoable4.undoneCount).toBe(1);
expect(undoable4.redoneCount).toBe(0);
manager.redo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(1);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(1);
expect(undoable3.undoneCount).toBe(0);
expect(undoable3.redoneCount).toBe(0);
expect(undoable4.undoneCount).toBe(1);
expect(undoable4.redoneCount).toBe(1);
});
test("limit", () => {
const manager = new UndoManager(2);
const undoable1 = new UndoableSpy();
const undoable2 = new UndoableSpy();
const undoable3 = new UndoableSpy();
expect(manager.getLimit()).toBe(2);
manager.add(undoable1);
manager.add(undoable2);
manager.add(undoable3);
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(false);
manager.undo();
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(true);
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(0);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(0);
manager.undo();
expect(manager.canUndo()).toBe(false);
expect(manager.canRedo()).toBe(true);
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(0);
manager.redo();
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(true);
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(1);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(0);
manager.redo();
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(false);
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(1);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(1);
});
test("limit_after_add", () => {
const manager = new UndoManager();
const undoable1 = new UndoableSpy();
const undoable2 = new UndoableSpy();
const undoable3 = new UndoableSpy();
manager.add(undoable1);
manager.add(undoable2);
manager.add(undoable3);
manager.setLimit(2);
expect(manager.getLimit()).toBe(2);
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(false);
manager.undo();
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(0);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(0);
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(true);
manager.undo();
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(0);
expect(manager.canUndo()).toBe(false);
expect(manager.canRedo()).toBe(true);
});
test("limit_after_add_save_marker_gone", () => {
const manager = new UndoManager();
expect(manager.isModified()).toBe(false);
manager.add(new UndoableSpy());
manager.add(new UndoableSpy());
manager.add(new UndoableSpy());
manager.setUnmodified();
manager.undo();
manager.add(new UndoableSpy());
manager.setLimit(2);
expect(manager.isModified()).toBe(true);
while (manager.canUndo()) {
manager.undo();
expect(manager.isModified()).toBe(true);
}
while (manager.canRedo()) {
manager.redo();
expect(manager.isModified()).toBe(true);
}
});
test("errors", () => {
const manager = new UndoManager();
expect(() => manager.undo()).toThrow();
expect(() => manager.redo()).toThrow();
manager.add(new UndoableSpy());
expect(() => manager.redo()).toThrow();
manager.undo();
expect(() => manager.undo()).toThrow();
});
test("clear", () => {
const manager = new UndoManager();
manager.add(new UndoableSpy());
manager.add(new UndoableSpy());
manager.add(new UndoableSpy());
manager.clear();
expect(manager.canUndo()).toBe(false);
expect(manager.canRedo()).toBe(false);
expect(() => manager.undo()).toThrow();
expect(() => manager.redo()).toThrow();
// perform basic test afterwards to see if it still works.
const undoable = new UndoableSpy();
manager.add(undoable);
expect(undoable.undoneCount).toBe(0);
expect(undoable.redoneCount).toBe(0);
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(false);
manager.undo();
expect(undoable.undoneCount).toBe(1);
expect(undoable.redoneCount).toBe(0);
manager.redo();
expect(undoable.undoneCount).toBe(1);
expect(undoable.redoneCount).toBe(1);
});
test("insignificant", () => {
const manager = new UndoManager();
const undoable1 = new UndoableSpy();
const undoable2 = new UndoableInsignificantSpy();
const undoable3 = new UndoableInsignificantSpy();
const undoable4 = new UndoableSpy();
manager.add(undoable1);
manager.add(undoable2);
manager.add(undoable3);
manager.add(undoable4);
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(0);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(0);
expect(undoable3.redoneCount).toBe(0);
expect(undoable4.undoneCount).toBe(0);
expect(undoable4.redoneCount).toBe(0);
manager.undo();
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(0);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(0);
expect(undoable3.redoneCount).toBe(0);
expect(undoable4.undoneCount).toBe(1);
expect(undoable4.redoneCount).toBe(0);
manager.undo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(0);
expect(undoable4.undoneCount).toBe(1);
expect(undoable4.redoneCount).toBe(0);
expect(manager.canUndo()).toBe(false);
manager.redo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(1);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(0);
expect(undoable4.undoneCount).toBe(1);
expect(undoable4.redoneCount).toBe(0);
manager.redo();
expect(undoable1.undoneCount).toBe(1);
expect(undoable1.redoneCount).toBe(1);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(1);
expect(undoable3.undoneCount).toBe(1);
expect(undoable3.redoneCount).toBe(1);
expect(undoable4.undoneCount).toBe(1);
expect(undoable4.redoneCount).toBe(1);
expect(manager.canRedo()).toBe(false);
});
test("save_marker", () => {
const manager = new UndoManager();
expect(manager.isModified()).toBe(false);
const undoable1 = new UndoableSpy();
manager.add(undoable1);
expect(manager.isModified()).toBe(true);
manager.undo();
expect(manager.isModified()).toBe(false);
manager.redo();
expect(manager.isModified()).toBe(true);
manager.setUnmodified();
expect(manager.isModified()).toBe(false);
manager.undo();
expect(manager.isModified()).toBe(true);
manager.redo();
expect(manager.isModified()).toBe(false);
});
test("save_marker_gone", () => {
const manager = new UndoManager();
expect(manager.isModified()).toBe(false);
manager.add(new UndoableSpy());
manager.add(new UndoableSpy());
manager.setUnmodified();
expect(manager.isModified()).toBe(false);
manager.undo();
expect(manager.isModified()).toBe(true);
manager.add(new UndoableSpy());
expect(manager.isModified()).toBe(true);
while (manager.canUndo()) {
manager.undo();
expect(manager.isModified()).toBe(true);
}
while (manager.canRedo()) {
manager.redo();
expect(manager.isModified()).toBe(true);
}
});
test("save_marker_insignificant", () => {
const manager = new UndoManager();
const undoable1 = new UndoableSpy();
const undoable2 = new UndoableInsignificantSpy();
const undoable3 = new UndoableInsignificantSpy();
const undoable4 = new UndoableSpy();
manager.add(undoable1);
manager.add(undoable2);
manager.add(undoable3);
manager.add(undoable4);
expect(manager.isModified()).toBe(true);
manager.setUnmodified();
expect(manager.isModified()).toBe(false);
manager.undo(); // 4 undone
expect(manager.isModified()).toBe(true);
manager.setUnmodified();
expect(manager.isModified()).toBe(false);
manager.undo(); // 3,2,1 undone
expect(manager.isModified()).toBe(true);
manager.redo(); // 1 redone
expect(manager.isModified()).toBe(false);
manager.redo(); // 2,3,4 redone
expect(manager.isModified()).toBe(true);
manager.setUnmodified();
manager.undo(); // 4 undone
manager.undo(); // 3,2,1 undone
expect(manager.isModified()).toBe(true);
manager.redo(); // 1 redone
expect(manager.isModified()).toBe(true);
manager.redo(); // 2,3,4 redone
expect(manager.isModified()).toBe(false);
});
test("save_marker_merged_insignificant", () => {
const manager = new UndoManager();
manager.add(new UndoableMerge(0, 1));
expect(manager.isModified()).toBe(true);
manager.add(new UndoableMerge(1, 0));
expect(manager.isModified()).toBe(false);
});
test("save_marker_saved_then_merged_insignificant", () => {
const manager = new UndoManager();
manager.add(new UndoableMerge(0, 1));
expect(manager.isModified()).toBe(true);
manager.setUnmodified();
manager.add(new UndoableMerge(1, 0));
expect(manager.isModified()).toBe(true);
});
test("replace", () => {
const manager = new UndoManager();
const undoable1 = new UndoableReplaceSpy();
const undoable2 = new UndoableReplaceSpy();
manager.add(undoable1);
manager.add(undoable2);
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(false);
manager.undo();
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(0);
expect(manager.canUndo()).toBe(false);
expect(manager.canRedo()).toBe(true);
manager.redo();
expect(undoable1.undoneCount).toBe(0);
expect(undoable1.redoneCount).toBe(0);
expect(undoable2.undoneCount).toBe(1);
expect(undoable2.redoneCount).toBe(1);
expect(manager.canUndo()).toBe(true);
expect(manager.canRedo()).toBe(false);
});
test("listener", () => {
let count = 0;
const manager = new UndoManager();
manager.setListener(() => count++);
expect(count).toBe(0);
manager.add(new UndoableSpy());
expect(count).toBe(1);
manager.undo();
expect(count).toBe(2);
manager.redo();
expect(count).toBe(3);
manager.clear();
expect(count).toBe(4);
manager.add(new UndoableSpy());
expect(count).toBe(5);
manager.add(new UndoableInsignificantSpy());
expect(count).toBe(6);
manager.add(new UndoableInsignificantSpy());
expect(count).toBe(7);
manager.add(new UndoableSpy());
expect(count).toBe(8);
manager.undo();
expect(count).toBe(9);
manager.undo();
expect(count).toBe(10);
expect(manager.canUndo()).toBe(false);
});
});
|
niklaskorz/nkchat | packages/client/src/components/organisms/Chat/index.tsx | import gql from 'graphql-tag';
import Linkify from 'linkifyjs/react';
import React from 'react';
import { ChildProps, compose, graphql, MutationFunc } from 'react-apollo';
import { Helmet } from 'react-helmet';
import ChatError from '../../molecules/ChatError';
import Embed, { Props as EmbedProps } from '../../molecules/Embed';
import Loading from '../../molecules/Loading';
import RoomInfo from '../../molecules/RoomInfo';
import {
Header,
Message,
MessageAuthor,
MessageDate,
MessageHeader,
MessageInput,
MessageInputContainer,
Messages,
MessageSendButton,
MessageText,
MessageWrapper,
NewMessageContainer,
Section,
} from './styled';
interface User {
id: string;
name: string;
}
interface Message {
id: string;
createdAt: string;
content: string;
author: User;
viewerIsAuthor: boolean;
embeds: EmbedProps[];
}
interface Room {
id: string;
name: string;
messages: Message[];
members: User[];
}
interface Response {
room: Room;
}
interface Props {
roomId: string;
sendMessage: MutationFunc<
{ sendMessage: { id: string } },
{ roomId: string; content: string }
>;
}
interface State {
inputText: string;
}
const compareMessages = (a: Message, b: Message): number => {
const dateA = new Date(a.createdAt);
const dateB = new Date(a.createdAt);
return dateA.getTime() - dateB.getTime();
};
const ChatMessageFragment = gql`
fragment ChatMessage on Message {
id
createdAt
content
author {
id
name
}
viewerIsAuthor
embeds {
type
src
}
}
`;
const ChatQuery = gql`
${ChatMessageFragment}
query ChatQuery($roomId: ObjectID!) {
room(id: $roomId) {
id
name
viewerIsMember
messages {
...ChatMessage
}
members {
id
name
}
}
}
`;
interface ChatSubscriptionData {
data: { messageWasSent: Message };
}
const ChatSubscription = gql`
${ChatMessageFragment}
subscription ChatSubscription($roomId: ObjectID!) {
messageWasSent(roomId: $roomId) {
...ChatMessage
}
}
`;
interface UserSubscriptionData {
data: { userJoinedRoom: User };
}
const UserSubscription = gql`
subscription UserSubscription($roomId: ObjectID!) {
userJoinedRoom(roomId: $roomId) {
id
name
}
}
`;
class Chat extends React.Component<ChildProps<Props, Response>, State> {
messageContainer?: HTMLDivElement;
stickToBottom: boolean = true;
unsubscribeMessages?: () => void;
unsubscribeUsers?: () => void;
state: State = {
inputText: '',
};
componentDidMount() {
this.stickToBottom = true;
if (this.messageContainer) {
this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
}
this.subscribeToMessages();
this.subscribeToNewUsers();
}
componentWillUnmount() {
if (this.unsubscribeMessages) {
this.unsubscribeMessages();
this.unsubscribeMessages = undefined;
}
if (this.unsubscribeUsers) {
this.unsubscribeUsers();
this.unsubscribeUsers = undefined;
}
}
componentDidUpdate(prevProps: ChildProps<Props, Response>) {
if (
this.messageContainer &&
this.props.data !== prevProps.data &&
this.stickToBottom
) {
this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
}
// Room changed
if (this.props.roomId !== prevProps.roomId) {
this.stickToBottom = true;
if (this.messageContainer) {
this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
}
if (this.unsubscribeMessages) {
this.unsubscribeMessages();
this.unsubscribeMessages = undefined;
}
if (this.unsubscribeUsers) {
this.unsubscribeUsers();
this.unsubscribeUsers = undefined;
}
}
if (!this.unsubscribeMessages) {
// Not subscribed currently, try to subscribe
this.subscribeToMessages();
}
if (!this.unsubscribeUsers) {
// Not subscribed currently, try to subscribe
this.subscribeToNewUsers();
}
}
refMessageContainer = (el: HTMLDivElement) => {
this.messageContainer = el;
if (this.messageContainer && this.stickToBottom) {
this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
}
};
subscribeToMessages() {
const { roomId, data } = this.props;
if (!data) {
return;
}
this.unsubscribeMessages = data.subscribeToMore({
document: ChatSubscription,
variables: { roomId },
updateQuery: (
prev: Response,
{ subscriptionData }: { subscriptionData: ChatSubscriptionData },
) => {
if (!subscriptionData.data) {
return prev;
}
const newMessage = subscriptionData.data.messageWasSent;
const messages = [...prev.room.messages];
const messageIndex = messages.findIndex(m => m.id === newMessage.id);
if (messageIndex !== -1) {
messages[messageIndex] = newMessage;
} else {
messages.push(newMessage);
}
messages.sort(compareMessages);
return {
...prev,
room: {
...prev.room,
messages,
},
};
},
});
}
subscribeToNewUsers() {
const { roomId, data } = this.props;
if (!data) {
return;
}
this.unsubscribeUsers = data.subscribeToMore({
document: UserSubscription,
variables: { roomId },
updateQuery: (
prev: Response,
{ subscriptionData }: { subscriptionData: UserSubscriptionData },
) => {
if (!subscriptionData.data) {
return prev;
}
const newUser = subscriptionData.data.userJoinedRoom;
return {
...prev,
room: {
...prev.room,
members: [...prev.room.members, newUser],
},
};
},
});
}
sendMessage = () => {
const { sendMessage, data } = this.props;
const { inputText } = this.state;
if (!data) {
return;
}
const { room } = data;
if (!room) {
return;
}
const content = inputText.trim();
if (!content.length || content.length > 500) {
return;
}
this.setState({ inputText: '' });
// Reset scroll preference so we see our new message
this.stickToBottom = true;
sendMessage({ variables: { roomId: room.id, content } });
};
onMessagesScroll: React.UIEventHandler<HTMLDivElement> = e => {
const target = e.currentTarget;
const height = target.getBoundingClientRect().height;
const scrollBottom = target.scrollTop + height;
this.stickToBottom = target.scrollHeight - scrollBottom <= 100;
};
onInputTextChange: React.ChangeEventHandler<HTMLTextAreaElement> = e => {
this.setState({ inputText: e.currentTarget.value });
};
onInputTextKeyDown: React.KeyboardEventHandler<HTMLTextAreaElement> = e => {
if (e.keyCode === 13 && !e.shiftKey) {
e.preventDefault();
this.sendMessage();
}
};
onEmbedLoaded = () => {
if (this.messageContainer && this.stickToBottom) {
// Make sure we're still at the bottom
this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
}
};
render() {
if (!this.props.data) {
return null;
}
const { loading, error, room } = this.props.data;
if (loading) {
return <Loading />;
}
if (error) {
return <ChatError errorMessage={error.message} />;
}
if (!room) {
return 'Room not found';
}
const { inputText } = this.state;
return (
<React.Fragment>
<Helmet title={room.name} />
<Section>
<Header title={room.name}>{room.name}</Header>
<Messages
innerRef={this.refMessageContainer}
onScroll={this.onMessagesScroll}
>
{room.messages.map(message => (
<MessageWrapper
key={message.id}
viewerIsAuthor={message.viewerIsAuthor}
>
<Message viewerIsAuthor={message.viewerIsAuthor}>
<MessageHeader>
<MessageAuthor>{message.author.name}</MessageAuthor>
<MessageDate>
{new Date(message.createdAt).toLocaleString()}
</MessageDate>
</MessageHeader>
<MessageText>
<Linkify>{message.content}</Linkify>
</MessageText>
{message.embeds
.slice(0, 3) // Limit embeds to 3 per message
.map((embed, i) => (
<Embed
key={i}
type={embed.type}
src={embed.src}
onLoad={this.onEmbedLoaded}
/>
))}
</Message>
</MessageWrapper>
))}
</Messages>
<NewMessageContainer>
<MessageInputContainer>
<MessageInput
useCacheForDOMMeasurements
value={inputText}
onChange={this.onInputTextChange}
onKeyDown={this.onInputTextKeyDown}
/>
</MessageInputContainer>
<MessageSendButton type="button" onClick={this.sendMessage}>
Send
</MessageSendButton>
</NewMessageContainer>
</Section>
<RoomInfo room={room} />
</React.Fragment>
);
}
}
interface QueryVariables {
roomId: string;
}
const withData = graphql<QueryVariables, Response, QueryVariables>(ChatQuery, {
options: ({ roomId }) => ({
variables: { roomId },
// Use cache-and-network policy to ensure we get the most recent messages
// but also start seeing the already cached messages while the new ones are
// loading
fetchPolicy: 'cache-and-network',
}),
});
const withSendMessageMutation = graphql(
gql`
mutation SendMessage($roomId: ObjectID!, $content: String!) {
sendMessage(input: { roomId: $roomId, content: $content }) {
id
}
}
`,
{ name: 'sendMessage' },
);
export default compose(
withData,
withSendMessageMutation,
)(Chat);
|
niklaskorz/nkchat | packages/server/typings/mongodb.d.ts | declare module 'mongodb' {
export { ObjectID } from 'typeorm';
}
|
niklaskorz/nkchat | packages/client/src/components/pages/LoginPage.tsx | <reponame>niklaskorz/nkchat
import * as colors from 'colors';
import formatError from 'formatError';
import gql from 'graphql-tag';
import React from 'react';
import { ChildProps, compose, graphql, MutationFunc } from 'react-apollo';
import { Helmet } from 'react-helmet';
import { Link, Redirect } from 'react-router-dom';
import styled from 'styled-components';
import client from '../../apollo';
import ErrorMessage from '../atoms/ErrorMessage';
const Container = styled.div`
background: ${colors.darkPrimary};
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
`;
const Form = styled.form`
background: ${colors.primary};
display: flex;
flex-direction: column;
padding: 20px;
border-radius: 2px;
width: 400px;
max-width: 100%;
`;
const Title = styled.h1`
text-align: center;
`;
const Input = styled.input`
margin-bottom: 20px;
border: 1px solid ${colors.secondary};
padding: 15px 10px;
border-radius: 2px;
box-shadow: none;
`;
const Button = styled.button`
border: 1px solid ${colors.darkSecondary};
background: ${colors.darkSecondary};
color: ${colors.darkSecondaryText};
padding: 15px 10px;
margin-bottom: 15px;
border-radius: 2px;
text-transform: uppercase;
cursor: pointer;
transition: 0.1s background ease, 0.1s color ease;
:hover,
:active {
background: ${colors.secondary};
color: ${colors.primaryText};
}
`;
const InfoText = styled.p`
text-align: center;
`;
interface Session {
id: string;
}
interface LoginVariables {
name: string;
password: string;
}
interface Props {
location: {
pathname: string;
state?: {
from: {
pathname: string;
};
};
};
login: MutationFunc<{ login: Session }, LoginVariables>;
register: MutationFunc<{ register: Session }, LoginVariables>;
}
interface Response {
viewer: {
id: string;
};
}
interface State {
name: string;
password: string;
errorMessage?: string;
redirect?: string;
}
class LoginPage extends React.Component<ChildProps<Props, Response>, State> {
state: State = {
name: '',
password: '',
};
componentDidUpdate(prevProps: Props) {
if (this.props.location.pathname !== prevProps.location.pathname) {
this.setState({ errorMessage: undefined });
}
}
onNameChange: React.ChangeEventHandler<HTMLInputElement> = e => {
this.setState({ name: e.currentTarget.value });
};
onPasswordChange: React.ChangeEventHandler<HTMLInputElement> = e => {
this.setState({ password: e.currentTarget.value });
};
onSubmit: React.FormEventHandler<HTMLFormElement> = async e => {
e.preventDefault();
const { name, password } = this.state;
const {
location: { pathname },
} = this.props;
try {
if (pathname === '/register') {
await this.props.register({
variables: { name, password },
});
} else {
await this.props.login({
variables: { name, password },
});
}
// Reset store so Apollo re-fetches the viewer
await client.resetStore();
if (this.props.location.state) {
// Reloads and redirects to the chat room visited before
// the user was redirected to the login page
this.setState({ redirect: this.props.location.state.from.pathname });
} else {
// Redirects the user to the room list if no room was open before
// the user was redirected to the login page
this.setState({ redirect: '/' });
}
} catch (ex) {
this.setState({ errorMessage: formatError(ex.message) });
}
};
render() {
const { name, password, errorMessage, redirect } = this.state;
const {
location: { pathname },
} = this.props;
const isRegistration = pathname === '/register';
const label = isRegistration ? 'Register' : 'Login';
if (redirect) {
return <Redirect to={redirect} />;
}
return (
<Container>
<Helmet title={label} />
<Form onSubmit={this.onSubmit}>
<Title>{label}</Title>
{errorMessage && <ErrorMessage>{errorMessage}</ErrorMessage>}
<Input
type="text"
placeholder="Name"
autoFocus
required
value={name}
onChange={this.onNameChange}
/>
<Input
type="password"
placeholder="Password"
required
value={password}
onChange={this.onPasswordChange}
/>
<Button type="submit">{label}</Button>
{!isRegistration && (
<InfoText>
Don't have an account yet?{' '}
<Link to="/register">Register here</Link>
</InfoText>
)}
{isRegistration && (
<InfoText>
Already have an account? <Link to="/login">Login here</Link>
</InfoText>
)}
</Form>
</Container>
);
}
}
const LoginMutation = gql`
mutation LoginMutation($name: String!, $password: String!) {
login(input: { name: $name, password: $password }) {
id
}
}
`;
const RegisterMutation = gql`
mutation RegisterMutation($name: String!, $password: String!) {
register(input: { name: $name, password: $password }) {
id
}
}
`;
const withMutations = compose(
graphql(LoginMutation, { name: 'login' }),
graphql(RegisterMutation, { name: 'register' }),
);
export default withMutations(LoginPage);
|
niklaskorz/nkchat | packages/server/src/resolvers/MessageResolver.ts | import getUrls from 'get-urls';
import { ObjectID } from 'mongodb';
import {
Arg,
Ctx,
Field,
FieldResolver,
InputType,
Mutation,
Publisher,
PubSub,
Resolver,
Root,
Subscription,
} from 'type-graphql';
import { MongoRepository } from 'typeorm';
import { InjectRepository } from 'typeorm-typedi-extensions';
import { URL } from 'url';
import Context from '../Context';
import {
Embed,
EmbedType,
Message,
Room,
User,
userIsMemberOfRoom,
} from '../models';
import { SubscriptionType } from '../subscriptions';
type EmbedParser = (url: URL) => Embed | null;
const embedHosts = new Map<string, EmbedParser>([
[
'youtube.com',
url => {
const videoId = url.searchParams.get('v');
if (!videoId || url.pathname !== '/watch') {
return null;
}
const embed = new Embed();
embed.type = EmbedType.Youtube;
embed.src = videoId;
return embed;
},
],
[
'youtu.be',
url => {
const videoId = url.pathname.slice(1);
const embed = new Embed();
embed.type = EmbedType.Youtube;
embed.src = videoId;
return embed;
},
],
[
'alugha.com',
url => {
if (!url.pathname.startsWith('/videos/')) {
return null;
}
const videoId = url.pathname.slice('/videos/'.length);
const embed = new Embed();
embed.type = EmbedType.Alugha;
embed.src = videoId;
return embed;
},
],
]);
const imageEmbedParser: EmbedParser = url => {
if (
url.pathname.endsWith('.png') ||
url.pathname.endsWith('.jpg') ||
url.pathname.endsWith('.jpeg') ||
url.pathname.endsWith('.webp') ||
url.pathname.endsWith('.bmp') ||
url.pathname.endsWith('.tga')
) {
const embed = new Embed();
embed.type = EmbedType.Image;
embed.src = url.href;
return embed;
}
return null;
};
const getEmbeds = (text: string): Embed[] => {
const embeds = [];
for (const urlString of getUrls(text)) {
const url = new URL(urlString);
const parser = embedHosts.get(url.hostname);
const embed = (parser && parser(url)) || imageEmbedParser(url);
if (embed) {
embeds.push(embed);
}
}
return embeds;
};
@InputType()
class SendMessageInput {
@Field(type => ObjectID)
roomId: ObjectID;
@Field()
content: string;
}
interface MessageWasSentPayload {
roomId: ObjectID;
message: Message;
}
@Resolver(of => Message)
export class MessageResolver {
constructor(
@InjectRepository(Message)
private messageRepository: MongoRepository<Message>,
@InjectRepository(Room) private roomRepository: MongoRepository<Room>,
@InjectRepository(User) private userRepository: MongoRepository<User>,
) {}
@FieldResolver(type => Room)
// @ManyToOne(type => Room, room => room.messages)
async room(@Root() message: Message): Promise<Room> {
return await this.roomRepository.findOneOrFail(message.roomId);
}
@FieldResolver(type => User)
// @ManyToOne(type => User, user => user.messages)
async author(@Root() message: Message): Promise<User> {
return await this.userRepository.findOneOrFail(message.authorId);
}
@FieldResolver()
viewerIsAuthor(@Root() message: Message, @Ctx() ctx: Context): boolean {
const viewer = ctx.state.viewer;
if (!viewer) {
return false;
}
return message.authorId.equals(viewer.id);
}
@Mutation(returns => Message, {
description:
'Sends a message to a specific room and returns the sent message',
})
async sendMessage(
@Arg('input') input: SendMessageInput,
@Ctx() ctx: Context,
@PubSub(SubscriptionType.MessageWasSent)
publish: Publisher<MessageWasSentPayload>,
): Promise<Message> {
const viewer = ctx.state.viewer;
if (!viewer) {
throw new Error('Authentication required');
}
const room = await this.roomRepository.findOne(input.roomId);
if (!room) {
throw new Error('Room could not be found');
}
const viewerIsMember = userIsMemberOfRoom(viewer, room);
if (!viewerIsMember) {
throw new Error('Only members of a room can send messages to the room');
}
const message = new Message();
message.content = input.content;
message.authorId = viewer.id;
message.roomId = input.roomId;
message.embeds = getEmbeds(input.content);
await this.messageRepository.save(message);
publish({
roomId: input.roomId,
message,
});
return message;
}
@Subscription(returns => Message, {
description:
'Notifies when a message has been sent to the specified room and returns the sent message',
topics: SubscriptionType.MessageWasSent,
filter: ({ payload, args }) => payload.roomId.equals(args.roomId),
})
messageWasSent(
@Root() payload: MessageWasSentPayload,
@Arg('roomId', type => ObjectID) roomId: ObjectID,
): Message {
return payload.message;
}
}
|
niklaskorz/nkchat | packages/server/src/models/Room.ts | <filename>packages/server/src/models/Room.ts
import { ObjectID } from 'mongodb';
import { Field, ObjectType } from 'type-graphql';
import { Column, Entity, ObjectIdColumn } from 'typeorm';
import { User } from './User';
@ObjectType({
description:
'A room contains information about the messages sent into the room and ' +
"the users participating in the room's conversation",
})
@Entity()
export class Room {
@Field(type => ObjectID)
@ObjectIdColumn()
readonly id: ObjectID;
@Field()
@Column()
name: string;
@Field(type => ObjectID)
@Column()
ownerId: ObjectID;
@Field(type => [ObjectID])
@Column()
memberIds: ObjectID[];
@Field()
createdAt(): Date {
return this.id.getTimestamp();
}
}
export const userIsMemberOfRoom = (user: User, room: Room): boolean => {
return !!room.memberIds.find(memberId => user.id.equals(memberId));
};
|
niklaskorz/nkchat | packages/client/src/components/molecules/RoomList.tsx | <filename>packages/client/src/components/molecules/RoomList.tsx
import * as colors from 'colors';
import React from 'react';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
import swal from 'sweetalert2';
import SideBar from './SideBar';
const ActionBar = styled.div`
flex-shrink: 0;
display: flex;
margin: 10px;
margin-bottom: 0;
font-size: 0.8em;
`;
const Action = styled.button`
border: none;
background: transparent;
border: 1px solid ${colors.darkSecondaryText};
color: ${colors.darkSecondaryText};
flex: 1;
appearance: none;
cursor: pointer;
padding: 5px 10px;
margin: 0 5px;
border-radius: 2px;
text-transform: uppercase;
font-size: 0.75em;
transition: 0.1s ease color, 0.1s ease background;
:hover {
background: ${colors.darkSecondaryText};
color: ${colors.darkSecondary};
}
`;
Action.defaultProps = {
type: 'button',
};
const List = styled.ul`
display: block;
margin: 0;
padding: 10px 0;
overflow: auto;
flex: 1;
font-size: 0.8em;
`;
const ItemLink = styled(Link)`
display: block;
padding: 10px 15px;
cursor: pointer;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
color: ${colors.darkSecondaryText};
text-decoration: none;
transition: 0.1s ease color, 0.1s ease background;
:hover,
&.active {
background: ${colors.darkSecondary};
color: ${colors.darkPrimaryText};
}
`;
const Footer = styled.footer`
border-top: 2px solid ${colors.darkSecondary};
border-bottom: 2px solid transparent;
font-size: 0.8em;
display: flex;
align-items: center;
height: 56px;
`;
const Viewer = styled.div`
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin: 10px 5px;
margin-left: 15px;
flex: 1;
`;
const LogoutButton = styled(Action)`
margin: 10px 5px;
margin-right: 15px;
flex: 0 0 auto;
`;
export interface Room {
id: string;
name: string;
}
interface Props {
viewerName: string;
rooms: Room[];
activeRoomId?: string;
onCreate(name: string): void;
onJoin(id: string): void;
onLogout(): void;
}
class RoomList extends React.Component<Props> {
showCreateDialog = async () => {
const result = await swal({
title: 'Create room',
input: 'text',
text: 'Room name',
showCancelButton: true,
confirmButtonText: 'Create',
});
if (!result.dismiss && result.value) {
this.props.onCreate(result.value);
}
};
showJoinDialog = async () => {
const result = await swal({
title: 'Join room',
input: 'text',
text: 'Room id',
showCancelButton: true,
confirmButtonText: 'Join',
});
if (!result.dismiss && result.value) {
this.props.onJoin(result.value);
}
};
render() {
const { rooms, viewerName, activeRoomId, onLogout } = this.props;
return (
<SideBar title="Rooms">
<ActionBar>
<Action onClick={this.showJoinDialog}>Join</Action>
<Action onClick={this.showCreateDialog}>Create</Action>
</ActionBar>
<List>
{rooms.map(room => (
<li key={room.id}>
<ItemLink
to={`/rooms/${room.id}`}
title={room.name}
className={room.id === activeRoomId ? 'active' : ''}
>
{room.name}
</ItemLink>
</li>
))}
</List>
<Footer>
<Viewer>{viewerName}</Viewer>
<LogoutButton onClick={onLogout}>Logout</LogoutButton>
</Footer>
</SideBar>
);
}
}
export default RoomList;
|
niklaskorz/nkchat | packages/server/typings/get-urls.d.ts | declare module 'get-urls' {
function getUrls(text: string, options?: any): Set<string>;
export = getUrls;
}
|
niklaskorz/nkchat | packages/client/src/colors.ts | export const darkPrimary = '#353b48';
export const darkSecondary = '#2f3640';
export const darkPrimaryText = '#f5f6fa';
export const darkSecondaryText = '#dcdde1';
export const primary = '#f5f6fa';
export const secondary = '#dcdde1';
export const primaryText = '#000';
export const secondaryText = '#2f3640';
export const error = '#e74c3c';
|
niklaskorz/nkchat | packages/client/src/components/molecules/ChatError.tsx | <filename>packages/client/src/components/molecules/ChatError.tsx
import formatError from 'formatError';
import React from 'react';
import CenteredContainer from '../atoms/CenteredContainer';
import ErrorMessage from '../atoms/ErrorMessage';
interface Props {
errorMessage: string;
}
export default class ChatError extends React.Component<Props> {
render() {
return (
<CenteredContainer>
<ErrorMessage>{formatError(this.props.errorMessage)}</ErrorMessage>
</CenteredContainer>
);
}
}
|
niklaskorz/nkchat | packages/server/src/models/index.ts | export * from './Message';
export * from './Room';
export * from './User';
|
niklaskorz/nkchat | packages/server/src/Context.ts | import Cookies from 'cookies';
import { User } from './models';
export interface State {
sessionId?: string;
viewer?: User;
}
export default interface Context {
cookies?: Cookies;
state: State;
}
|
niklaskorz/nkchat | packages/server/src/constants.ts | // One week
export const SESSION_EXPIRY_SECONDS = 1 * 7 * 24 * 60 * 60;
export const SESSION_EXPIRY_MILLISECONDS = SESSION_EXPIRY_SECONDS * 1000;
|
niklaskorz/nkchat | packages/server/src/config.ts | export const mongodbHost = process.env.MONGODB_HOST || '127.0.0.1';
export const natsHost = process.env.NATS_HOST || '127.0.0.1';
export const redisHost = process.env.REDIS_HOST || '127.0.0.1';
export const port = process.env.PORT ? parseInt(process.env.PORT, 10) : 4000;
|
niklaskorz/nkchat | packages/server/src/scalars/index.ts | <filename>packages/server/src/scalars/index.ts
export * from './ObjectIDScalar';
|
niklaskorz/nkchat | packages/server/src/sessions.ts | import Redis from 'ioredis';
import { ObjectID } from 'mongodb';
import { getMongoRepository } from 'typeorm';
import { redisHost } from './config';
import { SESSION_EXPIRY_SECONDS } from './constants';
import { User } from './models';
const redis = new Redis(`redis://${redisHost}`);
export const loadSession = async (id: string): Promise<User | null> => {
const userId = await redis.get(`session:${id}`);
if (!userId) {
return null;
}
const user = await getMongoRepository(User).findOne(userId);
if (!user) {
return null;
}
await redis.expire(id, SESSION_EXPIRY_SECONDS);
return user;
};
export const createSession = async (userId: ObjectID): Promise<string> => {
const id = new ObjectID().toHexString();
await redis.setex(
`session:${id}`,
SESSION_EXPIRY_SECONDS,
userId.toHexString(),
);
return id;
};
export const removeSession = async (id: string): Promise<void> => {
await redis.del(`session:${id}`);
};
|
niklaskorz/nkchat | packages/client/src/components/molecules/SideBar.tsx | import * as colors from 'colors';
import React from 'react';
import styled from 'styled-components';
const Section = styled.section`
background: ${colors.darkPrimary};
color: #fff;
min-width: 0;
flex: 0 0 250px;
display: flex;
flex-direction: column;
`;
const Header = styled.header`
padding: 15px;
flex-shrink: 0;
border-top: 2px solid transparent;
border-bottom: 2px solid ${colors.darkSecondary};
`;
const HeaderTitle = styled.h2`
font-size: 1em;
margin: 0;
font-weight: normal;
`;
interface Props {
title: string;
}
const SideBar: React.SFC<Props> = ({ title, children }) => (
<Section>
<Header>
<HeaderTitle>{title}</HeaderTitle>
</Header>
{children}
</Section>
);
export default SideBar;
|
niklaskorz/nkchat | packages/server/src/resolvers/RoomResolver.ts | import { ObjectID } from 'mongodb';
import {
Arg,
Ctx,
Field,
FieldResolver,
InputType,
Mutation,
Publisher,
PubSub,
Query,
Resolver,
Root,
Subscription,
} from 'type-graphql';
import { MongoRepository } from 'typeorm';
import { InjectRepository } from 'typeorm-typedi-extensions';
import Context from '../Context';
import { Message, Room, User, userIsMemberOfRoom } from '../models';
import { SubscriptionType } from '../subscriptions';
@InputType()
class CreateRoomInput {
@Field()
name: string;
}
@InputType()
class UpdateRoomInput {
@Field(type => ObjectID)
roomId: ObjectID;
@Field()
name: string;
}
@InputType()
class JoinRoomInput {
@Field(type => ObjectID)
roomId: ObjectID;
}
interface RoomWasUpdatedPayload {
room: Room;
}
interface UserJoinedRoomPayload {
roomId: ObjectID;
user: User;
}
@Resolver(of => Room)
export class RoomResolver {
constructor(
@InjectRepository(Message)
private messageRepository: MongoRepository<Message>,
@InjectRepository(Room) private roomRepository: MongoRepository<Room>,
@InjectRepository(User) private userRepository: MongoRepository<User>,
) {}
@FieldResolver(type => User)
// @ManyToOne(type => User, user => user.ownedRooms)
async owner(@Root() room: Room): Promise<User> {
return this.userRepository.findOneOrFail(room.ownerId);
}
@FieldResolver(type => [User])
// @Index()
// @ManyToMany(type => User, user => user.rooms)
// @JoinTable()
async members(@Root() room: Room): Promise<User[]> {
return await this.userRepository.findByIds(room.memberIds);
}
@FieldResolver(type => [Message])
// @OneToMany(type => Message, message => message.room)
async messages(@Root() room: Room, @Ctx() ctx: Context): Promise<Message[]> {
const viewer = ctx.state.viewer;
if (!viewer) {
throw new Error('Authentication required');
}
const viewerIsMember = userIsMemberOfRoom(viewer, room);
if (!viewerIsMember) {
throw new Error("Only members of a room can read the room's messages");
}
return await this.messageRepository.find({ roomId: room.id });
}
@FieldResolver()
viewerIsOwner(@Root() room: Room, @Ctx() ctx: Context): boolean {
const viewer = ctx.state.viewer;
if (!viewer) {
return false;
}
return room.ownerId.equals(viewer.id);
}
@FieldResolver()
viewerIsMember(@Root() room: Room, @Ctx() ctx: Context): boolean {
const viewer = ctx.state.viewer;
if (!viewer) {
return false;
}
return userIsMemberOfRoom(viewer, room);
}
@Query(returns => Room, {
description:
'Queries a room by id, returns the room if found, null otherwise',
nullable: true,
})
async room(@Arg('id', type => ObjectID) id: ObjectID): Promise<Room | null> {
return (await this.roomRepository.findOne(id)) || null;
}
@Mutation(returns => Room, {
description: 'Creates a new room and returns the created room',
})
async createRoom(
@Arg('input') input: CreateRoomInput,
@Ctx() ctx: Context,
): Promise<Room> {
const viewer = ctx.state.viewer;
if (!viewer) {
throw new Error('Authentication required');
}
const room = new Room();
room.name = input.name;
room.ownerId = viewer.id;
room.memberIds = [viewer.id];
return await this.roomRepository.save(room);
}
@Mutation(returns => Room, {
description: 'Updates a room and returns the updated room',
})
async updateRoom(
@Arg('input') input: UpdateRoomInput,
@Ctx() ctx: Context,
@PubSub(SubscriptionType.RoomWasUpdated)
publish: Publisher<RoomWasUpdatedPayload>,
): Promise<Room> {
const viewer = ctx.state.viewer;
if (!viewer) {
throw new Error('Authentication required');
}
const room = await this.roomRepository.findOne(input.roomId);
if (!room) {
throw new Error('Room could not be found');
}
if (!room.ownerId.equals(viewer.id)) {
throw new Error("Only a room's owner can update a room");
}
room.name = input.name;
await this.roomRepository.save(room);
publish({ room });
return room;
}
@Mutation(returns => Room, {
description:
'Makes the active user join a room and returns the joined room',
})
async joinRoom(
@Arg('input') input: JoinRoomInput,
@Ctx() ctx: Context,
@PubSub(SubscriptionType.UserJoinedRoom)
publish: Publisher<UserJoinedRoomPayload>,
): Promise<Room> {
const viewer = ctx.state.viewer;
if (!viewer) {
throw new Error('Authentication required');
}
const room = await this.roomRepository.findOne(input.roomId);
if (!room) {
throw new Error('Room could not be found');
}
room.memberIds.push(viewer.id);
await this.roomRepository.save(room);
publish({
roomId: room.id,
user: viewer,
});
return room;
}
@Subscription(returns => Room, {
description:
'Notifies when the specified room has been updated and returns the updated room',
topics: SubscriptionType.RoomWasUpdated,
filter: ({ payload, args }) => payload.room.id.equals(args.roomId),
})
roomWasUpdated(
@Root() payload: RoomWasUpdatedPayload,
@Arg('roomId', type => ObjectID) roomId: ObjectID,
): Room {
return payload.room;
}
@Subscription(returns => User, {
description:
'Notifies when a user has joined the specified room and returns the joined user',
topics: SubscriptionType.UserJoinedRoom,
filter: ({ payload, args }) => payload.roomId.equals(args.roomId),
})
userJoinedRoom(
@Root() payload: UserJoinedRoomPayload,
@Arg('roomId', type => ObjectID) roomId: ObjectID,
): User {
return payload.user;
}
}
|
niklaskorz/nkchat | packages/server/src/resolvers/index.ts | <gh_stars>10-100
export * from './MessageResolver';
export * from './RoomResolver';
export * from './UserResolver';
|
niklaskorz/nkchat | packages/server/src/schema.ts | import { ObjectID } from 'mongodb';
import { buildSchema } from 'type-graphql';
import { MessageResolver, RoomResolver, UserResolver } from './resolvers';
import { ObjectIDScalar } from './scalars';
import { pubSub } from './subscriptions';
const getSchema = () =>
buildSchema({
resolvers: [MessageResolver, RoomResolver, UserResolver],
scalarsMap: [{ type: ObjectID, scalar: ObjectIDScalar }],
pubSub,
});
export default getSchema;
|
niklaskorz/nkchat | packages/client/src/formatError.ts | <reponame>niklaskorz/nkchat
const trimLeft = 'GraphQL error: ';
export default (message: string): string => {
if (message.startsWith(trimLeft)) {
return message.slice(trimLeft.length);
}
return message;
};
|
niklaskorz/nkchat | packages/client/src/components/atoms/ErrorMessage.ts | <reponame>niklaskorz/nkchat<filename>packages/client/src/components/atoms/ErrorMessage.ts
import * as colors from 'colors';
import styled from 'styled-components';
export default styled.div`
border-radius: 2px;
padding: 15px;
margin-bottom: 20px;
background: ${colors.error};
color: #fff;
`;
|
niklaskorz/nkchat | packages/client/src/components/molecules/NothingHere.tsx | <reponame>niklaskorz/nkchat
import React from 'react';
import CenteredContainer from '../atoms/CenteredContainer';
export default class NothingHere extends React.Component {
render() {
return (
<CenteredContainer>
<p>Welcome! Join a room or create a new one to get started.</p>
</CenteredContainer>
);
}
}
|
niklaskorz/nkchat | packages/server/src/models/User.ts | <reponame>niklaskorz/nkchat<gh_stars>10-100
import { ObjectID } from 'mongodb';
import { Field, ObjectType } from 'type-graphql';
import { Column, Entity, Index, ObjectIdColumn } from 'typeorm';
@ObjectType({
description: 'A user is a user, not much left to say here',
})
@Entity()
export class User {
@Field(type => ObjectID)
@ObjectIdColumn()
readonly id: ObjectID;
@Field()
@Index({ unique: true })
@Column()
name: string;
// Do not expose this as a field!
@Column()
password: string;
@Field()
createdAt(): Date {
return this.id.getTimestamp();
}
}
|
niklaskorz/nkchat | packages/client/src/components/molecules/RoomInfo.tsx | <reponame>niklaskorz/nkchat
import * as colors from 'colors';
import React from 'react';
import styled from 'styled-components';
import SideBar from './SideBar';
const SubTitle = styled.h3`
font-size: 0.9em;
margin: 0;
font-weight: normal;
margin-top: 10px;
padding: 0 15px;
`;
const RoomIdText = styled.input`
appearance: none;
border: none;
border-radius: 2px;
padding: 5px;
margin: 10px 15px;
color: ${colors.primaryText};
background: ${colors.secondary};
font-size: 0.8em;
text-align: center;
`;
const List = styled.ul`
display: block;
margin: 0;
padding: 10px 0;
overflow: auto;
flex: 1;
font-size: 0.8em;
`;
const Item = styled.li`
display: block;
padding: 10px 15px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
color: ${colors.darkSecondaryText};
`;
interface User {
id: string;
name: string;
}
interface Room {
id: string;
members: User[];
}
interface Props {
room: Room;
}
const selectOnFocus: React.FocusEventHandler<HTMLInputElement> = e => {
// Work around a bug in Microsoft Edge that prevents selecting text
// inside the focus event handler:
// https://stackoverflow.com/questions/38487059/selecting-all-content-of-text-input-on-focus-in-microsoft-edge
const t = e.currentTarget;
setTimeout(() => t.select(), 0);
};
export default class RoomInfo extends React.Component<Props> {
render() {
const { room } = this.props;
return (
<SideBar title="About this room">
<SubTitle>Room ID</SubTitle>
<RoomIdText
type="text"
readOnly
onFocus={selectOnFocus}
value={room.id}
/>
<SubTitle>Members ({room.members.length})</SubTitle>
<List>
{room.members.map(user => (
<Item key={user.id}>{user.name}</Item>
))}
</List>
</SideBar>
);
}
}
|
niklaskorz/nkchat | packages/server/src/subscriptions.ts | import * as config from './config';
import NatsPubSub from './nats-subscriptions/NatsPubSub';
export enum SubscriptionType {
MessageWasSent = 'MessageWasSent',
RoomWasUpdated = 'RoomWasUpdated',
UserJoinedRoom = 'UserJoinedRoom',
}
export const pubSub = new NatsPubSub({
url: `nats://${config.natsHost}:4222`,
});
|
niklaskorz/nkchat | packages/server/src/resolvers/UserResolver.ts | <reponame>niklaskorz/nkchat<filename>packages/server/src/resolvers/UserResolver.ts<gh_stars>10-100
import * as bcrypt from 'bcrypt';
import { ObjectID } from 'mongodb';
import {
Arg,
Ctx,
Field,
FieldResolver,
InputType,
Mutation,
Query,
Resolver,
Root,
} from 'type-graphql';
import { MongoRepository } from 'typeorm';
import { InjectRepository } from 'typeorm-typedi-extensions';
import { SESSION_EXPIRY_MILLISECONDS } from '../constants';
import Context from '../Context';
import { Message, Room, User } from '../models';
import { createSession, removeSession } from '../sessions';
@InputType()
class RegisterInput {
@Field()
name: string;
@Field()
password: string;
}
@InputType()
class LoginInput {
@Field()
name: string;
@Field()
password: string;
}
@Resolver(of => User)
export class UserResolver {
constructor(
@InjectRepository(Message)
private messageRepository: MongoRepository<Message>,
@InjectRepository(Room)
private roomRepository: MongoRepository<Room>,
@InjectRepository(User)
private userRepository: MongoRepository<User>,
) {}
@FieldResolver(type => [Room])
// @OneToMany(type => Room, room => room.owner)
async ownedRooms(@Root() user: User): Promise<Room[]> {
return await this.roomRepository.find({ ownerId: user.id });
}
@FieldResolver(type => [Room])
// @ManyToMany(type => Room)
// @JoinTable()
async rooms(@Root() user: User): Promise<Room[]> {
return await this.roomRepository.find({ where: { memberIds: user.id } });
}
@FieldResolver(type => [Message])
// @OneToMany(type => Message, message => message.room)
async messages(@Root() user: User): Promise<Message[]> {
return await this.messageRepository.find({ authorId: user.id });
}
@FieldResolver()
isViewer(@Root() user: User, @Ctx() ctx: Context): boolean {
const viewer = ctx.state.viewer;
if (!viewer) {
return false;
}
return user.id.equals(viewer.id);
}
@Query(returns => User, {
description:
'Returns the authenticated user if the querying user is authenticated, null otherwise',
nullable: true,
})
viewer(@Ctx() ctx: Context): User | null {
return ctx.state.viewer || null;
}
@Mutation(returns => User, {
description:
'Creates a new user and returns a login session for the created user',
})
async register(
@Arg('input') input: RegisterInput,
@Ctx() ctx: Context,
): Promise<User> {
const user = new User();
user.name = input.name;
user.password = await bcrypt.hash(input.password, 10);
await this.userRepository.save(user);
const sessionId = await createSession(user.id);
ctx.state.sessionId = sessionId;
ctx.state.viewer = user;
if (ctx.cookies) {
ctx.cookies.set('session', sessionId, {
overwrite: true,
maxAge: SESSION_EXPIRY_MILLISECONDS,
});
}
return user;
}
@Mutation(returns => User, {
description: 'Creates and returns a login session for the specified user',
})
async login(
@Arg('input') input: LoginInput,
@Ctx() ctx: Context,
): Promise<User> {
const user = await this.userRepository.findOne({ name: input.name });
if (!user) {
throw new Error('User not found');
}
const isPasswordCorrect = await bcrypt.compare(
input.password,
user.password,
);
if (!isPasswordCorrect) {
throw new Error('Password is incorrect');
}
const sessionId = await createSession(user.id);
ctx.state.sessionId = sessionId;
ctx.state.viewer = user;
if (ctx.cookies) {
ctx.cookies.set('session', sessionId, {
overwrite: true,
maxAge: SESSION_EXPIRY_MILLISECONDS,
});
}
return user;
}
@Mutation(returns => ObjectID, {
description:
'Invalidates the active user session and returns the session id',
})
async logout(@Ctx() ctx: Context): Promise<string> {
const sessionId = ctx.state.sessionId;
if (!sessionId) {
throw new Error('Authentication required');
}
await removeSession(sessionId);
ctx.state.sessionId = undefined;
ctx.state.viewer = undefined;
if (ctx.cookies) {
ctx.cookies.set('session', undefined, { overwrite: true }); // Clear session
}
return sessionId;
}
}
|
niklaskorz/nkchat | packages/server/src/scalars/ObjectIDScalar.ts | import { GraphQLScalarType, Kind, ValueNode } from 'graphql';
import { ObjectID } from 'mongodb';
export const ObjectIDScalar = new GraphQLScalarType({
name: 'ObjectID',
description: 'Object id scalar type',
parseValue(value: string) {
return ObjectID.createFromHexString(value);
},
parseLiteral(node: ValueNode) {
if (node.kind !== Kind.STRING) {
throw new Error('Cannot parse non-string as ObjectID');
}
return ObjectID.createFromHexString(node.value);
},
serialize(value: ObjectID) {
return value.toHexString();
},
});
|
niklaskorz/nkchat | packages/client/src/apollo.ts | <gh_stars>10-100
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloClient } from 'apollo-client';
import { Operation, split } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
const base = '/graphql';
const wsProtocol = location.protocol.replace('http', 'ws');
const wsBase = wsProtocol + '//' + location.host + base;
const httpLink = new HttpLink({
uri: base,
credentials: 'same-origin',
});
const wsLink = new WebSocketLink({
uri: wsBase,
options: {
reconnect: true,
},
});
const isSubscription = ({ query }: Operation) => {
const node = getMainDefinition(query);
return (
node.kind === 'OperationDefinition' && node.operation === 'subscription'
);
};
const link = split(isSubscription, wsLink, httpLink);
const cache = new InMemoryCache();
const client = new ApolloClient({
link,
cache,
});
export default client;
|
niklaskorz/nkchat | packages/client/src/components/App.tsx | <gh_stars>10-100
import React from 'react';
import { ApolloProvider } from 'react-apollo';
import { Helmet } from 'react-helmet';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import apolloClient from '../apollo';
import ChatPage from './pages/ChatPage';
import LoginPage from './pages/LoginPage';
class App extends React.Component {
render() {
return (
<div>
<Helmet titleTemplate="%s - nkchat" defaultTitle="nkchat" />
<ApolloProvider client={apolloClient}>
<BrowserRouter>
<Switch>
<Route exact path="/" component={ChatPage} />
<Route exact path="/rooms/:roomId" component={ChatPage} />
<Route exact path="/login" component={LoginPage} />
<Route exact path="/register" component={LoginPage} />
</Switch>
</BrowserRouter>
</ApolloProvider>
</div>
);
}
}
export default App;
|
niklaskorz/nkchat | packages/server/src/models/Message.ts | <filename>packages/server/src/models/Message.ts
import { ObjectID } from 'mongodb';
import { Field, ObjectType, registerEnumType } from 'type-graphql';
import { Column, Entity, ObjectIdColumn } from 'typeorm';
export enum EmbedType {
Youtube = 'YOUTUBE',
Alugha = 'ALUGHA',
Image = 'IMAGE',
}
registerEnumType(EmbedType, {
name: 'EmbedType',
});
@ObjectType()
export class Embed {
@Field(type => EmbedType)
@Column()
type: EmbedType;
@Field()
@Column()
src: string;
}
@ObjectType()
@Entity()
export class Message {
@Field(type => ObjectID)
@ObjectIdColumn()
readonly id: ObjectID;
@Field()
@Column()
content: string;
@Field(type => ObjectID)
@Column()
authorId: ObjectID;
@Field(type => ObjectID)
@Column()
roomId: ObjectID;
@Field(type => [Embed])
@Column(type => Embed)
embeds: Embed[];
@Field()
createdAt(): Date {
return this.id.getTimestamp();
}
}
|
niklaskorz/nkchat | packages/server/src/nats-subscriptions/NatsPubSub.ts | import { PubSubEngine } from 'graphql-subscriptions';
import { ObjectID } from 'mongodb';
import { Client, ClientOpts, connect } from 'nats';
import PubSubAsyncIterator from './PubSubAsyncIterator';
const reviver = (key: string, value: any) => {
if (ObjectID.isValid(value)) {
return ObjectID.createFromHexString(value);
}
return value;
};
export default class NatsPubSub implements PubSubEngine {
protected client: Client;
constructor(opts: ClientOpts) {
this.client = connect(opts);
}
public async publish(triggerName: string, payload: any): Promise<void> {
this.client.publish(triggerName, JSON.stringify(payload));
}
public async subscribe(
triggerName: string,
onMessage: (payload: any) => void,
): Promise<number> {
return this.client.subscribe(triggerName, (msg: string) =>
onMessage(JSON.parse(msg, reviver)),
);
}
public unsubscribe(subId: number) {
this.client.unsubscribe(subId);
}
public asyncIterator<T>(triggers: string | string[]): AsyncIterator<T> {
return new PubSubAsyncIterator<T>(this, triggers);
}
}
|
niklaskorz/nkchat | packages/server/src/index.ts | <reponame>niklaskorz/nkchat
import 'reflect-metadata';
import * as typegraphql from 'type-graphql';
import { Container } from 'typedi';
import * as typeorm from 'typeorm';
import winston from 'winston';
import * as config from './config';
import { Message, Room, User } from './models';
import startServer from './startServer';
typeorm.useContainer(Container);
typegraphql.useContainer(Container);
const console = new winston.transports.Console({
format: winston.format.simple(),
});
winston.add(console);
const createDatabaseConnection = () =>
typeorm.createConnection({
type: 'mongodb',
url: `mongodb://${config.mongodbHost}/nkchat`,
entities: [Message, Room, User],
synchronize: true,
useNewUrlParser: true,
});
createDatabaseConnection()
.then(() => startServer(config.port))
.then(() => {
winston.info(`GraphQL API at http://localhost:${config.port}/graphql`);
})
.catch(err => winston.error(err.stack));
|
niklaskorz/nkchat | packages/client/src/components/pages/ChatPage.tsx | <filename>packages/client/src/components/pages/ChatPage.tsx
import { ApolloQueryResult } from 'apollo-client';
import gql from 'graphql-tag';
import { History, Location } from 'history';
import React from 'react';
import { ChildProps, compose, graphql, MutationFunc } from 'react-apollo';
import { Redirect } from 'react-router-dom';
import styled from 'styled-components';
import client from '../../apollo';
import Loading from '../molecules/Loading';
import NothingHere from '../molecules/NothingHere';
import RoomList, { Room } from '../molecules/RoomList';
import Chat from '../organisms/Chat';
const Container = styled.div`
display: flex;
width: 100vw;
height: 100vh;
overflow: hidden;
`;
interface User {
id: string;
name: string;
rooms: Room[];
}
interface Response {
viewer: User;
}
interface Props {
history: History;
location: Location;
match: {
params: {
roomId?: string;
};
};
createRoom: MutationFunc<{ createRoom: Room }, { name: string }>;
joinRoom: MutationFunc<{ joinRoom: Room }, { roomId: string }>;
logout: MutationFunc<{ logout: string }, {}>;
}
const ChatPageQuery = gql`
query ChatPageQuery {
viewer {
id
name
rooms {
id
name
}
}
}
`;
class ChatPage extends React.Component<ChildProps<Props, Response>> {
createRoom = async (name: string) => {
const res = await this.props.createRoom({
variables: { name },
update: (store, result: ApolloQueryResult<{ createRoom: Room }>) => {
const data = store.readQuery<Response>({ query: ChatPageQuery });
if (data) {
data.viewer.rooms.push(result.data.createRoom);
store.writeQuery({ query: ChatPageQuery, data });
}
},
});
// Open the created room
const roomId = res.data.createRoom.id;
this.props.history.push(`/rooms/${roomId}`);
};
joinRoom = async (roomId: string) => {
await this.props.joinRoom({
variables: { roomId },
update: (store, result: ApolloQueryResult<{ joinRoom: Room }>) => {
const data = store.readQuery<Response>({ query: ChatPageQuery });
if (data) {
data.viewer.rooms.push(result.data.joinRoom);
store.writeQuery({ query: ChatPageQuery, data });
}
},
});
// Open the joined room
this.props.history.push(`/rooms/${roomId}`);
};
logout = async () => {
await this.props.logout();
await client.resetStore();
};
render() {
if (!this.props.data) {
return null;
}
const { loading, error, viewer } = this.props.data;
if (loading) {
return <Loading />;
}
if (error) {
return error.message;
}
if (!viewer) {
return (
<Redirect
to={{
pathname: '/login',
state: {
from: this.props.location,
},
}}
/>
);
}
const { roomId } = this.props.match.params;
return (
<Container>
<RoomList
rooms={viewer.rooms}
viewerName={viewer.name}
activeRoomId={roomId}
onCreate={this.createRoom}
onJoin={this.joinRoom}
onLogout={this.logout}
/>
{roomId ? <Chat roomId={roomId} /> : <NothingHere />}
</Container>
);
}
}
const withData = graphql<Response>(ChatPageQuery);
const withCreateRoomMutation = graphql(
gql`
mutation CreateRoom($name: String!) {
createRoom(input: { name: $name }) {
id
name
}
}
`,
{ name: 'createRoom' },
);
const withJoinRoomMutation = graphql(
gql`
mutation JoinRoom($roomId: ObjectID!) {
joinRoom(input: { roomId: $roomId }) {
id
name
}
}
`,
{ name: 'joinRoom' },
);
const withLogoutMutation = graphql(
gql`
mutation LogoutMutation {
logout
}
`,
{ name: 'logout' },
);
export default compose(
withData,
withCreateRoomMutation,
withJoinRoomMutation,
withLogoutMutation,
)(ChatPage);
|
niklaskorz/nkchat | packages/server/src/startServer.ts | import { ApolloServer } from 'apollo-server-koa';
import Cookies from 'cookies';
import { createServer, ServerResponse } from 'http';
import Koa from 'koa';
import { SESSION_EXPIRY_MILLISECONDS } from './constants';
import Context, { State } from './Context';
import getSchema from './schema';
import { loadSession } from './sessions';
const loadState = async (sessionId?: string | null): Promise<State> => {
if (!sessionId) {
return {};
}
const viewer = await loadSession(sessionId);
if (!viewer) {
return {};
}
return { sessionId, viewer };
};
type ContextParameters =
| { ctx: Context; connection: undefined }
| { ctx: undefined; connection: { context: Context } };
const startServer = async (port: number) => {
const app = new Koa();
app.proxy = true;
app.use(async (ctx, next) => {
const sessionId = ctx.cookies.get('session');
const state = await loadState(sessionId);
if (state.viewer) {
// Refresh cookie
ctx.cookies.set('session', sessionId, {
overwrite: true,
maxAge: SESSION_EXPIRY_MILLISECONDS,
});
}
ctx.state = state;
await next();
});
const apolloServer = new ApolloServer({
schema: await getSchema(),
context: async (params: ContextParameters): Promise<Context> => {
return params.ctx || params.connection.context;
},
subscriptions: {
onConnect: async (
connectionParams,
webSocket,
connectionContext,
): Promise<Context> => {
const cookies = new Cookies(
connectionContext.request,
new ServerResponse(connectionContext.request), // Dummy object
);
const sessionId = cookies.get('sessionId');
return {
state: await loadState(sessionId),
};
},
},
});
apolloServer.applyMiddleware({
app,
cors: false,
});
const server = createServer(app.callback());
apolloServer.installSubscriptionHandlers(server);
return await new Promise(resolve => server.listen(port, resolve));
};
export default startServer;
|
react-epic/deviation | src/StoreInjector.ts | import { IProviderToStoreMap } from './Injectable'
import { PureDeviation } from './PureDeviation'
import { Store } from './Store'
interface IStoreInjectorProps {
providers: IProviderToStoreMap
}
export class StoreInjector<S> extends Store<
IStoreInjectorProps,
S
> {
constructor(deviation: PureDeviation) {
super({ providers: deviation.state.providers })
}
}
|
react-epic/deviation | src/Store.ts | import { isFunction } from 'lodash'
import { Subject } from 'rxjs'
import { IProviderToStoreMap } from './Injectable'
export const notifier: unique symbol = Symbol('notifier')
export class Store<P = {}, S extends Object = {}> {
public props: Readonly<P>
public state: S;
public [notifier]: Subject<S> = new Subject()
constructor(props: P) {
this.props = props
this.state = ({} as any) as S
}
public static updateProviders?(
store: Store<any, any>,
providers: IProviderToStoreMap
): void
public setState(state: S | ((prevState: S) => S)): void {
const prevState = this.state
if (isFunction(state)) {
this.state = state(this.state)
} else if (state) {
this.state = {
...(this.state as object),
...(state as object)
} as S
} else {
return
}
this[notifier].next(prevState)
}
public storeDidMount?(): void
public storeWillUnmount?(): void
}
|
react-epic/deviation | src/ConstructorType.ts | // tslint:disable-next-line interface-name
export interface AnyConstructorType<T> {
new (...args: any[]): T
}
// tslint:disable-next-line interface-name
export interface ConstructorType<
T extends { new (...args: any[]): any }
> {
new (...args: ConstructorParameters<T>): T
}
|