repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
adinvadim/vuex-orm-next
test/feature/repository/updates_update_composite_key.spec.ts
import { createStore, fillState, assertState } from 'test/Helpers' import { Model, Attr, Str, Num } from '@/index' describe('feature/repository/updates_update_composite_key', () => { class User extends Model { static entity = 'users' static primaryKey = ['idA', 'idB'] @Attr() idA!: any @Attr() idB!: any @Str('') name!: string @Num(0) age!: number } it('update records with composite key', async () => { const store = createStore() fillState(store, { users: { '[1,2]': { idA: 1, idB: 2, name: '<NAME>', age: 40 }, '[2,1]': { idA: 2, idB: 1, name: '<NAME>', age: 30 } } }) await store.$repo(User).update({ idA: 2, idB: 1, age: 50 }) assertState(store, { users: { '[1,2]': { idA: 1, idB: 2, name: '<NAME>', age: 40 }, '[2,1]': { idA: 2, idB: 1, name: '<NAME>', age: 50 } } }) }) it('throws if the one of the composite key is missing', async () => { expect.assertions(1) const store = createStore() fillState(store, { users: { '[1,2]': { idA: 1, idB: 2, name: '<NAME>', age: 40 }, '[2,1]': { idA: 2, idB: 1, name: '<NAME>', age: 30 } } }) try { await store.$repo(User).update({ idA: 2, age: 50 }) } catch (e) { expect(e).toBeInstanceOf(Error) } }) })
adinvadim/vuex-orm-next
test/feature/repository/save.spec.ts
import { createStore, fillState, assertState } from 'test/Helpers' import { Model, Str, Num } from '@/index' describe('feature/repository/save', () => { class User extends Model { static entity = 'users' @Num(0) id!: number @Str('') name!: string @Num(0) age!: number } it('does nothing when passing in an empty array', () => { const store = createStore() store.$repo(User).save([]) assertState(store, { users: {} }) }) it('saves a model to the store', () => { const store = createStore() store.$repo(User).save({ id: 1, name: '<NAME>', age: 30 }) assertState(store, { users: { 1: { id: 1, name: '<NAME>', age: 30 } } }) }) it('saves multiple models to the store', () => { const store = createStore() store.$repo(User).save([ { id: 1, name: '<NAME>', age: 30 }, { id: 2, name: '<NAME>', age: 20 } ]) assertState(store, { users: { 1: { id: 1, name: '<NAME>', age: 30 }, 2: { id: 2, name: '<NAME>', age: 20 } } }) }) it('updates existing model if it exists when saving a model', () => { const store = createStore() fillState(store, { users: { 1: { id: 1, name: '<NAME>', age: 30 } } }) store.$repo(User).save({ id: 1, age: 20 }) assertState(store, { users: { 1: { id: 1, name: '<NAME>', age: 20 } } }) }) it('updates existing model if it exists when saving multiple model', () => { const store = createStore() fillState(store, { users: { 1: { id: 1, name: '<NAME>', age: 30 } } }) store.$repo(User).save([ { id: 1, age: 20 }, { id: 2, name: '<NAME>', age: 10 } ]) assertState(store, { users: { 1: { id: 1, name: '<NAME>', age: 20 }, 2: { id: 2, name: '<NAME>', age: 10 } } }) }) it('returns normalized schema when saving a model', () => { const store = createStore() const schema = store.$repo(User).save({ id: 1, name: '<NAME>', age: 30 }) expect(schema).toEqual({ __id: '1', id: 1, name: '<NAME>', age: 30 }) }) it('returns normalized schema when saving multiple models', () => { const store = createStore() const schema = store.$repo(User).save([ { id: 1, name: '<NAME>', age: 30 }, { id: 2, name: '<NAME>', age: 20 } ]) expect(schema).toEqual([ { __id: '1', id: 1, name: '<NAME>', age: 30 }, { __id: '2', id: 2, name: '<NAME>', age: 20 } ]) }) })
adinvadim/vuex-orm-next
test/feature/repository/deletes_delete.spec.ts
import { createStore, fillState, assertState } from 'test/Helpers' import { Model, Attr, Str } from '@/index' describe('feature/repository/deletes_delete', () => { class User extends Model { static entity = 'users' @Attr() id!: any @Str('') name!: string } it('deletes a record specified by the where clause', async () => { const store = createStore() fillState(store, { users: { 1: { id: 1, name: '<NAME>' }, 2: { id: 2, name: '<NAME>' }, 3: { id: 3, name: '<NAME>' } } }) await store.$repo(User).where('name', '<NAME>').delete() assertState(store, { users: { 1: { id: 1, name: '<NAME>' }, 3: { id: 3, name: '<NAME>' } } }) }) it('can delete multiple records specified by the where clause', async () => { const store = createStore() fillState(store, { users: { 1: { id: 1, name: '<NAME>' }, 2: { id: 2, name: '<NAME>' }, 3: { id: 3, name: '<NAME>' } } }) await store .$repo(User) .where('name', '<NAME>') .orWhere('name', '<NAME>') .delete() assertState(store, { users: { 1: { id: 1, name: '<NAME>' } } }) }) })
adinvadim/vuex-orm-next
test/feature/relations/has_many_insert.spec.ts
import { createStore, assertState } from 'test/Helpers' import { Model, Attr, Str, HasMany } from '@/index' describe('feature/relations/has_many_insert', () => { class User extends Model { static entity = 'users' @Attr() id!: number @Str('') name!: string @HasMany(() => Post, 'userId') posts!: Post[] } class Post extends Model { static entity = 'posts' @Attr() id!: number @Attr() userId!: number @Str('') title!: string } it('inserts a record to the store with "has many" relation', async () => { const store = createStore() await store.$repo(User).insert({ id: 1, name: '<NAME>', posts: [ { id: 1, userId: 1, title: 'Title 01' }, { id: 2, userId: 1, title: 'Title 02' } ] }) assertState(store, { users: { 1: { id: 1, name: '<NAME>' } }, posts: { 1: { id: 1, userId: 1, title: 'Title 01' }, 2: { id: 2, userId: 1, title: 'Title 02' } } }) }) it('generates missing foreign key', async () => { const store = createStore() await store.$repo(User).insert({ id: 1, name: '<NAME>', posts: [ { id: 1, title: 'Title 01' }, { id: 2, title: 'Title 02' } ] }) assertState(store, { users: { 1: { id: 1, name: '<NAME>' } }, posts: { 1: { id: 1, userId: 1, title: 'Title 01' }, 2: { id: 2, userId: 1, title: 'Title 02' } } }) }) it('can insert a record with missing relational key', async () => { const store = createStore() await store.$repo(User).insert({ id: 1, name: '<NAME>' }) assertState(store, { users: { 1: { id: 1, name: '<NAME>' } }, posts: {} }) }) })
adinvadim/vuex-orm-next
test/feature/repository/inserts_new.spec.ts
<reponame>adinvadim/vuex-orm-next<gh_stars>0 import { createStore, assertState, mockUid } from 'test/Helpers' import { Model, Str, Num, Bool, Uid, Attr } from '@/index' describe('feature/repository/inserts_new', () => { it('inserts with a models default values', async () => { class User extends Model { static entity = 'users' @Uid() id!: string @Str('<NAME>') name!: string @Num(21) age!: number @Bool(true) active!: boolean } mockUid(['uid1']) const store = createStore() await store.$repo(User).new() assertState(store, { users: { uid1: { id: 'uid1', name: '<NAME>', age: 21, active: true } } }) }) it('throws if a primary key is not capable of being generated', async () => { class User extends Model { static entity = 'users' @Attr() id!: any @Str('<NAME>') name!: string } const store = createStore() await expect(() => store.$repo(User).new()).rejects.toThrow() }) })
adinvadim/vuex-orm-next
test/feature/repository/retrieves_revive.spec.ts
<reponame>adinvadim/vuex-orm-next<filename>test/feature/repository/retrieves_revive.spec.ts import { createStore, fillState } from 'test/Helpers' import { Model, Num, Str } from '@/index' describe('feature/repository/retrieves_revive', () => { class User extends Model { static entity = 'users' @Num(0) id!: number @Str('') name!: string } it('retrieves a model from the store by the given schema', () => { const store = createStore() fillState(store, { users: { 1: { id: 1, name: '<NAME>' }, 2: { id: 2, name: '<NAME>' }, 3: { id: 3, name: '<NAME>' } } }) const schema = { __id: 2 } const user = store.$repo(User).revive(schema)! expect(user).toBeInstanceOf(User) expect(user.id).toBe(2) }) it('returns null if result can not be found when passing object schema', () => { const store = createStore() fillState(store, { users: { 1: { id: 1, name: '<NAME>' }, 2: { id: 2, name: '<NAME>' }, 3: { id: 3, name: '<NAME>' } } }) // Test missing id in the store. expect(store.$repo(User).revive({ __id: 4 })).toBe(null) // Test missing id in the schema. expect(store.$repo(User).revive({})).toBe(null) }) it('retrieves multiple models from the store by the given schema', () => { const store = createStore() fillState(store, { users: { 1: { id: 1, name: '<NAME>' }, 2: { id: 2, name: '<NAME>' }, 3: { id: 3, name: '<NAME>' } } }) const schema = [{ __id: 3 }, { __id: 1 }] const users = store.$repo(User).revive(schema) expect(users.length).toBe(2) expect(users[0].id).toBe(3) expect(users[1].id).toBe(1) }) })
adinvadim/vuex-orm-next
test/feature/repository/inserts_replace.spec.ts
<reponame>adinvadim/vuex-orm-next<gh_stars>0 import { createStore, fillState, assertState } from 'test/Helpers' import { Model, Attr, Str } from '@/index' describe('feature/repository/inserts_replace', () => { class User extends Model { static entity = 'users' @Attr() id!: any @Str('') name!: string } it('inserts a record in the store', async () => { const store = createStore() await store.$repo(User).replace({ id: 1, name: '<NAME>' }) assertState(store, { users: { 1: { id: 1, name: '<NAME>' } } }) }) it('inserts multiple records in the store', async () => { const store = createStore() await store.$repo(User).replace([ { id: 1, name: '<NAME>' }, { id: 2, name: '<NAME>' } ]) assertState(store, { users: { 1: { id: 1, name: '<NAME>' }, 2: { id: 2, name: '<NAME>' } } }) }) it('replaces existing records', async () => { const store = createStore() fillState(store, { users: { 1: { id: 1, name: '<NAME>' }, 2: { id: 2, name: '<NAME>' } } }) await store.$repo(User).replace([ { id: 3, name: '<NAME>' }, { id: 4, name: '<NAME>' } ]) assertState(store, { users: { 3: { id: 3, name: '<NAME>' }, 4: { id: 4, name: '<NAME>' } } }) }) })
adinvadim/vuex-orm-next
src/interpreter/Interpreter.ts
import { normalize, schema as Normalizr } from 'normalizr' import { isArray, isEmpty } from '../support/Utils' import { Element, NormalizedData } from '../data/Data' import { Model } from '../model/Model' import { Database } from '@/database/Database' export class Interpreter<M extends Model> { /** * The database instance. */ database: Database /** * The model object. */ model: M /** * Create a new Interpreter instance. */ constructor(database: Database, model: M) { this.database = database this.model = model } /** * Perform interpretation for the given data and return normalized schema. */ processRecord(data: Element[]): [Element[], NormalizedData] processRecord(data: Element): [Element, NormalizedData] processRecord( data: Element | Element[] ): [Element | Element[], NormalizedData] { const schema = isArray(data) ? [this.getSchema()] : this.getSchema() const normalizedData = normalize(data, schema).entities as NormalizedData return [data, normalizedData] } /** * Perform interpretation for the given data. */ process(data: Element | Element[]): NormalizedData { return isEmpty(data) ? {} : this.normalize(data) } /** * Normalize the given data. */ private normalize(data: Element | Element[]): NormalizedData { const schema = isArray(data) ? [this.getSchema()] : this.getSchema() return normalize(data, schema).entities as NormalizedData } /** * Get the schema from the database. */ private getSchema(): Normalizr.Entity { return this.database.getSchema(this.model.$entity()) } }
adinvadim/vuex-orm-next
test/regression/normalizing_nested_relations_missing_parent_model.spec.ts
<gh_stars>0 import { createStore, assertState } from 'test/Helpers' import { Model, Str, Num, BelongsTo, HasMany } from '@/index' // A model with more than 2 related models related to the same model was // causing a normalization error. It was due to the Schema class was caching // the first created schema with its key. // // For example, the first relation creates a schema and say its name is // `proposal_settings`. Now the parent of this model is `proposal_templates`, // because it's defined first in Opportunity model. // // Next, if the `proposals` model also depends on `proposal_settings`, but // because the schema for `proposal_settings` is already created by // `proposal_templates`, it uses the same `proposal_settings` schema. Now we // have problem because the parent model this time should be `proposals` but // it's using the previous `proposal_templates`. // // We've fixed this by caching the schema with `model` AND `parent` entity // name. So only when the model and the parent name match, we use the cache. describe('regression/normalizing_nested_relations_missing_parent_model', () => { class Opportunity extends Model { static entity = 'opportunities' @Num(null, { nullable: true }) id!: number | null @HasMany(() => ProposalTemplate, 'opportunityId') proposalTemplates!: ProposalTemplate[] @HasMany(() => Proposal, 'opportunityId') proposals!: Proposal[] } class ProposalTemplate extends Model { static entity = 'proposal_templates' static primaryKey = ['opportunityId', 'proposalId'] @Num(null, { nullable: true }) opportunityId!: number | null @Num(null, { nullable: true }) proposalId!: number | null @BelongsTo(() => ProposalSetting, 'proposalId') proposal!: ProposalSetting } class Proposal extends Model { static entity = 'proposals' @Num(null, { nullable: true }) id!: number | null @Num(null, { nullable: true }) opportunityId!: number | null @Num(null, { nullable: true }) templateId!: number | null @BelongsTo(() => ProposalSetting, 'templateId') template!: ProposalSetting | null } class ProposalSetting extends Model { static entity = 'proposal_settings' @Num(null, { nullable: true }) id!: number | null @Str('') name!: string } it('???', async () => { const store = createStore() const dealRepo = store.$repo(Opportunity) await dealRepo.insert({ id: 1, proposalTemplates: [ { opportunityId: 2, proposalId: 1, proposal: { id: 1 } }, { opportunityId: 2, proposalId: 2, proposal: { id: 2 } } ], proposals: [ { id: 1, opportunityId: 1, templateId: 1, template: { id: 1, name: 'Hello, world!' } } ] }) assertState(store, { opportunities: { 1: { id: 1 } }, proposals: { 1: { id: 1, opportunityId: 1, templateId: 1 } }, proposal_settings: { 1: { id: 1, name: 'Hello, world!' }, 2: { id: 2, name: '' } }, proposal_templates: { '[1,1]': { opportunityId: 1, proposalId: 1 }, '[1,2]': { opportunityId: 1, proposalId: 2 } } }) }) })
adinvadim/vuex-orm-next
src/query/Query.ts
<filename>src/query/Query.ts import { isArray, isFunction, isEmpty, orderBy, groupBy, assert } from '../support/Utils' import { Element, Elements, NormalizedData, Item, Collection, Collections } from '../data/Data' import { Relation } from '../model/attributes/relations/Relation' import { Model } from '../model/Model' import { Interpreter } from '../interpreter/Interpreter' import { Connection } from '../connection/Connection' import { Where, WherePrimaryClosure, WhereSecondaryClosure, Order, OrderBy, OrderDirection, EagerLoad, EagerLoadConstraint, PersistMethod } from './Options' import { Database } from '@/database/Database' export interface CollectionPromises { indexes: string[] promises: Promise<Collection<Model>>[] } export class Query<M extends Model = Model> { /** * The database instance. */ database: Database /** * The model object. */ protected model: M /** * The interpreter instance. */ protected interpreter: Interpreter<M> /** * The connection instance. */ protected connection: Connection<M> /** * The where constraints for the query. */ protected wheres: Where[] = [] /** * The orderings for the query. */ protected orders: Order[] = [] /** * The maximum number of records to return. */ protected take: number | null = null /** * The number of records to skip. */ protected skip: number = 0 /** * The relationships that should be eager loaded. */ protected eagerLoad: EagerLoad = {} /** * Create a new query instance. */ constructor(database: Database, model: M) { this.database = database this.model = model this.interpreter = new Interpreter(database, model) this.connection = new Connection(database, model) } /** * Create a new query instance for the given model. */ protected newQuery(model: string): Query<Model> { return new Query(this.database, this.database.getModel(model)) } /** * Create a new query instance from the given relation. */ protected newQueryForRelation(relation: Relation): Query<Model> { return new Query( this.database, relation.getRelated().$setDatabase(this.database) ) } /** * Add a basic where clause to the query. */ where( field: WherePrimaryClosure | string, value?: WhereSecondaryClosure | any ): this { this.wheres.push({ field, value, boolean: 'and' }) return this } /** * Add a "where in" clause to the query. */ whereIn(field: string, values: any[]): this { this.wheres.push({ field, value: values, boolean: 'and' }) return this } /** * Add a where clause on the primary key to the query. */ whereId(ids: string | number | (string | number)[]): this { return this.where(this.model.$getKeyName() as any, ids) } /** * Add an "or where" clause to the query. */ orWhere( field: WherePrimaryClosure | string, value?: WhereSecondaryClosure | any ): this { this.wheres.push({ field, value, boolean: 'or' }) return this } /** * Add an "order by" clause to the query. */ orderBy(field: OrderBy, direction: OrderDirection = 'asc'): Query<M> { this.orders.push({ field, direction }) return this } /** * Set the "limit" value of the query. */ limit(value: number): this { this.take = value return this } /** * Set the "offset" value of the query. */ offset(value: number): this { this.skip = value return this } /** * Set the relationships that should be eager loaded. */ with(name: string, callback: EagerLoadConstraint = () => {}): Query<M> { this.eagerLoad[name] = callback return this } /** * Get all models from the store. The difference with the `get` is that this * method will not process any query chain. It'll always retrieve all models. */ all(): Collection<M> { const records = this.connection.get() const collection = [] as Collection<M> for (const id in records) { collection.push(this.hydrate(records[id])) } return collection } /** * Retrieve models by processing whole query chain. */ get(): Collection<M> { const models = this.select() if (!isEmpty(models)) { this.eagerLoadRelations(models) } return models } /** * Execute the query and get the first result. */ first(): Item<M> { return this.limit(1).get()[0] ?? null } /** * Find a model by its primary key. */ find(id: string | number): Item<M> find(ids: (string | number)[]): Collection<M> find(ids: any): any { return isArray(ids) ? this.findIn(ids) : this.whereId(ids).first() } /** * Find multiple models by their primary keys. */ findIn(ids: (string | number)[]): Collection<M> { return this.whereId(ids).get() } /** * Get models by given index ids. */ protected pick(id: string): Item<M> { const record = this.connection.find(id) return record ? this.hydrate(record) : null } /** * Retrieve models by processing all filters set to the query chain. */ select(): Collection<M> { let models = this.all() models = this.filterWhere(models) models = this.filterOrder(models) models = this.filterLimit(models) return models } /** * Filter the given collection by the registered where clause. */ protected filterWhere(models: Collection<M>): Collection<M> { if (isEmpty(this.wheres)) { return models } const comparator = this.getWhereComparator() return models.filter((model) => comparator(model)) } /** * Get comparator for the where clause. */ protected getWhereComparator(): (model: any) => boolean { const { and, or } = groupBy(this.wheres, (where) => where.boolean) return (model) => { const results: boolean[] = [] and && results.push(and.every((w) => this.whereComparator(model, w))) or && results.push(or.some((w) => this.whereComparator(model, w))) return results.indexOf(true) !== -1 } } /** * The function to compare where clause to the given model. */ protected whereComparator(model: M, where: Where): boolean { if (isFunction(where.field)) { return where.field(model) } if (isArray(where.value)) { return where.value.includes(model[where.field]) } if (isFunction(where.value)) { return where.value(model[where.field]) } return model[where.field] === where.value } /** * Filter the given collection by the registered order conditions. */ protected filterOrder(models: Collection<M>): Collection<M> { if (this.orders.length === 0) { return models } const fields = this.orders.map((order) => order.field) const directions = this.orders.map((order) => order.direction) return orderBy(models, fields, directions) } /** * Filter the given collection by the registered limit and offset values. */ protected filterLimit(models: Collection<M>): Collection<M> { return this.take !== null ? models.slice(this.skip, this.skip + this.take) : models.slice(this.skip) } /** * Eager load relations on the model. */ load(models: Collection<M>): void { this.eagerLoadRelations(models) } /** * Eager load the relationships for the models. */ protected eagerLoadRelations(models: Collection<M>): void { for (const name in this.eagerLoad) { this.eagerLoadRelation(models, name, this.eagerLoad[name]) } } /** * Eagerly load the relationship on a set of models. */ protected eagerLoadRelation( models: Collection<M>, name: string, constraints: EagerLoadConstraint ): void { // First we will "back up" the existing where conditions on the query so we can // add our eager constraints. Then we will merge the wheres that were on the // query back to it in order that any where conditions might be specified. const relation = this.getRelation(name) const query = this.newQueryForRelation(relation) relation.addEagerConstraints(query, models) constraints(query) // Once we have the results, we just match those back up to their parent models // using the relationship instance. Then we just return the finished arrays // of models which have been eagerly hydrated and are readied for return. relation.match(name, models, relation.getEager(query)) } /** * Get the relation instance for the given relation name. */ protected getRelation(name: string): Relation { return this.model.$getRelation(name) } /* * Retrieves the models from the store by following the given * normalized schema. */ revive(schema: Element[]): Collection<M> revive(schema: Element): Item<M> revive(schema: Element | Element[]): Item<M> | Collection<M> { return isArray(schema) ? this.reviveMany(schema) : this.reviveOne(schema) } /** * Revive single model from the given schema. */ reviveOne(schema: Element): Item<M> { const id = schema.__id if (!id) { return null } const item = this.connection.find(id) if (!item) { return null } const model = this.hydrate(item) this.reviveRelations(model, schema) return model } /** * Revive multiple models from the given schema. */ reviveMany(schema: Element[]): Collection<M> { return schema.reduce<Collection<M>>((collection, item) => { const model = this.reviveOne(item) model && collection.push(model) return collection }, []) } /** * Revive relations for the given schema and entity. */ protected reviveRelations(model: M, schema: Element) { const fields = this.model.$fields() for (const key in schema) { const attr = fields[key] if (!(attr instanceof Relation)) { continue } const relatedSchema = schema[key] model[key] = isArray(relatedSchema) ? this.newQueryForRelation(attr).reviveMany(relatedSchema) : this.newQueryForRelation(attr).reviveOne(relatedSchema) } } /** * Create and persist model with default values. */ async new(): Promise<M> { const model = this.model.$newInstance(undefined, { relations: false }) this.connection.insert(this.compile(model)) return model } /** * Save the given records to the store with data normalization. */ save(records: Element[]): Element[] save(record: Element): Element save(records: Element | Element[]): Element | Element[] { const [data, entities] = this.interpreter.processRecord(records) for (const entity in entities) { const query = this.newQuery(entity) const elements = entities[entity] query.saveElements(elements) } return data } /** * Save the given records to the store. */ saveElements(records: Elements): void { this.connection.save(records) } /** * Insert the given record to the store. */ async insert(records: Element | Element[]): Promise<Collections> { return this.persist('insert', records) } /** * Insert the given record to the store. */ async add<E extends Element>(records: E[]): Promise<Collection<M>> async add<E extends Element>(record: E): Promise<M> async add(records: any): Promise<any> { const models = this.hydrate(records) this.connection.insert(this.compile(models)) return models } /** * Insert the given records to the store by replacing any existing records. */ fresh(records: Element | Element[]): Promise<Collections> { return this.persist('fresh', records) } /** * Insert the given records to the store by replacing any existing records. */ async replace<E extends Element>(records: E[]): Promise<Collection<M>> async replace<E extends Element>(record: E): Promise<M> async replace(records: any): Promise<any> { const models = this.hydrate(records) this.connection.fresh(this.compile(models)) return models } /** * Update the given record to the store. */ async update(records: Element | Element[]): Promise<Collections> { return this.persist('update', records) } /** * Update records in the store by using the primary key of the given records. */ async merge(records: Element[]): Promise<Collection<M>> async merge(record: Element): Promise<Item<M>> async merge(records: any): Promise<any> { const models = this.getMergedModels(records) if (models === null) { return null } this.connection.update(this.compile(models)) return models } /** * Get models by merging the given records. This method will use the primary * key in the records to fetch models and merge it with the record. */ protected getMergedModels(records: Element[]): Collection<M> protected getMergedModels(record: Element): Item<M> protected getMergedModels(records: any): any { const recordsArray = isArray(records) ? records : [records] const models = recordsArray.reduce<Collection<M>>((collection, record) => { const model = this.pick(this.model.$getIndexId(record)) model && collection.push(model.$fill(record)) return collection }, []) return isArray(records) ? models : models[0] ?? null } /** * Update records in the store. */ async revise(record: Element): Promise<Collection<M>> { const models = this.get().map((model) => model.$fill(record)) this.connection.update(this.compile(models)) return models } /** * Persist records to the store by the given method. */ protected persist( method: PersistMethod, records: Element | Element[] ): Promise<Collections> { const normalizedData = this.interpret(records) const { indexes, promises } = this.createCollectionPromises( method, normalizedData ) return this.resolveCollectionPromises(indexes, promises) } /** * Persist normalized records with the given method. */ protected persistRecords( method: PersistMethod, records: Elements ): Promise<Collection<M>> { const mappedRecords = this.mapNormalizedData(records) switch (method) { case 'insert': return this.add(mappedRecords) case 'fresh': return this.replace(mappedRecords) case 'update': return this.merge(mappedRecords) } } /** * Convert normalized data into an array of records. */ protected mapNormalizedData(records: Elements): Element[] { const items = [] as Element[] for (const id in records) { items.push(records[id]) } return items } /** * Interpret the given record. */ protected interpret(records: Element | Element[]): NormalizedData { return this.interpreter.process(records) } /** * Create collection promises for the given normalized data. */ protected createCollectionPromises( method: PersistMethod, data: NormalizedData ): CollectionPromises { const indexes: string[] = [] const promises: Promise<Collection<any>>[] = [] for (const entity in data) { const records = data[entity] const query = this.newQuery(entity) indexes.push(entity) promises.push(query.persistRecords(method, records)) } return { indexes, promises } } /** * Resolve all collection promises and create a new collections object. */ protected async resolveCollectionPromises( indexes: string[], promises: Promise<Collection<any>>[] ): Promise<Collections> { return (await Promise.all(promises)).reduce<Collections>( (collections, collection, index) => { collections[indexes[index]] = collection return collections }, {} ) } /** * Destroy the models for the given id. */ async destroy(id: string | number): Promise<Item<M>> async destroy(ids: (string | number)[]): Promise<Collection<M>> async destroy(ids: any): Promise<any> { assert(!this.model.$hasCompositeKey(), [ "You can't use the `destroy` method on a model with a composite key.", 'Please use `delete` method instead.' ]) if (isArray(ids)) { return this.destroyMany(ids) } return (await this.whereId(ids).delete())[0] ?? null } /** * Destroy the models for the given id. */ async destroyMany(ids: (string | number)[]): Promise<Collection<M>> { return this.whereId(ids).delete() } /** * Delete records resolved by the query chain. */ async delete(): Promise<Collection<M>> { const models = this.get() this.connection.delete(this.getIndexIdsFromCollection(models)) return models } /** * Delete all records in the store. */ async flush(): Promise<Collection<M>> { const models = this.all() this.connection.flush() return models } /** * Get an array of ids from the given collection. */ protected getIndexIdsFromCollection(models: Collection<M>): string[] { return models.map((model) => model.$getIndexId()) } /** * Instantiate new models with the given record. */ protected hydrate(records: Element[]): Collection<M> protected hydrate(record: Element): M protected hydrate(records: any): any { return isArray(records) ? records.map((record) => this.hydrate(record)) : this.model.$newInstance(records, { relations: false }) } /** * Convert given models into an indexed object that is ready to be saved to * the store. */ protected compile(models: M | Collection<M>): Elements { const modelArray = isArray(models) ? models : [models] return modelArray.reduce<Elements>((records, model) => { records[model.$getIndexId()] = model.$getAttributes() return records }, {}) } }
adinvadim/vuex-orm-next
test/feature/relations/nested/nested_revive.spec.ts
<reponame>adinvadim/vuex-orm-next<filename>test/feature/relations/nested/nested_revive.spec.ts import { createStore, fillState } from 'test/Helpers' import { Model, Attr, BelongsTo, HasMany } from '@/index' describe('feature/relations/nested/nested_revive', () => { class User extends Model { static entity = 'users' @Attr() id!: number @HasMany(() => Post, 'userId') posts!: Post[] } class Post extends Model { static entity = 'posts' @Attr() id!: number @Attr() userId!: number | null @BelongsTo(() => User, 'userId') author!: User | null @HasMany(() => Comment, 'postId') comments!: Comment[] } class Comment extends Model { static entity = 'comments' @Attr() id!: number @Attr() postId!: number @Attr() userId!: number @BelongsTo(() => User, 'userId') author!: User | null } it('can revive a complex nested schema', () => { const store = createStore() fillState(store, { users: { 1: { id: 1 }, 2: { id: 2 }, 3: { id: 3 }, 4: { id: 4 } }, posts: { 1: { id: 1, userId: 2 }, 2: { id: 2, userId: 2 }, 3: { id: 3, userId: 1 }, 4: { id: 4, userId: 1 } }, comments: { 1: { id: 1, postId: 4, userId: 4 }, 2: { id: 2, postId: 1, userId: 2 }, 3: { id: 3, postId: 2, userId: 3 }, 4: { id: 4, postId: 4, userId: 3 }, 5: { id: 5, postId: 2, userId: 1 } } }) const schema = [ { __id: 2, posts: [ { __id: 4, comments: [{ __id: 2 }] }, { __id: 3, comments: [ { __id: 1, author: { __id: 4 } } ] } ] }, { __id: 1, posts: [{ __id: 1 }, { __id: 2 }] } ] const users = store.$repo(User).revive(schema) expect(users.length).toBe(2) expect(users[0].id).toBe(2) expect(users[1].id).toBe(1) expect(users[0].posts.length).toBe(2) expect(users[0].posts[0].comments.length).toBe(1) expect(users[0].posts[0].comments[0].id).toBe(2) expect(users[0].posts[1].comments.length).toBe(1) expect(users[0].posts[1].comments[0].id).toBe(1) }) })
adinvadim/vuex-orm-next
test/unit/model/Model.spec.ts
import { Model } from '@/model/Model' describe('unit/model/Model', () => { class User extends Model { static entity = 'users' } it('throws when accessing the store but it is not injected', () => { expect(() => new User().$database()).toThrow() }) })
richmccartney/mono-test
packages/react/src/components/BackgroundProvider/BackgroundProvider.stories.tsx
import React from 'react'; import { Meta, Story } from '@storybook/react'; import BackgroundProvider, { BackgroundProviderProps } from '.'; import mdx from './BackgroundProvider.mdx'; export default { title: 'Components/BackgroundProvider', args: { children: 'BackgroundProvider' }, parameters: { docs: { page: mdx, }, }, component: BackgroundProvider, } as Meta; export const Default: Story<BackgroundProviderProps> = (args) => ( <BackgroundProvider {...args} /> );
richmccartney/mono-test
packages/react/src/components/Surface/Surface.types.ts
<reponame>richmccartney/mono-test<filename>packages/react/src/components/Surface/Surface.types.ts import React, { HTMLAttributes } from 'react'; export type Backgrounds = 'primary' | 'secondary' | 'gray' | 'white' | 'dark'; export interface SurfaceProps extends HTMLAttributes<HTMLElement> { /** Content to display inside Surface. */ children: any; /** Optional prop to specify classNames onto the Surface */ className?: string; /** Option prop to specify the Element type */ as?: React.ElementType; /** * Optional prop to specify the `background` of the Surface? */ background?: Backgrounds; /** Optional prop to specify the ID used for testing */ testId?: string; /** Any additional props can be added where needed */ [props: string]: any; }
richmccartney/mono-test
packages/react/src/components/Button/Button.types.ts
import React, { MouseEvent, ReactNode } from 'react'; export interface ButtonProps { children?: ReactNode; id?: string; isFullWidth?: boolean; /** Optionally specify Button onClick function */ onClick?: (e: MouseEvent<HTMLElement>) => void; }
richmccartney/mono-test
packages/react/src/components/ThemeProvider/ThemeProvider.test.ssr.tsx
import React from 'react'; import { renderToString } from 'react-dom/server'; import { ThemeProvider } from '..'; describe('<ThemeProvider /> Server-side rendering>', () => { test(': renders on a server without crashing', () => { const renderOnServer = () => renderToString(<ThemeProvider />); expect(renderOnServer).not.toThrow(); }); });
richmccartney/mono-test
packages/react/src/components/Surface/Surface.test.tsx
<reponame>richmccartney/mono-test import React from 'react'; import { render } from '@testing-library/react'; import { Surface } from '..'; import { SurfaceProps } from '.'; describe('<Surface />', () => { const defaultProps: SurfaceProps = { testId: 'test-surface', }; test(': matches snapshot', () => { const { container } = render(<Surface {...defaultProps} />); expect(container.firstChild).toMatchSnapshot(); }); });
richmccartney/mono-test
packages/react/src/components/BackgroundProvider/BackgroundProvider.tsx
/** * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { FunctionComponent, createContext } from 'react'; import type { BackgroundProviderProps } from '.'; const Context = createContext({ Background: '' }); const { Provider } = Context; /** * Use `BackgroundProvider` to display components on different background colors. * * BackgroundProvider component. * * @component * @example * const background = 'dark' * return ( * <BackgroundProvider background={background}>...</BackgroundProvider> * ) */ const BackgroundProvider: FunctionComponent<BackgroundProviderProps> = ({ background = 'light', children, }) => { return <Provider value={{ Background: background }}>{children}</Provider>; }; export { Context as BackgroundProviderContext }; export default BackgroundProvider;
richmccartney/mono-test
packages/react/src/components/BackgroundProvider/BackgroundProvider.types.ts
export type BackgroundVariant = 'dark' | 'light' | undefined; export interface BackgroundProviderProps { /** * Background variant to be composed into the BackgroundProvider. */ background?: BackgroundVariant; /** * Content to display on the BackgroundProvider. */ children: any; }
richmccartney/mono-test
packages/react/.playroom/FrameComponent.tsx
<filename>packages/react/.playroom/FrameComponent.tsx<gh_stars>0 // .playroom/FrameComponent.tsx import React, { FunctionComponent } from 'react'; const reset = ` body { margin: 0; } `; const FrameComponent: FunctionComponent = ({ children }) => { return ( <> <style type="text/css">{reset}</style> {children} </> ); }; export default FrameComponent;
richmccartney/mono-test
packages/react/src/components/ThemeProvider/ThemeProvider.stories.tsx
<filename>packages/react/src/components/ThemeProvider/ThemeProvider.stories.tsx<gh_stars>0 import React from 'react'; import { Meta, Story } from '@storybook/react'; import ThemeProvider, { ThemeProviderProps } from '.'; import mdx from './ThemeProvider.mdx'; export default { title: 'Components/ThemeProvider', args: { children: 'ThemeProvider' }, parameters: { docs: { page: mdx, }, }, component: ThemeProvider, } as Meta; export const Default: Story<ThemeProviderProps> = (args) => ( <ThemeProvider {...args} /> );
richmccartney/mono-test
packages/react/src/components/ThemeProvider/ThemeProvider.test.tsx
<reponame>richmccartney/mono-test import React from 'react'; import { render } from '@testing-library/react'; import { ThemeProvider } from '..'; import { ThemeProviderProps } from '.'; describe('<ThemeProvider />', () => { const defaultProps: ThemeProviderProps = { testId: 'test-themeprovider', }; test(': matches snapshot', () => { const { container } = render(<ThemeProvider {...defaultProps} />); expect(container.firstChild).toMatchSnapshot(); }); });
richmccartney/mono-test
packages/react/src/components/ThemeProvider/themes/MonoTheme.tsx
<filename>packages/react/src/components/ThemeProvider/themes/MonoTheme.tsx<gh_stars>0 import React from 'react'; import './MonoTheme.scss'; const Theme = () => <React.Fragment></React.Fragment>; export default Theme;
richmccartney/mono-test
packages/react/src/components/Surface/Surface.tsx
/** * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import classNames from 'classnames'; import React, { FunctionComponent } from 'react'; import type { SurfaceProps } from '.'; import { BackgroundProvider } from '..'; import './Surface.scss'; /** * Use `Surface` to display content on different colour backgrounds. * * @component * @example * const background = 'navy' * return ( * <Surface background={background}> * <div>Hello World!</div> * </Surface> * ) */ const Surface: FunctionComponent<SurfaceProps> = ({ children, className, background, as: ElementTag = 'div', testId, ...props }) => { const surfaceClasses = classNames({ 'mono-Surface': true, 'mono-Surface--backgroundPrimary': background === 'primary', 'mono-Surface--backgroundSecondary': background === 'secondary', 'mono-Surface--backgroundWhite': background === 'white', 'mono-Surface--backgroundDark': background === 'dark', 'mono-Surface--backgroundGray': background === 'gray', [`${className}`]: className, }); const commonProps = { className: surfaceClasses, 'data-testid': testId, }; const surfaceBackground = background === 'dark' || background === 'secondary' || background === 'gray' ? 'dark' : 'light'; return ( <BackgroundProvider background={surfaceBackground}> <ElementTag {...commonProps} {...props}> {children} </ElementTag> </BackgroundProvider> ); }; export default Surface;
richmccartney/mono-test
packages/react/src/components/BackgroundProvider/BackgroundProvider.snippets.tsx
<filename>packages/react/src/components/BackgroundProvider/BackgroundProvider.snippets.tsx<gh_stars>0 export const BackgroundProviderSnippets = [ { group: 'BackgroundProvider', name: 'Default', code: ` <BackgroundProvider /> `, }, ];
richmccartney/mono-test
packages/react/src/components/ThemeProvider/ThemeProvider.snippets.tsx
<reponame>richmccartney/mono-test<filename>packages/react/src/components/ThemeProvider/ThemeProvider.snippets.tsx export const ThemeProviderSnippets = [ { group: 'ThemeProvider', name: 'Default', code: ` <ThemeProvider /> `, }, ];
richmccartney/mono-test
packages/react/src/components/index.ts
<filename>packages/react/src/components/index.ts /** * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ export { default as BackgroundProvider } from './BackgroundProvider'; export { default as Button } from './Button'; export { default as Surface } from './Surface'; export { default as ThemeProvider } from './ThemeProvider';
richmccartney/mono-test
packages/react/src/components/Button/Button.tsx
<filename>packages/react/src/components/Button/Button.tsx import classNames from 'classnames'; import React, { forwardRef, FunctionComponent, useContext } from 'react'; import { ButtonProps } from './Button.types'; import { BackgroundProviderContext } from '../BackgroundProvider'; import './Button.scss'; type Ref = React.Ref<HTMLButtonElement>; /** * Use `Button` to allow users to take actions with clicks and taps. */ const Button: FunctionComponent<ButtonProps> = forwardRef( ({ children, id, isFullWidth, onClick }, ref: Ref) => { const { Background } = useContext(BackgroundProviderContext); const buttonClasses = classNames({ 'mono-Button': true, 'mono-Button--isFullWidth': !!isFullWidth, 'mono-Button--onPrimaryBackground': Background === 'light', 'mono-Button--onSecondaryBackground': Background === 'dark', 'mono-Button--onDarkBackground': Background === 'dark', }); return ( <button className={buttonClasses} id={id} ref={ref} onClick={onClick}> {children} </button> ); } ); export default Button;
richmccartney/mono-test
packages/react/src/components/BackgroundProvider/BackgroundProvider.test.a11y.tsx
<reponame>richmccartney/mono-test import React from 'react'; import { render } from '@testing-library/react'; import { BackgroundProvider } from '..'; import { BackgroundProviderProps } from '.'; import { axe, toHaveNoViolations } from 'jest-axe'; expect.extend(toHaveNoViolations); describe('<BackgroundProvider />', () => { const defaultProps: BackgroundProviderProps = { testId: 'test-backgroundprovider', }; test(': should not have basic accessibility issues', async () => { const { container } = render(<BackgroundProvider {...defaultProps} />); const results = await axe(container); expect(results).toHaveNoViolations(); }); });
richmccartney/mono-test
packages/react/src/components/Surface/Surface.snippets.tsx
<gh_stars>0 export const SurfaceSnippets = [ { group: 'Surface', name: 'Default', code: ` <Surface /> `, }, ];
richmccartney/mono-test
packages/react/src/components/ThemeProvider/ThemeProvider.tsx
<filename>packages/react/src/components/ThemeProvider/ThemeProvider.tsx<gh_stars>0 /** * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import classNames from 'classnames'; import React, { FunctionComponent } from 'react'; import type { ThemeProviderProps } from '.'; import './ThemeProvider.scss'; const MonoTheme = React.lazy(() => import('./themes/MonoTheme')); const ChromeTheme = React.lazy(() => import('./themes/ChromeTheme')); /** * ThemeProvider component. * * @component * @example * return ( * <ThemeProvider /> * ) */ const ThemeProvider: FunctionComponent<ThemeProviderProps> = ({ testId, children, className, screen = 'light', theme = 'mono', ...props }) => { const themeproviderClasses = classNames({ 'mono-ThemeProvider': true, 'mono-ThemeProvider--mono': theme === 'mono', 'mono-ThemeProvider--chrome': theme === 'chrome', [`${className}`]: className, }); const commonProps = { className: themeproviderClasses, 'data-testid': testId, 'data-color-scheme': screen, }; return ( <> <React.Suspense fallback={<></>}> {theme === 'mono' && <MonoTheme />} {theme === 'chrome' && <ChromeTheme />} </React.Suspense> <div {...commonProps} {...props}> {children} </div> </> ); }; export default ThemeProvider;
richmccartney/mono-test
packages/react/src/components/snippets.ts
/** * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { ButtonSnippets } from './Button/Button.snippets'; export default [...ButtonSnippets];
richmccartney/mono-test
packages/react/src/components/Button/Button.snippets.tsx
<filename>packages/react/src/components/Button/Button.snippets.tsx<gh_stars>0 export const ButtonSnippets = [ { group: 'Button', name: 'Default', code: ` <Button> Button </Button> `, }, ];
richmccartney/mono-test
packages/react/src/components/Surface/Surface.stories.tsx
import React from 'react'; import { Meta, Story } from '@storybook/react'; import Surface, { SurfaceProps } from '.'; import mdx from './Surface.mdx'; export default { title: 'Components/Surface', args: { children: 'Surface' }, parameters: { docs: { page: mdx, }, }, component: Surface, } as Meta; export const Default: Story<SurfaceProps> = (args) => <Surface {...args} />;
richmccartney/mono-test
packages/react/src/components/ThemeProvider/ThemeProvider.types.ts
export type ThemeVariant = 'mono' | 'chrome'; export type ScreenMode = 'light' | 'dark'; export interface ThemeProviderProps { /** Optional prop to specify the ID used for testing */ testId?: string; /** Content to display inside ThemeProvider. */ children?: React.ReactNode; /** Optional prop to specify classNames onto ThemeProvider */ className?: string; screen: ScreenMode; /** Prop to specify the variant of the theme to use */ theme: ThemeVariant; /** Any additional props can be added where needed */ [props: string]: any; }
richmccartney/mono-test
packages/react/src/components/Surface/Surface.test.a11y.tsx
<gh_stars>0 import React from 'react'; import { render } from '@testing-library/react'; import { Surface } from '..'; import { SurfaceProps } from '.'; import { axe, toHaveNoViolations } from 'jest-axe'; expect.extend(toHaveNoViolations); describe('<Surface />', () => { const defaultProps: SurfaceProps = { testId: 'test-surface', }; test(': should not have basic accessibility issues', async () => { const { container } = render(<Surface {...defaultProps} />); const results = await axe(container); expect(results).toHaveNoViolations(); }); });
richmccartney/mono-test
packages/react/src/components/ThemeProvider/index.ts
<reponame>richmccartney/mono-test export { default } from './ThemeProvider'; export type { ThemeProviderProps } from './ThemeProvider.types';
richmccartney/mono-test
packages/react/src/components/BackgroundProvider/index.ts
export { default, BackgroundProviderContext } from './BackgroundProvider'; export type { BackgroundProviderProps } from './BackgroundProvider.types';
richmccartney/mono-test
packages/react/src/components/BackgroundProvider/BackgroundProvider.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { BackgroundProvider } from '..'; import { BackgroundProviderProps } from '.'; describe('<BackgroundProvider />', () => { const defaultProps: BackgroundProviderProps = { testId: 'test-backgroundprovider', }; test(': matches snapshot', () => { const { container } = render(<BackgroundProvider {...defaultProps} />); expect(container.firstChild).toMatchSnapshot(); }); });
Colorfulstan/discord-bot-starter-kit
Lib/typescript-version/handlers/command.ts
import { readdirSync } from 'fs'; const ascii = require('ascii-table'); let table = new ascii('Commands'); table.setHeading('Commands', 'STATUS'); module.exports = (client: any) => { readdirSync('./commands/').forEach(dir => { const commands = readdirSync(`./commands/${dir}/`).filter(file => file.endsWith('.ts') ); for (let file of commands) { let pull = require(`../commands/${dir}/${file}`); if (pull.name) { client.commands.set(pull.name, pull); table.addRow(file, '✓'); } else { table.addRow(file, `❌ -> help.name MISSING.`); continue; } if (pull.aliases && Array.isArray(pull.aliases)) pull.aliases.forEach((alias: any) => client.aliases.set(alias, pull.name) ); } }); console.log(table.toString()); };
Colorfulstan/discord-bot-starter-kit
Lib/typescript-version/index.ts
<reponame>Colorfulstan/discord-bot-starter-kit const { Client, Collection, RichEmbed } = require('discord.js'); const { config } = require('dotenv'); const client = new Client({ disableEveryone: true }); client.commands = new Collection(); client.aliases = new Collection(); config({ path: __dirname + '/.env' }); ['command'].forEach(handler => { require(`./handlers/${handler}`)(client); }); client.on('ready', () => { console.log(`Hi, ${client.user.username} is now online!`); client.user.setPresence({ status: 'online', game: { name: 'Me getting F*', type: 'WATCHING' } }); }); const newUsers = new Collection(); client.on('guildMemberAdd', (member: any) => { newUsers.set(member.id, member.user); member.guild.channels.get('662244192784744471').send( new RichEmbed() .setColor('#d347a6') .setDescription(`Welcome ${member.user.username} 👶`) .setTitle('Welcome our new User!') ); }); client.on('guildMemberRemove', (member: any) => { if (newUsers.has(member.id)) newUsers.delete(member.id); member.guild.channels.get('662244192784744471').send( new RichEmbed() .setColor('#d347a6') .setDescription(`${member.user.username} 🖕🏿🖕🏿🖕🏿🖕🏿`) .setTitle('Bye fucking prick 🖕🏿🖕🏿🖕🏿🖕🏿🖕🏿🖕🏿') ); }); client.on('message', async (message: any) => { const prefix: string = '!!'; if (message.author.bot) return; if (!message.guild) return; if (!message.content.startsWith(prefix)) return; if (!message.member) message.member = await message.guild.fetchMember(message); const args = message.content .slice(prefix.length) .trim() .split(/ +/g); const cmd = args.shift().toLowerCase(); if (cmd.length === 0) return; let command = client.commands.get(cmd); if (!command) command = client.commands.get(client.aliases.get(cmd)); if (command) command.run(client, message, args); }); client.login(process.env.TOKEN);
Colorfulstan/discord-bot-starter-kit
Lib/typescript-version/functions.ts
module.exports = { getMember: function(message: any, toFind: any = '') { toFind = toFind.toLowerCase(); let target = message.guild.members.get(toFind); if (!target && message.mentions.members) target = message.mentions.members.first(); if (!target && toFind) { target = message.guild.members.find((member: any) => { return ( member.displayName.toLowerCase().includes(toFind) || member.user.tag.toLowerCase().includes(toFind) ); }); } if (!target) target = message.member; return target; }, formatDate: function(date: any) { return new Intl.DateTimeFormat('en-US').format(date); } };
ArtMan-8/htmlacademy-dashboard
src/components/DataLoader/index.ts
export { default } from './DataLoader';
ArtMan-8/htmlacademy-dashboard
src/store/types.ts
import { IProject, INormalizedProject } from '../components/DataLoader/helpers'; export enum EActionType { SET_SELECTED_PROJECTS = 'SET_SELECTED_PROJECTS', SET_REQUEST_LIMIT = 'SET_REQUEST_LIMIT', ADD_REPOSITORIES = 'ADD_REPOSITORIES', UPDATE_FETCH_STATUS = 'UPDATE_FETCH_STATUS', CLEAR_REPOSITORIES = 'CLEAR_REPOSITORIES', } export enum EFetchStatus { IDLE = 'idle', PENDING = 'pending', SUCCEEDED = 'succeeded', FAILED = 'failed', } export interface IState { selectedProjects: string[]; requestLimit: number; fetchStatus: EFetchStatus; projects: INormalizedProject[]; } export interface IActions { [EActionType.SET_SELECTED_PROJECTS]: { selectedProjects: string[]; }; [EActionType.SET_REQUEST_LIMIT]: { requestLimit: number; }; [EActionType.ADD_REPOSITORIES]: { projects: IProject[]; }; [EActionType.UPDATE_FETCH_STATUS]: { fetchStatus: EFetchStatus; }; [EActionType.CLEAR_REPOSITORIES]: undefined; } type ActionMap<M extends { [index: string]: any }> = { [Key in keyof M]: M[Key] extends undefined ? { type: Key; } : { type: Key; payload: M[Key]; }; }; export type TActions = ActionMap<IActions>[keyof ActionMap<IActions>]; function createAction<Obj extends { [index: string]: any }>() { return function <Key extends keyof Obj>(name: Key, ...args: Obj[Key] extends undefined ? [] : [Obj[Key]]) { return args.length > 0 ? { type: name, payload: args[0] } : { type: name }; }; } export const actionCreate = createAction<IActions>();
ArtMan-8/htmlacademy-dashboard
src/components/DataLoader/dataLoader.styles.ts
<filename>src/components/DataLoader/dataLoader.styles.ts import { createStyles, makeStyles } from '@material-ui/core/styles'; export default makeStyles(() => createStyles({ dataLoader: { margin: 20, padding: 20, }, progressBar: { margin: 20, }, button: { margin: 5, }, note: { marginTop: 20, fontSize: 12, }, }), );
ArtMan-8/htmlacademy-dashboard
src/pages/Charts/helpers.ts
import { INormalizedProject } from '../../components/DataLoader/helpers'; import { NotFound } from '../../constants'; function getRandomColor(opacity = 1) { const r = Math.random() * 255; const g = Math.random() * 255; const b = Math.random() * 255; return `rgba(${r}, ${g}, ${b}, ${opacity})`; } export const options = { plugins: { title: { display: true, text: 'Количество проектов по модулям.', }, }, }; interface IDate { labels: string[]; datasets: { label: string; data: number[]; backgroundColor: string[]; borderColor: string[]; borderWidth: number; hoverOffset: number; }[]; } export function getDataForDoughnutChart(projects: INormalizedProject[]): IDate { const dataForDoughnutChart = projects.reduce((data: Record<string, number>, project) => { const lastPR = project.lastPullRequestName === NotFound.TITLE ? NotFound.TITLE : project.lastPullRequestName.split('-')[0]; return { ...data, [lastPR]: data[lastPR] ? data[lastPR] + 1 : 1, }; }, {}); const labels = Object.keys(dataForDoughnutChart).sort(); const data = { labels: labels.map((label) => `На ${label} - ${dataForDoughnutChart[label]} репозиториев`), datasets: [ { label: 'Count projects on modules', data: labels.map((label) => dataForDoughnutChart[label]), backgroundColor: labels.map(() => getRandomColor(0.5)), borderColor: ['white'], borderWidth: 2, hoverOffset: 3, }, ], }; return data; }
ArtMan-8/htmlacademy-dashboard
src/pages/Table/helpers.ts
<reponame>ArtMan-8/htmlacademy-dashboard<filename>src/pages/Table/helpers.ts import { INormalizedProject } from '../../components/DataLoader/helpers'; export type Order = 'asc' | 'desc'; export function descendingComparator<T>(a: T, b: T, orderBy: keyof T): number { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0; } export function getComparator<Key extends keyof any>( order: Order, orderBy: Key, ): (a: { [key in Key]: string }, b: { [key in Key]: string }) => number { return order === 'desc' ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy); } export function stableSort<T>(array: T[], comparator: (a: T, b: T) => number): T[] { const stabilizedThis = array.map((el, index) => [el, index] as [T, number]); stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]); if (order !== 0) return order; return a[1] - b[1]; }); return stabilizedThis.map((el) => el[0]); } export function generateRows(projects: INormalizedProject[]): { authorName: string; authorUrl: string; repoName: string; repoUrl: string; mentorName: string; mentorUrl: string; lastPullRequestName: string; lastPullRequestUrl: string; lastCommit: string; }[] { return projects.map( ({ authorName, authorUrl, repoName, repoUrl, mentorName, mentorUrl, lastPullRequestName, lastPullRequestUrl, lastCommit, }) => ({ authorName, authorUrl, repoName, repoUrl, mentorName, mentorUrl, lastPullRequestName, lastPullRequestUrl, lastCommit, }), ); } export interface IheadCells { id: 'authorName' | 'repoName' | 'lastCommit' | 'mentorName' | 'lastPullRequestName'; align: 'left' | 'center' | 'right'; padding: 'none' | 'normal'; label: string; } export const headCells: IheadCells[] = [ { id: 'authorName', align: 'left', padding: 'normal', label: 'Автор' }, { id: 'repoName', align: 'left', padding: 'normal', label: 'Репозиторий' }, { id: 'lastCommit', align: 'center', padding: 'normal', label: 'Последний commit' }, { id: 'mentorName', align: 'left', padding: 'normal', label: 'Наставник' }, { id: 'lastPullRequestName', align: 'left', padding: 'normal', label: 'Последний PullRquest' }, ];
ArtMan-8/htmlacademy-dashboard
src/pages/Charts/charts.styles.ts
<gh_stars>0 import { createStyles, makeStyles } from '@material-ui/core/styles'; export default makeStyles(() => createStyles({ charts: { margin: '20px auto', maxWidth: 700, padding: 20, }, note: {}, }), );
ArtMan-8/htmlacademy-dashboard
src/graphql/GetStudentRepos.query.ts
<filename>src/graphql/GetStudentRepos.query.ts import { gql } from '@apollo/client'; import { PAGE_INFO, RATE_LIMIT, REPO_STUDENT_INFO, REPO_ACADEMY_INFO } from './fragment'; export const GET_STUDENT_REPOS = gql` ${RATE_LIMIT} ${PAGE_INFO} ${REPO_STUDENT_INFO} ${REPO_ACADEMY_INFO} query GetRepos($projectName: String!, $after: String, $first: Int!) { ...RateLimit search(query: $projectName, type: REPOSITORY, after: $after, first: $first) { ...PageInfo nodes { ... on Repository { url ...RepoStudentInfo ...RepoAcademyInfo } } } } `;
ArtMan-8/htmlacademy-dashboard
src/pages/Search/helpers.ts
import { Courses, NotFound, PROXY_URL } from '../../constants'; export function generateOriginalCourseUrl(selectedCourse: string): string { return `${PROXY_URL}/get?url=https://github.com/${Courses[selectedCourse]?.organization}/`; } export function getCourseNumber(html: string): string { const parser = new DOMParser(); const content = parser.parseFromString(html, 'text/html'); const courseNumber = content ?.querySelector('li.Box-row:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > a:nth-child(1)') ?.textContent?.trim() .split('-') .pop(); return courseNumber || NotFound.TITLE; }
ArtMan-8/htmlacademy-dashboard
src/components/NotFoundRepo/index.ts
export { default } from './NotFoundRepo';
ArtMan-8/htmlacademy-dashboard
src/index.tsx
<gh_stars>0 import React from 'react'; import ReactDom from 'react-dom'; import { ApolloProvider } from '@apollo/client'; import StoreProvider from './store/store'; import App from './App'; import createApolloClient from './api/apollo.config'; import { GITHUB_GRAPHQL_ENDPOINT } from './constants'; ReactDom.render( <ApolloProvider client={createApolloClient(GITHUB_GRAPHQL_ENDPOINT)}> <StoreProvider> <App /> </StoreProvider> </ApolloProvider>, document.querySelector('#root'), );
ArtMan-8/htmlacademy-dashboard
src/components/DataLoader/DataLoader.tsx
import React, { useContext, useState } from 'react'; import { useQuery } from '@apollo/client'; import { Link } from 'react-router-dom'; import LinearProgress from '@material-ui/core/LinearProgress'; import Paper from '@material-ui/core/Paper'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import { GET_STUDENT_REPOS } from '../../graphql/GetStudentRepos.query'; import { store } from '../../store/store'; import { actionCreate, EActionType, EFetchStatus } from '../../store/types'; import useStyles from './dataLoader.styles'; /* refetchLimit заглушка для быстрых тестов обрывает запросы */ export default function DataLoader(): JSX.Element { const classes = useStyles(); // const [refetchLimit, setRefetchLimit] = useState(2); const [cursor, setCursor] = useState<string | null>(null); const { state, dispatch } = useContext(store); const { selectedProjects, projects, fetchStatus } = state; const { data, loading, error } = useQuery(GET_STUDENT_REPOS, { variables: { projectName: selectedProjects[0], after: cursor, first: 10, }, onCompleted() { dispatch(actionCreate(EActionType.SET_REQUEST_LIMIT, { requestLimit: data.rateLimit.remaining })); dispatch(actionCreate(EActionType.ADD_REPOSITORIES, { projects: data.search.nodes })); // const hasPage = () => data.search.pageInfo.hasNextPage && refetchLimit > 0; const hasPage = () => data.search.pageInfo.hasNextPage; if (hasPage()) { setCursor(data.search.pageInfo.endCursor); // setRefetchLimit(refetchLimit - 1); } if (!hasPage() && selectedProjects.length) { setCursor(null); const [, ...restProjects] = selectedProjects; dispatch(actionCreate(EActionType.SET_SELECTED_PROJECTS, { selectedProjects: restProjects })); } if (loading) { dispatch(actionCreate(EActionType.UPDATE_FETCH_STATUS, { fetchStatus: EFetchStatus.PENDING })); } if (error) { dispatch(actionCreate(EActionType.UPDATE_FETCH_STATUS, { fetchStatus: EFetchStatus.FAILED })); } if (!error && !loading && !hasPage() && selectedProjects.length === 1) { dispatch(actionCreate(EActionType.UPDATE_FETCH_STATUS, { fetchStatus: EFetchStatus.SUCCEEDED })); } }, }); const isLoading = fetchStatus === EFetchStatus.PENDING; const isError = fetchStatus === EFetchStatus.FAILED; const isSuccess = fetchStatus === EFetchStatus.SUCCEEDED; return ( <Paper className={classes.dataLoader}> {isLoading && <LinearProgress className={classes.progressBar} />} {projects.length > 0 && ( <Typography align="center">Найдено активных* репозиториев:&nbsp;{projects.length}</Typography> )} {isError && <Typography align="center">Что-то пошло не так</Typography>} {projects.length > 0 && isSuccess && ( <div style={{ textAlign: 'center' }}> <Typography align="center">Выберите вариант просмотра</Typography> <Button variant="contained" color="primary" component={Link} to="/table" className={classes.button}> таблица </Button> <Button variant="contained" color="primary" component={Link} to="/charts" className={classes.button}> графики </Button> <Button variant="contained" color="primary" component={Link} to="/mentors" className={classes.button}> Наставники </Button> <Typography align="center" className={classes.note}> * Учитываются форкнутые репозитории, <br />с наличием пул-реквестов </Typography> </div> )} </Paper> ); }
ArtMan-8/htmlacademy-dashboard
src/graphql/fragment.ts
<reponame>ArtMan-8/htmlacademy-dashboard import { gql } from '@apollo/client'; export const RATE_LIMIT = gql` fragment RateLimit on Query { rateLimit { remaining } } `; export const PAGE_INFO = gql` fragment PageInfo on SearchResultItemConnection { pageInfo { hasNextPage endCursor } } `; export const REPO_STUDENT_INFO = gql` fragment RepoStudentInfo on Repository { forks(first: 1) { nodes { ... on Repository { id url name pushedAt assignableUsers(first: 1) { nodes { ... on User { name login url } } } } } } } `; export const REPO_ACADEMY_INFO = gql` fragment RepoAcademyInfo on Repository { pullRequests(last: 25) { nodes { headRefName url merged participants(first: 5) { nodes { ... on User { name login url } } } } } } `;
ArtMan-8/htmlacademy-dashboard
src/components/DataLoader/helpers.ts
<filename>src/components/DataLoader/helpers.ts import { NotFound } from '../../constants'; export interface INormalizedPullRequest { branchName: string; branchUrl: string; merged: boolean; mentorName: string; mentorUrl: string; } export interface INormalizedProject { id: string; repoUrl: string; repoName: string; authorName: string; authorUrl: string; mentorName: string; mentorUrl: string; lastCommit: string; lastPullRequestName: string; lastPullRequestUrl: string; pullRequests: INormalizedPullRequest[]; } export interface IUser { login: string; name: string; url: string; } export interface IForks { nodes: { id: string; name: string; url: string; pushedAt: string; assignableUsers: { nodes: IUser[]; }; }[]; } export interface IPullRequest { nodes: { headRefName: string; url: string; merged: boolean; participants: { nodes: IUser[]; }; }[]; } export interface IProject { url: string; forks: IForks; pullRequests: IPullRequest; } export function normalizeProject({ forks, pullRequests }: IProject): INormalizedProject { const fork = forks.nodes[0]; const authorName = fork.assignableUsers.nodes[0].name; const authorLogin = fork.assignableUsers.nodes[0].login; const filteredPullRequests = pullRequests.nodes.filter(({ headRefName }) => headRefName.includes('module')); const normalizedPullRequests = filteredPullRequests.reduce( (pullRequestList: INormalizedPullRequest[], pullRequest) => { const mentor = pullRequest.participants.nodes .filter(({ login }) => login !== 'keksobot' && login !== authorLogin) .map(({ name, url, login }) => ({ name, url, login })); const mentorName = mentor[0]?.name || ''; const mentorLogin = mentor[0]?.login || NotFound.TITLE; const mentorLink = mentor[0]?.url || NotFound.URL; return pullRequestList.concat({ branchName: pullRequest.headRefName, branchUrl: pullRequest.url, merged: pullRequest.merged, mentorName: mentorName ? `${mentorName} aka ${mentorLogin}` : mentorLogin, mentorUrl: mentorLink, }); }, [], ); const lastPullRequest = normalizedPullRequests[normalizedPullRequests.length - 1] || { branchName: NotFound.TITLE, branchUrl: NotFound.URL, merged: false, }; const pullRequestInfo = normalizedPullRequests.filter(({ mentorName }) => mentorName !== NotFound.TITLE)[0]; return { id: fork.id, repoUrl: fork.url, repoName: fork.name, authorName: authorName ? `${authorName} aka ${authorLogin}` : authorLogin, authorUrl: fork.assignableUsers.nodes[0].url, mentorName: pullRequestInfo?.mentorName || NotFound.TITLE, mentorUrl: pullRequestInfo?.mentorUrl || NotFound.URL, lastCommit: fork.pushedAt.slice(0, 10), lastPullRequestName: lastPullRequest.merged ? `${lastPullRequest.branchName} - merged` : `${lastPullRequest.branchName} - open`, lastPullRequestUrl: lastPullRequest.branchUrl, pullRequests: normalizedPullRequests, }; }
ArtMan-8/htmlacademy-dashboard
src/module.d.ts
<gh_stars>0 declare module 'react-swipeable-views';
ArtMan-8/htmlacademy-dashboard
src/pages/Charts/Charts.tsx
<filename>src/pages/Charts/Charts.tsx import React, { useContext, useRef } from 'react'; import { Doughnut } from 'react-chartjs-2'; import Paper from '@material-ui/core/Paper'; import { store } from '../../store/store'; import NotFoundRepo from '../../components/NotFoundRepo'; import { getDataForDoughnutChart, options } from './helpers'; import useStyles from './charts.styles'; export default function Charts(): JSX.Element { const classes = useStyles(); const refDoughnut = useRef(); const { state } = useContext(store); const { projects } = state; if (projects.length === 0) { return <NotFoundRepo />; } const data = getDataForDoughnutChart(projects); return ( <Paper className={classes.charts}> <Doughnut ref={refDoughnut} data={data} options={options} /> </Paper> ); }
ArtMan-8/htmlacademy-dashboard
src/graphql/GetRateLimit.query.ts
import { gql } from '@apollo/client'; import { RATE_LIMIT } from './fragment'; export const GET_RATE_LIMIT = gql` ${RATE_LIMIT} query { ...RateLimit } `;
ArtMan-8/htmlacademy-dashboard
src/pages/Search/search.styles.ts
import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; export default makeStyles((theme: Theme) => createStyles({ search: { margin: '20px auto', maxWidth: 600, }, form: { display: 'flex', flexDirection: 'column', margin: 20, padding: 20, backgroundColor: 'white', borderRadius: 4, boxShadow: '0px 2px 1px -1px rgba(0,0,0,0.2),0px 1px 1px 0px rgba(0,0,0,0.14),0px 1px 3px 0px rgba(0,0,0,0.12)', }, inputNumber: { '& input': { textAlign: 'center', }, }, submit: { margin: '30px auto', width: 'max-content', }, formControl: { margin: theme.spacing(1), minWidth: 200, maxWidth: '100%', textAlign: 'center', }, selectEmpty: { marginTop: theme.spacing(2), }, chips: { display: 'flex', flexWrap: 'wrap', justifyContent: 'center', }, chip: { margin: 2, }, noLabel: { marginTop: theme.spacing(3), }, }), );
ArtMan-8/htmlacademy-dashboard
src/api/apollo.config.ts
import { ApolloClient, InMemoryCache, NormalizedCacheObject } from '@apollo/client'; export default function createApolloClient(uri: string): ApolloClient<NormalizedCacheObject> { return new ApolloClient({ uri, headers: { authorization: `Bearer ${process.env.GRAPHQL_API_KEY}`, }, connectToDevTools: true, cache: new InMemoryCache(), }); }
ArtMan-8/htmlacademy-dashboard
src/components/NotFoundRepo/NotFoundRepo.tsx
<filename>src/components/NotFoundRepo/NotFoundRepo.tsx import React from 'react'; import { Link } from 'react-router-dom'; import SearchIcon from '@material-ui/icons/Search'; import Paper from '@material-ui/core/Paper'; import Button from '@material-ui/core/Button'; import useStyles from './notFoundRepo.styles'; export default function NotFoundRepo(): JSX.Element { const classes = useStyles(); return ( <Paper className={classes.notFound}> Репозитории не найдены <br /> <Button variant="contained" color="primary" endIcon={<SearchIcon />} component={Link} to="/" className={classes.button} > найти </Button> </Paper> ); }
ArtMan-8/htmlacademy-dashboard
src/components/NotFoundRepo/notFoundRepo.styles.ts
import { createStyles, makeStyles } from '@material-ui/core/styles'; export default makeStyles(() => createStyles({ notFound: { margin: '20px auto', padding: 20, width: 'max-content', textAlign: 'center', fontSize: 16, fontWeight: 500, }, button: { margin: '20px auto 0', }, }), );
ArtMan-8/htmlacademy-dashboard
src/pages/Mentors/index.ts
export { default } from './Mentors';
ArtMan-8/htmlacademy-dashboard
src/components/Header/Header.tsx
import React from 'react'; import { Link } from 'react-router-dom'; import clsx from 'clsx'; import Drawer from '@material-ui/core/Drawer'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import List from '@material-ui/core/List'; import Typography from '@material-ui/core/Typography'; import Divider from '@material-ui/core/Divider'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import PeopleIcon from '@material-ui/icons/People'; import ListItemText from '@material-ui/core/ListItemText'; import BubbleChartIcon from '@material-ui/icons/BubbleChart'; import TocIcon from '@material-ui/icons/Toc'; import SearchIcon from '@material-ui/icons/Search'; import Backdrop from '@material-ui/core/Backdrop'; import useStyles from './header.styles'; const navLinks = { search: { title: 'Поиск проектов', icon: SearchIcon, url: '/', }, table: { title: 'Таблица проектов', icon: TocIcon, url: '/table', }, mentors: { title: 'Наставники', icon: PeopleIcon, url: '/mentors', }, charts: { title: 'Графики', icon: BubbleChartIcon, url: '/charts', }, }; export default function Header(): JSX.Element { const classes = useStyles(); const [isMenuOpen, setMenu] = React.useState(false); const handleMenuOpen = () => { setMenu(true); }; const handleMenuClose = () => { setMenu(false); }; return ( <> <AppBar component="header" position="fixed" color="primary" className={clsx(classes.appBar, { [classes.appBarShift]: isMenuOpen, })} > <Toolbar> <Typography variant="h6" color="inherit" noWrap className={classes.title} component={Link} to="/"> htmlacademy dashboard </Typography> <IconButton color="inherit" aria-label="open menu" edge="end" onClick={handleMenuOpen} className={clsx(isMenuOpen && classes.hide)} > <MenuIcon /> </IconButton> </Toolbar> </AppBar> <Backdrop className={classes.backdrop} open={isMenuOpen} onClick={handleMenuClose}> <Drawer className={classes.drawer} variant="persistent" anchor="right" open={isMenuOpen} classes={{ paper: classes.drawerPaper, }} > <div className={classes.drawerHeader}> <IconButton onClick={handleMenuClose}> <ChevronLeftIcon /> </IconButton> </div> <Divider /> <List component="nav"> {Object.values(navLinks).map(({ icon: Icon, title, url }) => ( <Link key={title} to={url} className={classes.link}> <ListItem button> <ListItemIcon> <Icon /> </ListItemIcon> <ListItemText primary={title} /> </ListItem> </Link> ))} </List> </Drawer> </Backdrop> </> ); }
ArtMan-8/htmlacademy-dashboard
src/pages/Charts/index.ts
<reponame>ArtMan-8/htmlacademy-dashboard export { default } from './Charts';
ArtMan-8/htmlacademy-dashboard
src/pages/Table/table.styles.ts
<reponame>ArtMan-8/htmlacademy-dashboard import { createStyles, makeStyles } from '@material-ui/core/styles'; export default makeStyles(() => createStyles({ root: { width: '100%', }, paper: { margin: '20px', }, table: { minWidth: 1000, }, visuallyHidden: { border: 0, clip: 'rect(0 0 0 0)', height: 1, margin: -1, overflow: 'hidden', padding: 0, position: 'absolute', top: 20, width: 1, }, }), );
ArtMan-8/htmlacademy-dashboard
src/pages/Search/Search.tsx
<reponame>ArtMan-8/htmlacademy-dashboard<filename>src/pages/Search/Search.tsx import React, { useContext, useEffect, useState } from 'react'; import Button from '@material-ui/core/Button'; import Input from '@material-ui/core/Input'; import InputLabel from '@material-ui/core/InputLabel'; import MenuItem from '@material-ui/core/MenuItem'; import FormControl from '@material-ui/core/FormControl'; import TextField from '@material-ui/core/TextField'; import Select from '@material-ui/core/Select'; import Chip from '@material-ui/core/Chip'; import SearchIcon from '@material-ui/icons/Search'; import { Courses, NotFound } from '../../constants'; import { actionCreate, EActionType, EFetchStatus } from '../../store/types'; import { store } from '../../store/store'; import { generateOriginalCourseUrl, getCourseNumber } from './helpers'; import DataLoader from '../../components/DataLoader'; import useStyles from './search.styles'; export default function Search(): JSX.Element { const classes = useStyles(); const [selectedCourse, setCourse] = useState<string>(''); const [chosenProjects, setProjects] = useState<string[]>([]); const [courseNumber, setCourseNumber] = useState<string>(NotFound.TITLE); const { state, dispatch } = useContext(store); const { fetchStatus, projects } = state; const handleSelectProject = (event: React.ChangeEvent<{ value: unknown }>) => { setProjects(event.target.value as string[]); }; const handleChangeCourse = (event: React.ChangeEvent<{ value: unknown }>) => { setCourse(event.target.value as string); setCourseNumber('определяем номер потока ...'); setProjects([]); }; const onQuerySubmit = (event: React.ChangeEvent<HTMLFormElement>) => { event.preventDefault(); const selectedProjects = chosenProjects.map((project) => `${project}-${courseNumber}`); dispatch(actionCreate(EActionType.CLEAR_REPOSITORIES)); dispatch(actionCreate(EActionType.SET_SELECTED_PROJECTS, { selectedProjects: selectedProjects })); dispatch(actionCreate(EActionType.UPDATE_FETCH_STATUS, { fetchStatus: EFetchStatus.PENDING })); }; useEffect(() => { fetch(generateOriginalCourseUrl(selectedCourse)) .then((response) => response.json()) .then(({ contents }) => { setCourseNumber(getCourseNumber(contents)); }); }, [selectedCourse]); const isLoading = fetchStatus === EFetchStatus.PENDING; return ( <div className={classes.search}> <form className={classes.form} onSubmit={onQuerySubmit}> <FormControl className={classes.formControl}> <InputLabel id="select-course-label">Выберите курс</InputLabel> <Select labelId="select-course-label" id="select-course" required disabled={isLoading} value={selectedCourse} onChange={handleChangeCourse} label="course" > {Object.entries(Courses).map(([key, value]) => ( <MenuItem key={key} value={key}> {value.description} </MenuItem> ))} </Select> </FormControl> <FormControl className={classes.formControl}> <InputLabel id="select-project-label">Выберите проект/ы</InputLabel> <Select labelId="select-project-label" id="select-project" multiple required disabled={isLoading} value={chosenProjects} onChange={handleSelectProject} input={<Input id="select-multiple-chip" />} renderValue={(selected) => ( <div className={classes.chips}> {(selected as string[]).map((value) => ( <Chip key={value} label={value} className={classes.chip} /> ))} </div> )} > {Courses[selectedCourse]?.projects.map((project) => ( <MenuItem key={project} value={project}> {project} </MenuItem> ))} </Select> </FormControl> <FormControl className={classes.formControl}> <TextField label="Номер потока" id="select-course-number" disabled={true} value={courseNumber} className={classes.inputNumber} /> </FormControl> <Button className={classes.submit} type="submit" disabled={isLoading || !Number(courseNumber) || !chosenProjects.length} variant="contained" color="primary" endIcon={<SearchIcon />} > Найти проекты </Button> </form> {(isLoading || projects.length > 0) && <DataLoader />} </div> ); }
ArtMan-8/htmlacademy-dashboard
src/pages/Table/Table.tsx
<reponame>ArtMan-8/htmlacademy-dashboard<gh_stars>0 import React, { useContext, useState, useEffect } from 'react'; import MuiTable from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import { useMediaQuery } from '@material-ui/core'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TablePagination from '@material-ui/core/TablePagination'; import TableRow from '@material-ui/core/TableRow'; import TableSortLabel from '@material-ui/core/TableSortLabel'; import Paper from '@material-ui/core/Paper'; import useStyles from './table.styles'; import { generateRows, getComparator, headCells, IheadCells, Order, stableSort } from './helpers'; import { store } from '../../store/store'; import NotFoundRepo from '../../components/NotFoundRepo'; interface IEnhancedTableHead { classes: ReturnType<typeof useStyles>; onRequestSort: (event: React.MouseEvent<unknown>, property: IheadCells['id']) => void; order: Order; orderBy: string; } function EnhancedTableHead(props: IEnhancedTableHead) { const { classes, order, orderBy, onRequestSort } = props; const createSortHandler = (property: IheadCells['id']) => (event: React.MouseEvent<unknown>) => { onRequestSort(event, property); }; return ( <TableHead> <TableRow> {headCells.map((headCell) => ( <TableCell key={headCell.id} align={headCell.align} padding={headCell.padding} sortDirection={orderBy === headCell.id ? order : false} > <TableSortLabel active={orderBy === headCell.id} direction={orderBy === headCell.id ? order : 'asc'} onClick={createSortHandler(headCell.id)} > {headCell.label} {orderBy === headCell.id ? ( <span className={classes.visuallyHidden}> {order === 'desc' ? 'sorted descending' : 'sorted ascending'} </span> ) : null} </TableSortLabel> </TableCell> ))} </TableRow> </TableHead> ); } export default function Table(): JSX.Element { const classes = useStyles(); const isDesktop = useMediaQuery('(min-height: 950px)'); const [order, setOrder] = useState<Order>('asc'); const [orderBy, setOrderBy] = useState<IheadCells['id']>('authorName'); const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(10); const { state } = useContext(store); const { projects } = state; useEffect(() => { setRowsPerPage(isDesktop ? 20 : 10); }, [isDesktop]); if (projects.length === 0) { return <NotFoundRepo />; } const rows = generateRows(projects); const handleRequestSort = (event: React.MouseEvent<unknown>, property: IheadCells['id']) => { const isAsc = orderBy === property && order === 'asc'; setOrder(isAsc ? 'desc' : 'asc'); setOrderBy(property); }; const handleChangePage = (event: unknown, newPage: number) => { setPage(newPage); }; const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage); return ( <div className={classes.root}> <Paper className={classes.paper}> <TableContainer> <MuiTable className={classes.table} aria-labelledby="tableTitle" size={'small'} aria-label="enhanced table"> <EnhancedTableHead classes={classes} order={order} orderBy={orderBy} onRequestSort={handleRequestSort} /> <TableBody> {stableSort(rows, getComparator(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((row, index) => { const labelId = `enhanced-table-checkbox-${index}`; return ( <TableRow hover role="checkbox" tabIndex={-1} key={row.repoUrl}> <TableCell component="th" id={labelId} scope="row"> <a href={row.authorUrl} target="_blank" rel="noreferrer"> {row.authorName} </a> </TableCell> <TableCell align="left"> <a href={row.repoUrl} target="_blank" rel="noreferrer"> {row.repoName} </a> </TableCell> <TableCell align="center">{row.lastCommit}</TableCell> <TableCell component="th" id={labelId} scope="row"> <a href={row.mentorUrl} target="_blank" rel="noreferrer"> {row.mentorName} </a> </TableCell> <TableCell component="th" id={labelId} scope="row"> <a href={row.lastPullRequestUrl} target="_blank" rel="noreferrer"> {row.lastPullRequestName} </a> </TableCell> </TableRow> ); })} {emptyRows > 0 && ( <TableRow style={{ height: 33 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} </TableBody> </MuiTable> </TableContainer> <TablePagination rowsPerPageOptions={[10, 20, 50]} component="div" count={rows.length} rowsPerPage={rowsPerPage} labelRowsPerPage="Записей на страницу" page={page} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} /> </Paper> </div> ); }
ArtMan-8/htmlacademy-dashboard
src/constants.ts
<filename>src/constants.ts<gh_stars>0 export const GITHUB_GRAPHQL_ENDPOINT = 'https://api.github.com/graphql'; export const PROXY_URL = 'https://hexlet-allorigins.herokuapp.com'; export const Author = { NAME: 'ArtMan-8', URL: 'https://github.com/ArtMan-8', }; export const NotFound = { TITLE: 'не определён', URL: 'https://github.com/404', }; interface ICourses { [key: string]: { organization: string; description: string; projects: string[]; }; } export const Courses: ICourses = { htmlCss1: { organization: `htmlacademy-htmlcss`, description: 'HTML и CSS. Профессиональная вёрстка сайтов', projects: ['device', 'gllacy', 'nerds', 'sedona', 'technomart'], }, htmlCss2: { organization: `htmlacademy-adaptive`, description: 'HTML и CSS. Адаптивная вёрстка и автоматизация', projects: ['cat-energy', 'device', 'mishka', 'pognali', 'sedona'], }, javaScript1: { organization: `htmlacademy-javascript`, description: 'JavaScript. Профессиональная разработка веб-интерфейсов', projects: ['keksobooking', 'kekstagram'], }, javaScript2: { organization: `htmlacademy-ecmascript`, description: 'JavaScript. Архитектура клиентских приложений', projects: ['big-trip', 'cinemaddict'], }, react: { organization: `htmlacademy-react`, description: 'React. Разработка сложных клиентских приложений', projects: ['six-cities', 'what-to-watch'], }, };
ArtMan-8/htmlacademy-dashboard
src/store/reducer.ts
<filename>src/store/reducer.ts import { normalizeProject } from '../components/DataLoader/helpers'; import { EActionType, IState, TActions } from './types'; export default function reducer(state: IState, action: TActions): IState { switch (action.type) { case EActionType.SET_SELECTED_PROJECTS: return { ...state, ...action.payload, }; case EActionType.SET_REQUEST_LIMIT: { return { ...state, ...action.payload, }; } case EActionType.ADD_REPOSITORIES: { const { projects } = state; const filteredProjects = action.payload.projects.filter( ({ url, pullRequests, forks }) => url.includes('htmlacademy') && pullRequests.nodes[0] && forks.nodes[0], ); const normalizedProject = filteredProjects.map(normalizeProject); const existsRepositoryUrl = projects.map(({ repoUrl }) => repoUrl); const newRepository = normalizedProject.filter(({ repoUrl }) => !existsRepositoryUrl.includes(repoUrl)); return { ...state, projects: [...projects, ...newRepository], }; } case EActionType.UPDATE_FETCH_STATUS: { return { ...state, ...action.payload, }; } case EActionType.CLEAR_REPOSITORIES: { return { ...state, projects: [], }; } default: throw new Error(`Unknown action type`); } }
ArtMan-8/htmlacademy-dashboard
src/pages/Mentors/helpers.ts
<filename>src/pages/Mentors/helpers.ts<gh_stars>0 import { GridColDef } from '@material-ui/data-grid'; import { NotFound } from '../../constants'; import { INormalizedProject } from '../../components/DataLoader/helpers'; export const columns: GridColDef[] = [ { field: 'id', headerName: '№', width: 100, align: 'center', }, { field: 'mentor', headerName: 'Ментор', width: 400, }, { field: 'students', headerName: 'Студенты', description: 'Количество студентов у ментора', type: 'number', width: 150, align: 'center', }, { field: 'githubProfile', headerName: 'Gihub', description: 'Github ментора', sortable: false, width: 400, }, ]; interface IRow { id: number; mentor: string; students: number; githubProfile: string; } interface IMentor { mentorName: string; mentorUrl: string; studendCount: number; } export default function getRowsForDataGrid(projects: INormalizedProject[]): IRow[] { const dataForGrid = projects.reduce((data: Record<string, IMentor>, item) => { const { mentorName, mentorUrl } = item; return { ...data, [mentorName]: { mentorName, mentorUrl, studendCount: data[mentorName] ? data[mentorName].studendCount + 1 : 1, }, }; }, {}); const rows: IRow[] = Object.values(dataForGrid) .map((mentor, index) => ({ id: index + 1, mentor: mentor.mentorName, students: mentor.studendCount, githubProfile: mentor.mentorUrl, })) .sort(({ mentor }) => (mentor === NotFound.TITLE ? 1 : -1)); return rows; }
ArtMan-8/htmlacademy-dashboard
src/pages/Mentors/Mentors.tsx
import React, { useContext } from 'react'; import { useMediaQuery } from '@material-ui/core'; import { DataGrid } from '@material-ui/data-grid'; import Paper from '@material-ui/core/Paper'; import NotFoundRepo from '../../components/NotFoundRepo'; import { store } from '../../store/store'; import getRowsForDataGrid, { columns } from './helpers'; import useStyles from './mentors.styles'; export default function Mentor(): JSX.Element { const classes = useStyles(); const isDesktop = useMediaQuery('(min-height: 950px)'); const { state } = useContext(store); const { projects } = state; if (projects.length === 0) { return <NotFoundRepo />; } const rows = getRowsForDataGrid(projects); return ( <div className={classes.root}> <Paper className={classes.paper} style={{ height: isDesktop ? 650 : 400 }}> <DataGrid rows={rows} columns={columns} pageSize={isDesktop ? 10 : 5} disableSelectionOnClick /> </Paper> </div> ); }
ArtMan-8/htmlacademy-dashboard
src/components/Main/Main.tsx
<filename>src/components/Main/Main.tsx import React from 'react'; interface IMain { children: React.ReactNode; } export default function Main({ children }: IMain): JSX.Element { return <main>{children}</main>; }
ArtMan-8/htmlacademy-dashboard
src/App/app.styles.ts
<filename>src/App/app.styles.ts<gh_stars>0 import { createStyles } from '@material-ui/core/styles'; export default createStyles({ '@global': { '#root': { display: 'flex', flexDirection: 'column', minHeight: '100vh', backgroundColor: '#f5f5f5', }, header: {}, main: { marginTop: 64, }, footer: { marginTop: 'auto', }, }, });
ArtMan-8/htmlacademy-dashboard
src/components/Footer/footer.styles.ts
import { createStyles, makeStyles } from '@material-ui/core/styles'; export default makeStyles(() => createStyles({ appBar: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 20, }, author: { color: 'white', textDecoration: 'underline', '&:hover': { opacity: 0.7, }, }, }), );
ArtMan-8/htmlacademy-dashboard
src/components/Footer/Footer.tsx
<reponame>ArtMan-8/htmlacademy-dashboard<gh_stars>0 import React, { useState, useContext, useEffect } from 'react'; import { useQuery } from '@apollo/client'; import { Typography, Link, AppBar } from '@material-ui/core'; import Snackbar from '@material-ui/core/Snackbar'; import Slide from '@material-ui/core/Slide'; import Alert from '@material-ui/lab/Alert'; import { GET_RATE_LIMIT } from '../../graphql/GetRateLimit.query'; import { actionCreate, EActionType } from '../../store/types'; import { store } from '../../store/store'; import useStyles from './footer.styles'; import { Author } from '../../constants'; export default function Footer(): JSX.Element { const classes = useStyles(); const [isError, setError] = useState(false); const { state, dispatch } = useContext(store); const { requestLimit } = state; const { data, error } = useQuery(GET_RATE_LIMIT, { onCompleted() { dispatch(actionCreate(EActionType.SET_REQUEST_LIMIT, { requestLimit: data.rateLimit.remaining })); }, }); const handleClose = () => { setError(false); }; useEffect(() => { if (error) { setError(true); } }, [error]); return ( <AppBar component="footer" position="static" color="primary" className={classes.appBar}> <Typography align="center"> Создал{' '} <b> <Link color="inherit" href={Author.URL} target="_blank" className={classes.author}> {Author.NAME} </Link> </b> </Typography> <Typography align="center"> лимит запросов: <b>{requestLimit || '...'}</b> </Typography> <Snackbar open={isError} autoHideDuration={5000} onClose={handleClose} TransitionComponent={Slide}> <Alert onClose={handleClose} severity="error"> Ошибка загрузки данных </Alert> </Snackbar> </AppBar> ); }
ArtMan-8/htmlacademy-dashboard
src/store/store.tsx
import React, { createContext, useReducer } from 'react'; import reducer from './reducer'; import { EFetchStatus, IState, TActions } from './types'; const initialState: IState = { selectedProjects: [], requestLimit: 0, fetchStatus: EFetchStatus.IDLE, projects: [], }; interface IStore { state: IState; dispatch: React.Dispatch<any>; } export const store = createContext<IStore>({ state: initialState, dispatch: () => null, }); const { Provider } = store; export default function StoreProvider({ children }: { children: React.ReactNode }): JSX.Element { const [state, dispatch] = useReducer<React.Reducer<IState, TActions>>(reducer, initialState); return <Provider value={{ state, dispatch }}>{children}</Provider>; }
ArtMan-8/htmlacademy-dashboard
src/pages/Mentors/mentors.styles.ts
<reponame>ArtMan-8/htmlacademy-dashboard<gh_stars>0 import { createStyles, makeStyles } from '@material-ui/core/styles'; export default makeStyles(() => createStyles({ root: { width: '100%', }, paper: { margin: '20px', }, }), );
ArtMan-8/htmlacademy-dashboard
src/App/App.tsx
import React from 'react'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; import { CssBaseline, withStyles } from '@material-ui/core'; import Header from '../components/Header'; import Main from '../components/Main'; import Footer from '../components/Footer'; import styles from './app.styles'; import Search from '../pages/Search'; import Table from '../pages/Table'; import Charts from '../pages/Charts'; import Mentors from '../pages/Mentors'; export default withStyles(styles)(function App(): JSX.Element { return ( <> <CssBaseline /> <BrowserRouter> <Header /> <Main> <Switch> <Route path="/charts" component={Charts} /> <Route path="/table" component={Table} /> <Route path="/mentors" component={Mentors} /> <Route path="/" component={Search} /> </Switch> </Main> <Footer /> </BrowserRouter> </> ); });
giorgiofederici/giorgiofederici-frontend
src/app/website/home/home.module.ts
import { NgModule } from '@angular/core'; // Routing import { RouterModule, Routes } from '@angular/router'; // FontAwesome import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { library } from '@fortawesome/fontawesome-svg-core'; import { faGithub, faTwitter, faLinkedin, faInstagram } from '@fortawesome/free-brands-svg-icons'; // Home import { HomeComponent } from './containers/home/home.component'; import { HomePresentationComponent } from './components/home-presentation/home-presentation.component'; export const ROUTES: Routes = [ { path: '', component: HomeComponent } ]; @NgModule({ imports: [ RouterModule.forChild(ROUTES), FontAwesomeModule ], declarations: [ HomeComponent, HomePresentationComponent ] }) export class HomeModule { constructor() { // Add an icon to the library for convenient access in other components library.add(faGithub, faTwitter, faLinkedin, faInstagram); } }
giorgiofederici/giorgiofederici-frontend
src/app/website/root/components/website-header/website-header.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'website-header', templateUrl: './website-header.component.html', styleUrls: ['./website-header.component.scss'] }) export class WebsiteHeaderComponent { }
giorgiofederici/giorgiofederici-frontend
src/app/auth/services/auth.service.ts
import { Injectable } from '@angular/core'; import { Observable, of, throwError } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class AuthService { /* private AUTH_BASE_URL = environment.backendUrl + '/auth'; constructor(private httpClient: HttpClient) { } login({ username, password, email }: Credentials): Observable<User> { const url = `${this.AUTH_BASE_URL}/login`; return this.httpClient.post<User>(url, { username, password }); } logout() { return of(true); } signup({ username, password, email }: Credentials): Observable<User> { const url = `${this.AUTH_BASE_URL}/signup`; return this.httpClient.post<User>(url, { username, password, email }); } */ }
giorgiofederici/giorgiofederici-frontend
src/app/admin/admin.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; // Router import { RouterModule, Routes } from '@angular/router'; // Guards import { AuthGuard } from '../auth/shared/guards/auth.guard'; // Shared import { SharedModule } from './shared/shared.module'; export const ROUTES: Routes = [ { path: '', canActivate: [AuthGuard], loadChildren: './root/admin-root.module#AdminRootModule' } ]; @NgModule({ imports: [RouterModule.forChild(ROUTES), CommonModule, SharedModule.forRoot()] }) export class AdminModule {}
giorgiofederici/giorgiofederici-frontend
src/app/website/root/website-root.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; // Routing import { RouterModule, Routes } from '@angular/router'; // Ng Bootstrap import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap'; // Font Awesome import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { library } from '@fortawesome/fontawesome-svg-core'; import { faBars } from '@fortawesome/free-solid-svg-icons'; // Website Root import { WebsiteRootComponent } from './containers/website-root/website-root.component'; import { WebsiteHeaderComponent } from './components/website-header/website-header.component'; import { WebsiteFooterComponent } from './components/website-footer/website-footer.component'; import { WebsiteNavComponent } from './components/website-nav/website-nav.component'; import { WebsiteNavItemComponent } from './components/website-nav-item/website-nav-item.component'; import { WebsiteClipTextComponent } from './components/website-clip-text/website-clip-text.component'; export const ROUTES: Routes = [ { path: '', component: WebsiteRootComponent, children: [ { path: '', loadChildren: '../home/home.module#HomeModule' }, { path: 'cv', loadChildren: '../cv/cv.module#CVModule' }, { path: 'projects', loadChildren: '../portfolio/portfolio.module#PortfolioModule' }, { path: 'contact', loadChildren: '../contact/contact.module#ContactModule' } ] } ]; @NgModule({ imports: [ CommonModule, RouterModule.forChild(ROUTES), NgbCollapseModule, FontAwesomeModule ], declarations: [ WebsiteRootComponent, WebsiteHeaderComponent, WebsiteFooterComponent, WebsiteNavComponent, WebsiteNavItemComponent, WebsiteClipTextComponent ], exports: [] }) export class WebsiteRootModule { constructor() { library.add(faBars); } }
giorgiofederici/giorgiofederici-frontend
src/app/auth/auth.module.ts
<filename>src/app/auth/auth.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; // Routing import { Routes, RouterModule } from '@angular/router'; // Material import { MaterialModule } from '../material/material.module'; // Shared import { SharedModule } from './shared/shared.module'; // Env import { environment } from '../../environments/environment'; // Logout import { LogoutModule } from './logout/logout.module'; export const ROUTES: Routes = [ { path: 'login', loadChildren: './login/login.module#LoginModule' } ]; @NgModule({ imports: [ CommonModule, RouterModule.forChild(ROUTES), // forRoot() specified here to avoid AuthService duplicates. Not needed to do the same in login and register module SharedModule.forRoot(), LogoutModule ], declarations: [], entryComponents: [] }) export class AuthModule {}
giorgiofederici/giorgiofederici-frontend
src/app/admin/shared/resolvers/skills/skill.resolver.ts
<gh_stars>0 import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router'; // RxJS import { Observable } from 'rxjs'; import { filter, first, tap } from 'rxjs/operators'; // ngRx import { select, Store } from '@ngrx/store'; // Reducer import * as fromSkills from '../../reducers/skills/skills.reducer'; // Actions import { SkillsActions } from '../../actions/skills/index'; // Model import { Skill } from '../../models/skills/skill.model'; // Service import { SkillsService } from '../../services/skills/skills.service'; export class SkillResolver implements Resolve<Skill> { constructor( private store: Store<fromSkills.SkillsState>, private skillsService: SkillsService ) {} resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<Skill> { const skillId = route.params.id; return this.store.pipe( select(fromSkills.selectSkillById(skillId)), tap(skill => { if (!skill) { this.store.dispatch(new SkillsActions.GetSkill({ skillId })); } }), filter(skill => !!skill), first() ); } }
giorgiofederici/giorgiofederici-frontend
src/app/website/root/components/website-nav/website-nav.component.ts
<reponame>giorgiofederici/giorgiofederici-frontend import { Component, OnInit } from '@angular/core'; @Component({ selector: 'website-nav', templateUrl: './website-nav.component.html', styleUrls: ['./website-nav.component.scss'] }) export class WebsiteNavComponent implements OnInit { isCollapsed: boolean; constructor() { } ngOnInit() { this.isCollapsed = true; } }
giorgiofederici/giorgiofederici-frontend
src/app/admin/shared/actions/skills/skills.actions.ts
// ngRx import { Action } from '@ngrx/store'; import { Update } from '@ngrx/entity'; // Shared import { Skill } from '../../models/skills/skill.model'; export enum SkillsActionTypes { // Get All Skills GetAllSkills = '[Skills] Get All Skills', GetAllSkillsSuccess = '[Skills/API] Get All Skills Success', GetAllSkillsFailure = '[Skills/API] Get All Skills Failure', // Get Skill GetSkill = '[Skills] Get Skill', GetSkillSuccess = '[Skills/API] Get Skill Success', GetSkillFailure = '[Skills/API] Get Skill Failure', // Create Skill CreateSkill = '[Skills] Create Skill', CreateSkillSuccess = '[Skills/API] Create Skill Success', CreateSkillFailure = '[Skills/API] Create Skill Failure', // Update Skill UpdateSkill = '[Skills] Update Skill', UpdateSkillSuccess = '[Skills/API] Update Skill Success', UpdateSkillFailure = '[Skills/API] Update Skill Failure', // Delete Skill DeleteSkill = '[Skills] Delete Skill', DeleteSkillSuccess = '[Skills/API] Delete Skill Success', DeleteSkillFailure = '[Skills/API] Delete Skill Failure' } // Get All Skills export class GetAllSkills implements Action { readonly type = SkillsActionTypes.GetAllSkills; } export class GetAllSkillsSuccess implements Action { readonly type = SkillsActionTypes.GetAllSkillsSuccess; constructor(public payload: { skills: Skill[] }) {} } export class GetAllSkillsFailure implements Action { readonly type = SkillsActionTypes.GetAllSkillsFailure; constructor(public payload: { error: any }) {} } // Get Skill export class GetSkill implements Action { readonly type = SkillsActionTypes.GetSkill; constructor(public payload: { skillId: string }) {} } export class GetSkillSuccess implements Action { readonly type = SkillsActionTypes.GetSkillSuccess; constructor(public payload: { skill: Skill }) {} } export class GetSkillFailure implements Action { readonly type = SkillsActionTypes.GetSkillFailure; constructor(public payload: { error: any }) {} } // Create Skill export class CreateSkill implements Action { readonly type = SkillsActionTypes.CreateSkill; constructor(public payload: { skill: Skill }) {} } export class CreateSkillSuccess implements Action { readonly type = SkillsActionTypes.CreateSkillSuccess; constructor(public payload: { skill: Skill }) {} } export class CreateSkillFailure implements Action { readonly type = SkillsActionTypes.CreateSkillFailure; constructor(public payload: { error: any }) {} } // Update Skill export class UpdateSkill implements Action { readonly type = SkillsActionTypes.UpdateSkill; constructor(public payload: { skillId: string; skillChanges: Skill }) {} } export class UpdateSkillSuccess implements Action { readonly type = SkillsActionTypes.UpdateSkillSuccess; constructor(public payload: { skill: Update<Skill> }) {} } export class UpdateSkillFailure implements Action { readonly type = SkillsActionTypes.UpdateSkillFailure; constructor(public payload: { error: any }) {} } // Delete Skill export class DeleteSkill implements Action { readonly type = SkillsActionTypes.DeleteSkill; constructor(public payload: { skillId: string }) {} } export class DeleteSkillSuccess implements Action { readonly type = SkillsActionTypes.DeleteSkillSuccess; constructor(public payload: { skillId: string }) {} } export class DeleteSkillFailure implements Action { readonly type = SkillsActionTypes.DeleteSkillFailure; constructor(public payload: { error: any }) {} } export type SkillsActionsUnion = | GetAllSkills | GetAllSkillsSuccess | GetAllSkillsFailure | GetSkill | GetSkillSuccess | GetSkillFailure | CreateSkill | CreateSkillSuccess | CreateSkillFailure | UpdateSkill | UpdateSkillSuccess | UpdateSkillFailure | DeleteSkill | DeleteSkillSuccess | DeleteSkillFailure;
giorgiofederici/giorgiofederici-frontend
src/app/admin/shared/models/projects/project.model.ts
export interface Project { _id: string; name: string; description: string; image?: string; repository?: string; link?: string; index?: number; modifiedAt: Date; createdAt: Date; }
giorgiofederici/giorgiofederici-frontend
src/app/website/cv/components/cv-skills/cv-skills.component.ts
<gh_stars>0 import { Component, Input } from '@angular/core'; // Models import { Skill } from '../../../../admin/shared/models/skills/skill.model'; @Component({ selector: 'website-cv-skills', templateUrl: './cv-skills.component.html', styleUrls: ['./cv-skills.component.scss'] }) export class CVSkillsComponent { @Input() skills: Skill[]; constructor() {} getFilledStars(experience: number) { return Array(experience); } getNotFilledStars(experience: number) { return Array(5 - experience); } }
giorgiofederici/giorgiofederici-frontend
src/app/admin/shared/reducers/projects/projects.reducer.ts
// NgRx import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity'; import { createFeatureSelector, createSelector } from '@ngrx/store'; // Actions import { ProjectsActions } from '../../actions/projects'; // Models import { Project } from '../../models/projects/project.model'; export interface ProjectsState extends EntityState<Project> { allProjectsLoading: boolean; allProjectsError: string | null; projectLoading: boolean; projectError: string | null; createLoading: boolean; createError: string | null; updateLoading: boolean; updateError: string | null; deleteLoading: boolean; deleteError: string | null; } export const adapter: EntityAdapter<Project> = createEntityAdapter<Project>({ selectId: project => project._id }); export const initialProjectsState: ProjectsState = adapter.getInitialState({ allProjectsLoading: false, allProjectsError: null, projectLoading: false, projectError: null, createLoading: false, createError: null, updateLoading: false, updateError: null, deleteLoading: false, deleteError: null }); export function projectsReducer( state = initialProjectsState, action: | ProjectsActions.GetAllProjects | ProjectsActions.GetAllProjectsSuccess | ProjectsActions.GetAllProjectsFailure | ProjectsActions.GetProject | ProjectsActions.GetProjectSuccess | ProjectsActions.GetProjectFailure | ProjectsActions.CreateProject | ProjectsActions.CreateProjectSuccess | ProjectsActions.CreateProjectFailure | ProjectsActions.UpdateProject | ProjectsActions.UpdateProjectSuccess | ProjectsActions.UpdateProjectFailure | ProjectsActions.DeleteProject | ProjectsActions.DeleteProjectSuccess | ProjectsActions.DeleteProjectFailure ): ProjectsState { switch (action.type) { case ProjectsActions.ProjectsActionTypes.GetAllProjects: { return { ...state, allProjectsLoading: true, allProjectsError: null }; } case ProjectsActions.ProjectsActionTypes.GetAllProjectsSuccess: { return adapter.addAll(action.payload.projects, { ...state, allProjectsLoading: false, allProjectsError: null }); } case ProjectsActions.ProjectsActionTypes.GetAllProjectsFailure: { return { ...state, allProjectsLoading: false, allProjectsError: action.payload.error }; } case ProjectsActions.ProjectsActionTypes.GetProject: { return { ...state, projectLoading: true, projectError: null }; } case ProjectsActions.ProjectsActionTypes.GetProjectSuccess: { return adapter.addOne(action.payload.project, { ...state, projectLoading: false, projectError: null }); } case ProjectsActions.ProjectsActionTypes.GetProjectFailure: { return { ...state, projectLoading: true, projectError: action.payload.error }; } case ProjectsActions.ProjectsActionTypes.CreateProject: { return { ...state, createLoading: true, createError: null }; } case ProjectsActions.ProjectsActionTypes.CreateProjectSuccess: { return adapter.addOne(action.payload.project, { ...state, createLoading: false, createError: null }); } case ProjectsActions.ProjectsActionTypes.CreateProjectFailure: { return { ...state, createLoading: false, createError: action.payload.error }; } case ProjectsActions.ProjectsActionTypes.UpdateProject: { return { ...state, updateLoading: true, updateError: null }; } case ProjectsActions.ProjectsActionTypes.UpdateProjectSuccess: { return adapter.updateOne(action.payload.project, { ...state, updateLoading: false, updateError: null }); } case ProjectsActions.ProjectsActionTypes.UpdateProjectFailure: { return { ...state, updateLoading: false, updateError: action.payload.error }; } case ProjectsActions.ProjectsActionTypes.DeleteProject: { return { ...state, deleteLoading: true, deleteError: null }; } case ProjectsActions.ProjectsActionTypes.DeleteProjectSuccess: { return adapter.removeOne(action.payload.projectId, { ...state, deleteLoading: false, deleteError: null }); } case ProjectsActions.ProjectsActionTypes.DeleteProjectFailure: { return { ...state, deleteLoading: false, deleteError: action.payload.error }; } default: { return state; } } } export const selectProjectsState = createFeatureSelector<ProjectsState>( 'projects' ); export const selectAllProjects = createSelector( selectProjectsState, adapter.getSelectors().selectAll ); export const selectAllProjectsLoading = createSelector( selectProjectsState, projectsState => projectsState.allProjectsLoading ); export const selectAllProjectsError = createSelector( selectProjectsState, projectsState => projectsState.allProjectsError ); export const selectProjectById = (id: string) => createSelector( selectProjectsState, projectsState => projectsState.entities[id] ); export const selectProjectLoading = createSelector( selectProjectsState, projectsState => { return projectsState.projectLoading; } ); export const selectProjectError = createSelector( selectProjectsState, projectsState => projectsState.projectError ); export const selectCreateProjectLoading = createSelector( selectProjectsState, projectsState => { return projectsState.createLoading; } ); export const selectCreateProjectError = createSelector( selectProjectsState, projectsState => projectsState.createError ); export const selectUpdateProjectLoading = createSelector( selectProjectsState, projectsState => { return projectsState.updateLoading; } ); export const selectUpdateProjectError = createSelector( selectProjectsState, projectsState => projectsState.updateError ); export const selectDeleteProjectLoading = createSelector( selectProjectsState, projectsState => { return projectsState.deleteLoading; } ); export const selectDeleteProjectError = createSelector( selectProjectsState, projectsState => projectsState.deleteError );
giorgiofederici/giorgiofederici-frontend
src/app/website/shared/services/contact/contact.service.ts
import { Injectable } from '@angular/core'; export interface ContactMessage { firstName: string; lastName: string; email: string; message: string; } @Injectable() export class ContactService { constructor() { } sendMessage(contactMessage: ContactMessage): void { console.log('Message sent: ', contactMessage); } }
giorgiofederici/giorgiofederici-frontend
src/app/auth/shared/shared.module.ts
<reponame>giorgiofederici/giorgiofederici-frontend<filename>src/app/auth/shared/shared.module.ts import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ReactiveFormsModule } from '@angular/forms'; // ngRx import { StoreModule } from '@ngrx/store'; import { EffectsModule } from '@ngrx/effects'; // Cookies import { CookieService } from 'ngx-cookie-service'; // Shared import { AuthFormComponent } from './components/auth-form/auth-form.component'; import { reducers } from './reducers'; import { AuthEffects } from './effects/auth.effects'; // Services import { AuthService } from './services/auth/auth.service'; // Guards import { AuthGuard } from './guards/auth.guard'; @NgModule({ imports: [ CommonModule, ReactiveFormsModule, StoreModule.forFeature('auth', reducers), EffectsModule.forFeature([AuthEffects]) ], declarations: [AuthFormComponent], exports: [AuthFormComponent] }) export class SharedModule { // Avoid the creation of many instances of AuthService, because ShareModule is imported in login and register module static forRoot(): ModuleWithProviders { return { ngModule: SharedModule, providers: [AuthService, AuthGuard, CookieService] }; } }
giorgiofederici/giorgiofederici-frontend
src/app/auth/logout/logout.module.ts
import { NgModule } from '@angular/core'; // Material import { MaterialModule } from 'src/app/material/material.module'; // Logout import { LogoutConfirmationDialogComponent } from './components/logout-confirmation-dialog/logout-confirmation-dialog.component'; @NgModule({ imports: [ MaterialModule ], declarations: [ LogoutConfirmationDialogComponent ], entryComponents: [ LogoutConfirmationDialogComponent ] }) export class LogoutModule { }
giorgiofederici/giorgiofederici-frontend
src/app/admin/root/components/admin-footer/admin-footer.component.ts
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'admin-footer', changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './admin-footer.component.html', styleUrls: ['./admin-footer.component.scss'] }) export class AdminFooterComponent {}
giorgiofederici/giorgiofederici-frontend
src/app/auth/shared/guards/auth.guard.ts
<filename>src/app/auth/shared/guards/auth.guard.ts import { CanActivate } from '@angular/router'; import { Injectable } from '@angular/core'; // RxJS import { Store, select } from '@ngrx/store'; import { Observable, of } from 'rxjs'; import { take, tap, filter, switchMap, catchError } from 'rxjs/operators'; // Auth shared import * as fromAuth from '../reducers'; import { UserActions } from '../actions'; import { User } from '../models/user.model'; @Injectable() export class AuthGuard implements CanActivate { user$: Observable<User>; constructor(private store: Store<fromAuth.State>) {} // wrapping the logic so we can .switchMap it getFromStoreOrCookies(): Observable<any> { // return an Observable stream from the store return this.store.pipe( // selecting the user state using a feature selecting select(fromAuth.getLoggedIn), // the tap() operator allow for a side effect, at this point, // I'm checking if the user property exists in my // Store slice of state tap((loggedIn: boolean) => { // if there is no user, dispatch an action to check the cookies (jwt auth) if (!loggedIn) { this.store.dispatch(new UserActions.IsLoggedIn()); } }), filter((loggedIn: boolean) => loggedIn), // which if loggedIn is false, we will never .take() // this is the same as .first() which will only // take 1 value from the Observable then complete // which does our unsubscribing, technically. take(1) ); } canActivate(): Observable<boolean> { // return our Observable stream from above return this.getFromStoreOrCookies().pipe( // if it was successful, we can return Observable.of(true) switchMap(() => of(true)), // otherwise, something went wrong catchError(() => of(false)) ); } }
giorgiofederici/giorgiofederici-frontend
src/app/website/root/components/website-clip-text/website-clip-text.component.ts
import { Component, Input, ChangeDetectionStrategy, ViewChild, ElementRef, AfterViewInit, QueryList, ViewChildren, OnDestroy, OnInit } from '@angular/core'; import { style, animate, AnimationBuilder, AnimationPlayer } from '@angular/animations'; import { timer, Observable, Subscription } from 'rxjs'; @Component({ selector: 'website-clip-text', changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './website-clip-text.component.html', styleUrls: ['./website-clip-text.component.scss'] }) export class WebsiteClipTextComponent implements OnInit, AfterViewInit, OnDestroy { @ViewChild('textContainer', { static: false }) textContainer: QueryList< ElementRef >; @ViewChild('wordsWrapper', { static: false }) wordsWrapper: ElementRef; @ViewChildren('htmlTextLines') htmlTextLines: QueryList<ElementRef>; textLines: string[]; animationOptions: any; animationPlayer: AnimationPlayer; timer$: Observable<number>; subTimer: Subscription; constructor(private animationBuilder: AnimationBuilder) {} ngOnInit() { this.textLines = [ 'Engineer', 'Developer', 'Freelance', 'Code Teacher', 'IT Coach', 'Gamer' ]; this.animationOptions = { animationDelay: 0, revealDuration: 800 }; this.timer$ = timer(this.animationOptions.animationDelay); } ngAfterViewInit() { // Initialise clip text animation this.animateTextLine(); } ngOnDestroy() { this.animationPlayer.pause(); this.subTimer.unsubscribe(); } private animateTextLine(): void { const newWidth = this.wordsWrapper.nativeElement.offsetWidth + 10 + 'px'; this.wordsWrapper.nativeElement.style.width = newWidth; // Trigger animation this.subTimer = this.timer$.subscribe(() => { this.hideTextLine(); }); /* setTimeout(() => { this.hideTextLine(); }, this.animationOptions.animationDelay); */ } private hideTextLine() { const textLine: ElementRef = this.findVisibleTextLine(); const nextTextLine: ElementRef = this.takeNext(textLine); const myAnimation = this.animationBuilder.build([ style('*'), animate(this.animationOptions.revealDuration, style({ width: '2px' })) ]); // use the returned factory object to create a player this.animationPlayer = myAnimation.create( this.wordsWrapper.nativeElement, {} ); this.animationPlayer.onDone(() => { this.switchTextLine(textLine, nextTextLine); this.showTextLine(nextTextLine); }); this.animationPlayer.play(); } private findVisibleTextLine(): ElementRef { return this.htmlTextLines.find(textLine => { return textLine.nativeElement.classList.contains('is-visible'); }); } private takeNext(textLine: ElementRef): ElementRef { const htmlTextLinesArr = this.htmlTextLines.toArray(); for (let i = 0; i < htmlTextLinesArr.length; i++) { const htmlTextLine = htmlTextLinesArr[i]; if (htmlTextLine.nativeElement.id === textLine.nativeElement.id) { if (i === this.htmlTextLines.length - 1) { return htmlTextLinesArr[0]; } else { return htmlTextLinesArr[++i]; } } } } private showTextLine(textLine: ElementRef): void { const myAnimation = this.animationBuilder.build([ style('*'), animate( this.animationOptions.revealDuration, style({ width: textLine.nativeElement.offsetWidth + 10 + 'px' }) ) ]); // use the returned factory object to create a player this.animationPlayer = myAnimation.create( this.wordsWrapper.nativeElement, {} ); this.animationPlayer.onDone(() => { setTimeout(() => { this.hideTextLine(); }, this.animationOptions.revealDuration); }); this.animationPlayer.play(); } private switchTextLine( oldTextLine: ElementRef, newTextLine: ElementRef ): void { oldTextLine.nativeElement.classList.remove('is-visible'); oldTextLine.nativeElement.classList.add('is-hidden'); newTextLine.nativeElement.classList.remove('is-hidden'); newTextLine.nativeElement.classList.add('is-visible'); } }
giorgiofederici/giorgiofederici-frontend
src/app/root/containers/app/app.component.ts
import { Component, OnInit } from '@angular/core'; // RxJs import { Observable } from 'rxjs'; // NgRx import { Store, select } from '@ngrx/store'; // Auth import * as fromAuth from '../../../auth/shared/reducers'; import { User } from 'src/app/auth/shared/models/user.model'; import { UserActions } from 'src/app/auth/shared/actions'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { user$: Observable<User>; constructor(private store: Store<fromAuth.State>) {} ngOnInit() { // this.user$ = this.store.pipe(select(fromAuth.getUser)); // this.store.dispatch(new UserActions.GetUser()); } }
giorgiofederici/giorgiofederici-frontend
src/app/admin/shared/reducers/skills/skills.reducer.ts
<filename>src/app/admin/shared/reducers/skills/skills.reducer.ts // NgRx import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity'; import { createFeatureSelector, createSelector } from '@ngrx/store'; // Actions import { SkillsActions } from '../../actions/skills'; // Models import { Skill } from '../../models/skills/skill.model'; export interface SkillsState extends EntityState<Skill> { allSkillsLoading: boolean; allSkillsError: string | null; skillLoading: boolean; skillError: string | null; createLoading: boolean; createError: string | null; updateLoading: boolean; updateError: string | null; deleteLoading: boolean; deleteError: string | null; } export const adapter: EntityAdapter<Skill> = createEntityAdapter<Skill>({ selectId: skill => skill._id }); export const initialSkillsState: SkillsState = adapter.getInitialState({ allSkillsLoading: false, allSkillsError: null, skillLoading: false, skillError: null, createLoading: false, createError: null, updateLoading: false, updateError: null, deleteLoading: false, deleteError: null }); export function skillsReducer( state = initialSkillsState, action: | SkillsActions.GetAllSkills | SkillsActions.GetAllSkillsSuccess | SkillsActions.GetAllSkillsFailure | SkillsActions.GetSkill | SkillsActions.GetSkillSuccess | SkillsActions.GetSkillFailure | SkillsActions.CreateSkill | SkillsActions.CreateSkillSuccess | SkillsActions.CreateSkillFailure | SkillsActions.UpdateSkill | SkillsActions.UpdateSkillSuccess | SkillsActions.UpdateSkillFailure | SkillsActions.DeleteSkill | SkillsActions.DeleteSkillSuccess | SkillsActions.DeleteSkillFailure ): SkillsState { switch (action.type) { case SkillsActions.SkillsActionTypes.GetAllSkills: { return { ...state, allSkillsLoading: true, allSkillsError: null }; } case SkillsActions.SkillsActionTypes.GetAllSkillsSuccess: { return adapter.addAll(action.payload.skills, { ...state, allSkillsLoading: false, allSkillsError: null }); } case SkillsActions.SkillsActionTypes.GetAllSkillsFailure: { return { ...state, allSkillsLoading: false, allSkillsError: action.payload.error }; } case SkillsActions.SkillsActionTypes.GetSkill: { return { ...state, skillLoading: true, skillError: null }; } case SkillsActions.SkillsActionTypes.GetSkillSuccess: { return adapter.addOne(action.payload.skill, { ...state, skillLoading: false, skillError: null }); } case SkillsActions.SkillsActionTypes.GetSkillFailure: { return { ...state, skillLoading: true, skillError: action.payload.error }; } case SkillsActions.SkillsActionTypes.CreateSkill: { return { ...state, createLoading: true, createError: null }; } case SkillsActions.SkillsActionTypes.CreateSkillSuccess: { return adapter.addOne(action.payload.skill, { ...state, createLoading: false, createError: null }); } case SkillsActions.SkillsActionTypes.CreateSkillFailure: { return { ...state, createLoading: false, createError: action.payload.error }; } case SkillsActions.SkillsActionTypes.UpdateSkill: { return { ...state, updateLoading: true, updateError: null }; } case SkillsActions.SkillsActionTypes.UpdateSkillSuccess: { return adapter.updateOne(action.payload.skill, { ...state, updateLoading: false, updateError: null }); } case SkillsActions.SkillsActionTypes.UpdateSkillFailure: { return { ...state, updateLoading: false, updateError: action.payload.error }; } case SkillsActions.SkillsActionTypes.DeleteSkill: { return { ...state, deleteLoading: true, deleteError: null }; } case SkillsActions.SkillsActionTypes.DeleteSkillSuccess: { return adapter.removeOne(action.payload.skillId, { ...state, deleteLoading: false, deleteError: null }); } case SkillsActions.SkillsActionTypes.DeleteSkillFailure: { return { ...state, deleteLoading: false, deleteError: action.payload.error }; } default: { return state; } } } export const selectSkillsState = createFeatureSelector<SkillsState>('skills'); export const selectAllSkills = createSelector( selectSkillsState, adapter.getSelectors().selectAll ); export const selectAllSkillsLoading = createSelector( selectSkillsState, skillsState => skillsState.allSkillsLoading ); export const selectAllSkillsError = createSelector( selectSkillsState, skillsState => skillsState.allSkillsError ); export const selectSkillById = (id: string) => createSelector( selectSkillsState, skillsState => skillsState.entities[id] ); export const selectSkillLoading = createSelector( selectSkillsState, skillsState => { return skillsState.skillLoading; } ); export const selectSkillError = createSelector( selectSkillsState, skillsState => skillsState.skillError ); export const selectCreateSkillLoading = createSelector( selectSkillsState, skillsState => { return skillsState.createLoading; } ); export const selectCreateSkillError = createSelector( selectSkillsState, skillsState => skillsState.createError ); export const selectUpdateSkillLoading = createSelector( selectSkillsState, skillsState => { return skillsState.updateLoading; } ); export const selectUpdateSkillError = createSelector( selectSkillsState, skillsState => skillsState.updateError ); export const selectDeleteSkillLoading = createSelector( selectSkillsState, skillsState => { return skillsState.deleteLoading; } ); export const selectDeleteSkillError = createSelector( selectSkillsState, skillsState => skillsState.deleteError );
giorgiofederici/giorgiofederici-frontend
src/app/website/shared/components/list-item/list-item.component.ts
<gh_stars>0 import { Component, Input, ChangeDetectionStrategy, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-list-item', changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './list-item.component.html', styleUrls: ['list-item.component.scss'] }) export class ListItemComponent { toggled = false; @Input() item: any; @Output() remove: EventEmitter<any> = new EventEmitter<any>(); constructor() {} toggle() { this.toggled = !this.toggled; } removeItem() { this.remove.emit(this.item); } getRoute(item: any) { return item.link; } }