repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
yuanliang/Pharos
app/src/components/Home/Home.tsx
import './Home.css' const Home = () => ( <section> <h1>Welcome to Pharos!</h1> </section> ) export default Home
yuanliang/Pharos
app/src/components/Auth/AuthForm.tsx
import { useState, useRef, useContext } from 'react' import { useNavigate } from 'react-router-dom' import AuthContext from '../../store/AuthContext' import Errors from '../Errors/Errors' const AuthForm = () => { const navigate = useNavigate() const usernameRef = useRef<HTMLInputElement | null>(null) const passwordRef = useRef<HTMLInputElement | null>(null) const authContext = useContext(AuthContext) const [loggingIn, setLoggingIn] = useState(true) const [errors, setErrors] = useState({}) const switchModeHandler = () => { setLoggingIn((prevState) => !prevState) setErrors({}) } const endpoint = loggingIn ? '/api/signin' : '/api/signup' async function submitHandler(event: { preventDefault: () => void }) { event.preventDefault() setErrors({}) const usernameValue = usernameRef.current !== null ? usernameRef.current.value : '' const passwordValue = passwordRef.current !== null ? passwordRef.current.value : '' try { const response = await fetch(endpoint, { method: 'POST', body: JSON.stringify({ Username: usernameValue, Password: <PASSWORD> }), headers: { 'Access-Control-Allow-Headers': 'POST, GET, OPTIONS', 'Content-type': 'application/json' } }) const data = await response.json() if (!response.ok) { const errorText = loggingIn ? 'Login failed' : 'Sign up failed' if (!Object.prototype.hasOwnProperty.call(data, 'error')) { throw new Error(errorText) } if (typeof data.error === 'string') { setErrors({ unknown: data.error }) } else { setErrors(data.error) } } else { authContext.login(data.jwt) navigate('/') } } catch (error: any) { // TODO: error Types setErrors({ error: error.message }) } } const header = loggingIn ? 'Login' : 'Sign up' const mainButtonText = loggingIn ? 'Login' : 'Create account' const switchModeButtonText = loggingIn ? 'Create new account' : 'Login with existing account' const errorContent = Object.keys(errors).length === 0 ? null : Errors(errors) return ( <section> <h1 className='text-center'>{header}</h1> <div className='container w-50'> <form onSubmit={submitHandler}> <div className='form-group pb-3'> <label htmlFor='username'> Username <input id='username' type='text' className='form-control' required ref={usernameRef} /> </label> </div> <div className='form-group pb-3'> <label htmlFor='password'> Password <input id='password' type='password' className='form-control' required ref={passwordRef} /> </label> </div> <div className='pt-3 d-flex justify-content-between'> <button type='submit' className='btn btn-success'> {mainButtonText} </button> <button type='button' className='btn btn-link' onClick={switchModeHandler}> {switchModeButtonText} </button> </div> </form> {errorContent} </div> </section> ) } export default AuthForm
yuanliang/Pharos
app/src/components/Errors/Errors.tsx
<reponame>yuanliang/Pharos const Errors = (errors: any) => { const errorList: any[] = [] console.log(errors) // eslint-disable-next-line react/destructuring-assignment Object.keys(errors).forEach((key: any) => errorList.push(errors[key])) return ( <div className='mt-3'> {errorList.map((error) => ( <p className='alert alert-danger'>{error}</p> ))} </div> ) } export default Errors
yuanliang/Pharos
app/src/components/Posts/PostForm.tsx
import { useState, useContext, useEffect, useCallback } from 'react' import AuthContext from '../../store/AuthContext' import Errors from '../Errors/Errors' const PostForm = (props: any) => { const authContext = useContext(AuthContext) const [titleValue, setTitleValue] = useState('') const [contentValue, setContentValue] = useState('') const [errors, setErrors] = useState({}) const { post, post: { Title, Content, ID }, onAddPost, onEditPost } = props const populateFields = useCallback(() => { if (post) { setTitleValue(Title) setContentValue(Content) } }, [Content, Title, post]) useEffect(() => { populateFields() }, [populateFields]) async function submitHandler(event: { preventDefault: () => void }) { event.preventDefault() setErrors({}) try { const method = onEditPost ? 'PUT' : 'POST' const body = { Title: titleValue, Content: contentValue, ID: '' } if (onEditPost) { body.ID = ID } const response = await fetch('api/posts', { method, body: JSON.stringify(body), headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${authContext.token}` } }) const data = await response.json() if (!response.ok) { const errorText = 'Failed to add new post.' if (!Object.prototype.hasOwnProperty.call(data, 'error')) { throw new Error(errorText) } if (typeof data.error === 'string') { setErrors({ unknown: data.error }) } else { setErrors(data.error) } } else { setTitleValue('') setContentValue('') if (onAddPost) { onAddPost(data.data) } if (onEditPost) { onEditPost(data.data) } } } catch (error: any) { setErrors({ error: error.message }) } } const titleChangeHandler = (event: any) => { setTitleValue(event.target.value) } const contentChangeHandler = (event: any) => { setContentValue(event.target.value) } const errorContent = Object.keys(errors).length === 0 ? null : Errors(errors) const submitButtonText = onEditPost ? 'Update Post' : 'Add Post' return ( <section> <div className='container w-75 pb-4'> <form onSubmit={submitHandler}> <div className='form-group pb-3'> <label htmlFor='title'> Title <input id='title' type='text' className='form-control' required value={titleValue} onChange={titleChangeHandler} /> </label> </div> <div className='form-group pb-3'> <label htmlFor='content'> Content <textarea id='content' className='form-control' rows={5} required value={contentValue} onChange={contentChangeHandler} /> </label> </div> <button type='submit' className='btn btn-success'> {submitButtonText} </button> </form> {errorContent} </div> </section> ) } export default PostForm
yuanliang/Pharos
app/src/App.tsx
import { useContext } from 'react' import { Routes, Route, Navigate } from 'react-router-dom' import Layout from './components/Layout/Layout' import HomePage from './pages/HomePage' import AuthPage from './pages/AuthPage' import PostsPage from './pages/PostsPage' import AuthContext from './store/AuthContext' import './App.css' const App = () => { const authContext = useContext(AuthContext) const { loggedIn } = authContext return ( <Layout> <Routes> <Route path='/' element={<HomePage />} /> {!loggedIn && <Route path='/auth' element={<AuthPage />} />} <Route path='/posts' element={loggedIn ? <PostsPage /> : <Navigate to='/auth' />} /> <Route path='*' element={<Navigate to='/auth' />} /> </Routes> </Layout> ) } export default App
GZH-INVESTER/zhaoxin-2020-be
app/controller/place.ts
<gh_stars>0 const Controller = require('../core/base'); export default class PlaceController extends Controller { async createPlace(){ const { ctx, service, app } = this if (!this.isLogged()) return const { campus , location} = ctx.request.body const createRule = {campus:'myCampus',location:'myLocation'} let errs = app.validator.validate(createRule,ctx.request.body); if(errs){ this.fail(errs) return } const newPlace=await service.place.createPlace(campus,location) if(newPlace){ this.success(newPlace) } return } async updatePlace(){ const { ctx, service, app } = this if (!this.isLogged()) return const {id, campus , location} = ctx.request.body const createRule = {id:'myId',campus:'myCampus',location:'myLocation'} let errs = app.validator.validate(createRule,ctx.request.body); if(errs){ this.fail(errs) return } const place=await service.place.updatePlace(id,campus,location) if(place){ this.success(place) } } async deletePlace(){ const { ctx, service, app } = this if (!this.isLogged()) return const id = Number(ctx.params.id) let errs = app.validator.validate({id:'myId'},{id}); if(errs){ this.fail(errs) return } const place=await service.place.deletePlace(id) if(place){ ctx.body={ success:1 } } return } }
GZH-INVESTER/zhaoxin-2020-be
app/service/itime.ts
<reponame>GZH-INVESTER/zhaoxin-2020-be import { Service } from 'egg'; const moment = require('moment'); export default class Itime extends Service { //创建时间 async createDate(interviewDatetime: string) { const { ctx } = this const { Itime } = ctx.model const itimeExist = await Itime.findOne({ where: {interviewDatetime} }) if (itimeExist) { ctx.body = { success: 0, errMsg: '时间已存在' } return } var interviewDate = moment(interviewDatetime).format('YYYY-MM-DD'); var interviewTime = moment(interviewDatetime).format('HH:mm:ss'); const id = await (await Itime.create({interviewDate,interviewTime,interviewDatetime })).id const itime = await Itime.findByPk(id) return { itime } } //更新时间 async updateDate(id: number, interviewDatetime: string) { const { ctx } = this const { Itime } = ctx.model const idExist = await Itime.findByPk(id) if (!idExist) { ctx.body = { success: 0, errMsg: '该条时间不存在' } return } const itimeExist = await Itime.findOne({ attributes: ['id'], where: { interviewDatetime } }) if (itimeExist) { ctx.body = { success: 0, errMsg: '时间已存在' } return } var interviewDate = moment(interviewDatetime).format('YYYY-MM-DD'); var interviewTime = moment(interviewDatetime).format('HH:mm:ss'); const status = await Itime.update({interviewDate, interviewTime ,interviewDatetime}, { where: { id } }) if(status){ const itime=await Itime.findByPk(id) return itime } return } //删除时间 async deleteDate(id: number) { const { ctx } = this const { Itime } = ctx.model const idExist = await Itime.findOne({ attributes: ['id'], where: { id, delete: false } }) if (!idExist) { ctx.body = { success: 0, errMsg: '该条时间不存在' } return } const itime = await Itime.destroy({where:{id}}) return itime } }
GZH-INVESTER/zhaoxin-2020-be
typings/app/controller/index.d.ts
<gh_stars>0 // This file is created by egg-ts-helper@1.25.6 // Do not modify this file!!!!!!!!! import 'egg'; import ExportHome from '../../../app/controller/home'; import ExportItime from '../../../app/controller/itime'; import ExportPlace from '../../../app/controller/place'; import ExportUser from '../../../app/controller/user'; declare module 'egg' { interface IController { home: ExportHome; itime: ExportItime; place: ExportPlace; user: ExportUser; } }
GZH-INVESTER/zhaoxin-2020-be
typings/app/model/index.d.ts
<gh_stars>0 // This file is created by egg-ts-helper@1.25.6 // Do not modify this file!!!!!!!!! import 'egg'; import ExportItime from '../../../app/model/itime'; import ExportPlace from '../../../app/model/place'; import ExportQuestion from '../../../app/model/question'; import ExportStudent from '../../../app/model/student'; import ExportTimePlace from '../../../app/model/time-place'; import ExportUser from '../../../app/model/user'; declare module 'egg' { interface IModel { Itime: ReturnType<typeof ExportItime>; Place: ReturnType<typeof ExportPlace>; Question: ReturnType<typeof ExportQuestion>; Student: ReturnType<typeof ExportStudent>; TimePlace: ReturnType<typeof ExportTimePlace>; User: ReturnType<typeof ExportUser>; } }
GZH-INVESTER/zhaoxin-2020-be
app.ts
<filename>app.ts export default (app) => { app.validator.addRule('myPassword', (_rule, value) => { if (typeof value !== 'string') return '密码应为字符串' if (value.length < 6 || value.length > 16) return '密码的长度应在6到16位' return }); app.validator.addRule('myDateTime', (_rule, value) => { var reg = /^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s((([0-1][0-9])|(2?[0-3]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$/; if(!reg.test(value)) return '日期错误或日期格式错误,正确格式为: 2014-01-01 12:00:00 ' return }); app.validator.addRule('myId',(_rule, value) =>{ if (typeof value !== 'number') return 'id应为数字' return }); app.validator.addRule('myCampus',(_rule,value)=>{ if(typeof value!=='number') return 'campus应为数字' if(value !==1 && value!==2) return '校区不存在' }) app.validator.addRule('myLocation',(_rule,value)=>{ if(typeof value!=='string') return '地点应为字符串' if(value.length > 50) return '地点信息长度应在50字以内' }) };
GZH-INVESTER/zhaoxin-2020-be
app/service/user.ts
<filename>app/service/user.ts import { Service } from 'egg'; export default class User extends Service { async login(password:string){ const { ctx } = this const { User } = ctx.model const user = await User.findOne({ where: { id:1 } }) if(!user||user.password!==password){ ctx.body={ success:0, errMsg:'密码错误' } return } return user } }
GZH-INVESTER/zhaoxin-2020-be
typings/app/service/index.d.ts
// This file is created by egg-ts-helper@1.25.6 // Do not modify this file!!!!!!!!! import 'egg'; import ExportItime from '../../../app/service/itime'; import ExportPlace from '../../../app/service/place'; import ExportTest from '../../../app/service/Test'; import ExportUser from '../../../app/service/user'; declare module 'egg' { interface IService { itime: ExportItime; place: ExportPlace; test: ExportTest; user: ExportUser; } }
GZH-INVESTER/zhaoxin-2020-be
app/model/time-place.ts
import { Application } from 'egg'; import { Model, INTEGER, DATE, BOOLEAN } from 'sequelize'; export class TimePlace extends Model { id: number; timeId: number; placeId: number; campus:number; isChosen: boolean; createdAt:string; updatedAt:string static associate: () => any } export default (app: Application) => { TimePlace.init({ id: { type: INTEGER, primaryKey: true, autoIncrement: true }, timeId: { type: INTEGER, field: 'time_id' }, placeId: { type: INTEGER, field: 'place_id' }, campus:INTEGER, isChosen: { type: BOOLEAN, field: 'is_chosen' }, createdAt: { type: DATE, field: 'created_at' }, updatedAt: { type: DATE, field: 'updated_at' }, }, { modelName: 'time_place', //freezeTableName: true, tableName: 'time_places', sequelize: app.model, }) TimePlace.associate = () => { app.model.TimePlace.hasOne(app.model.Student, { foreignKey: 'timeplaceId' }); } return TimePlace; }
GZH-INVESTER/zhaoxin-2020-be
app/model/itime.ts
<reponame>GZH-INVESTER/zhaoxin-2020-be<gh_stars>0 import { Application } from 'egg'; import { Model, INTEGER, DATE,DATEONLY,TIME} from 'sequelize'; export class Itime extends Model { id: number interviewDate:string interviewTime:string interviewDatetime:string createdAt:string updatedAt:string static associate: ()=>any } export default (app: Application) => { Itime.init({ id: { type: INTEGER, primaryKey: true, autoIncrement: true }, interviewDate: {type:DATEONLY,field:'interview_date'}, interviewTime: {type:TIME,field:'interview_time'}, interviewDatetime: {type:DATE,field:'interview_datetime'}, createdAt: { type: DATE, field: 'created_at' }, updatedAt: { type: DATE, field: 'updated_at' }, }, { modelName: 'itime', //freezeTableName: true, tableName: 'itime', sequelize: app.model, }) Itime.associate = () => { app.model.Itime.belongsToMany(app.model.Place,{ through:app.model.TimePlace, foreignKey:'timeId', otherKey:'placeId' }) app.model.Itime.hasMany(app.model.TimePlace,{ foreignKey:'timeId', sourceKey:'id' }) } return Itime; }
GZH-INVESTER/zhaoxin-2020-be
app/model/user.ts
<filename>app/model/user.ts import {Application} from 'egg'; import {Model,INTEGER,STRING,DATE} from 'sequelize'; export class User extends Model{ id:number; password:string; createdAt:string; updatedAt:string } export default(app:Application)=>{ User.init({ id:{type:INTEGER,primaryKey:true,autoIncrement:true}, password:STRING, createdAt:{type:DATE,field:'created_at'}, updatedAt:{type:DATE,field:'updated_at'}, },{ modelName:'user', sequelize:app.model, }) return User; }
GZH-INVESTER/zhaoxin-2020-be
app/core/base.ts
const { Controller } = require('egg'); class BaseController extends Controller { isLogged(){ if(!this.ctx.session.userId){ this.ctx.body={ success:0, errMsg:'未登录' } return } return true } success(data){ this.ctx.body={ success:1, data } } fail(errMsg){ this.ctx.body={ success:0, errMsg } } } module.exports = BaseController;
GZH-INVESTER/zhaoxin-2020-be
app/router.ts
<gh_stars>0 import { Application } from 'egg'; export default (app: Application) => { const { controller, router } = app; router.get('/', controller.home.index); //user router.post('/login',controller.user.login); router.get('/logout', controller.user.logout); router.get('/isLogged', controller.user.isLogged); //datetime router.post('/createDatetime',controller.itime.createDate) router.put('/updateDatetime',controller.itime.updateDate) router.delete('/deleteDate/:id',controller.itime.deleteDate) //place router.post('/createPlace',controller.place.createPlace) router.put('/updatePlace',controller.place.updatePlace) router.delete('/deletePlace/:id',controller.place.deletePlace) };
GZH-INVESTER/zhaoxin-2020-be
config/config.default.ts
<gh_stars>0 import { EggAppConfig, EggAppInfo, PowerPartial } from 'egg'; export default (appInfo: EggAppInfo) => { const config = {} as PowerPartial<EggAppConfig>; // override config from framework / plugin // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + '_123456'; // add your egg config in here config.middleware = []; config.security = { csrf: { enable: false } } config.sequelize = { dialect: 'mysql', host: '127.0.0.1',//ip port: 3306, database: 'zhaoxin', username: 'root', password: '<PASSWORD>', dialectOptions: { dateStrings:true, typeCast(field,next){ if (field.type==="DATETIME"){ return field.string(); } return next(); } }, timezone: '+08:00', //for writing from database }; config.validate = { convert: false, widelyUndefined: true // validateRoot: false, }; // add your special config in here const bizConfig = { sourceUrl: `https://github.com/eggjs/examples/tree/master/${appInfo.name}`, }; // the return config will combines to EggAppConfig return { ...config, ...bizConfig, }; };
GZH-INVESTER/zhaoxin-2020-be
app/service/place.ts
<reponame>GZH-INVESTER/zhaoxin-2020-be<gh_stars>0 import { Service } from 'egg'; export default class Place extends Service { async createPlace(campus: number, location: string) { const { ctx } = this const { Place } = ctx.model const placeExist = await Place.findOne({ attributes: ['id'], where: { campus, location } }) if (placeExist) { ctx.body = { success: 0, errMsg: '地点已存在' } return } const place = await Place.create({ campus, location }) return place } async updatePlace(id: number, campus: number, location: string) { const { ctx } = this const { Place } = ctx.model const idExist = await Place.findByPk(id) if (!idExist) { ctx.body = { success: 0, errMsg: '该条地点不存在或已经被删除' } return } const placeExist = await Place.findOne({ attributes: ['id'], where: { campus, location } }) if (placeExist) { ctx.body = { success: 0, errMsg: '地点已存在' } return } const status = await Place.update({ campus, location }, { where: { id } }) if (status) { const place = await Place.findByPk(id) return place } return } async deletePlace(id: number) { const { ctx } = this const { Place } = ctx.model const idExist = await Place.findByPk(id) if (!idExist) { ctx.body = { success: 0, errMsg: '该条地点不存在或已经被删除' } return } const status = Place.destroy({ where: { id } }) return status } }
GZH-INVESTER/zhaoxin-2020-be
app/controller/user.ts
<reponame>GZH-INVESTER/zhaoxin-2020-be<gh_stars>0 import { Controller } from 'egg'; export default class UserController extends Controller{ async isLogged(){ const {ctx} = this if(ctx.session.userId){ ctx.body={isLogged:1} return } ctx.body={isLogged:0} return } async login(){ const { ctx,app,service} = this const { password } = ctx.request.body const createRule={password:'<PASSWORD>'} let errs = app.validator.validate(createRule, ctx.request.body); if(errs){ if(errs[0].message=='required') errs[0].message='密码不能为空' ctx.body={ success:0, errMsg:errs[0].message } return } const user = await service.user.login(password) if(user){ ctx.session.userId = user.id ctx.body = { success: 1, } } } async logout(){ const {ctx} = this ctx.session.userId=null ctx.body={ success:1 } return } }
GZH-INVESTER/zhaoxin-2020-be
app/model/question.ts
import { Application } from 'egg'; import { Model, INTEGER, STRING, DATE, BOOLEAN } from 'sequelize'; export class Question extends Model { id: number; department: number; isTailored: boolean; description: string; detail: string; createdAt:string updatedAt:string static associate: () => any } export default (app: Application) => { Question.init({ id: { type: INTEGER, primaryKey: true, autoIncrement: true }, department: INTEGER, isTailored:{type: BOOLEAN,field:'is_tailored'}, description: STRING, detail: STRING, createdAt: { type: DATE, field: 'created_at' }, updatedAt: { type: DATE, field: 'updated_at' }, }, { modelName: 'user', sequelize: app.model, }) Question.associate = () => { app.model.Question.hasMany(app.model.Student, { foreignKey: 'questionId', sourceKey: 'id' }) } return Question; }
GZH-INVESTER/zhaoxin-2020-be
app/model/place.ts
<reponame>GZH-INVESTER/zhaoxin-2020-be import { Application } from 'egg'; import { Model, INTEGER, STRING, DATE } from 'sequelize'; export class Place extends Model { id: number; campus:number; location: string; createdAt:string; updatedAt:string; static associate: () => any } export default (app: Application) => { Place.init({ id: { type: INTEGER, primaryKey: true, autoIncrement: true }, campus:INTEGER, location: STRING, createdAt: { type: DATE, field: 'created_at' }, updatedAt: { type: DATE, field: 'updated_at' }, }, { modelName: 'place', sequelize: app.model, }) Place.associate = () => { app.model.Place.belongsToMany(app.model.Itime,{ through:app.model.TimePlace, foreignKey:'placeId', otherKey:'timeId' }) } return Place; }
GZH-INVESTER/zhaoxin-2020-be
app/controller/itime.ts
const Controller = require('../core/base'); export default class ItimeController extends Controller { async createDate() { const { ctx, service, app } = this const { interviewDatetime } = ctx.request.body const createRule = { interviewDatetime: 'myDateTime' } if (!this.isLogged()) return let errs = app.validator.validate(createRule, ctx.request.body); if (errs) { this.fail(errs) return } const newItime = await service.itime.createDate(interviewDatetime) if (newItime) { this.success(newItime) } return } async updateDate() { const { ctx, service, app } = this const { id, interviewDatetime } = ctx.request.body const createRule = { id: 'myId', interviewDatetime: 'myDateTime' } if (!this.isLogged()) return let errs = app.validator.validate(createRule, ctx.request.body); if (errs) { this.fail(errs) return } const itime = await service.itime.updateDate(id, interviewDatetime) if (itime) { this.success(itime) } return } async deleteDate() { const { ctx, service, app } = this const id = Number(ctx.params.id) if (!this.isLogged()) return let errs = app.validator.validate({ id: 'myId' }, { id }); if (errs) { this.fail(errs) return } const itime = await service.itime.deleteDate(id) if (itime) { ctx.body = { success: 1, } } return } }
GZH-INVESTER/zhaoxin-2020-be
app/model/student.ts
import { Application } from 'egg'; import { Model, INTEGER, STRING, DATE, BOOLEAN } from 'sequelize'; export class Student extends Model { id: number; sid: string; name: string; adClass: string; phone: string; email: string; mainDepartment: number; subDepartment: string; mastered: string; wantLearn: string; campus: number; timeplaceId: number; questionId: number; sent: boolean; status: number; score: number; evaluation: string; delete: boolean createdAt:string updatedAt:string deletedAt:string static associate: () => any } export default (app: Application) => { Student.init({ id: { type: INTEGER, primaryKey: true, autoIncrement: true }, sid: STRING, name: STRING, adClass: { type: STRING, field: 'ad_class' }, phone: STRING, email: STRING, mainDepartment: { type: INTEGER, field: 'main_department' }, subDepartment: { type: STRING, field: 'sub_department' }, mastered: STRING, wantLearn: { type: STRING, field: 'want_learn' }, campus: INTEGER, timeplaceId: { type: INTEGER, field: 'timeplace_id' }, questionId: { type: INTEGER, field: 'question_id' }, sent: { type: BOOLEAN, defaultValue: false }, status:INTEGER, score: INTEGER, evaluation: STRING, delete: { type: BOOLEAN, defaultValue: false }, createdAt: { type: DATE, field: 'created_at' }, updatedAt: { type: DATE, field: 'updated_at' }, deletedAt: { type: DATE, field: 'deleted_at' }, }, { modelName: 'user', sequelize: app.model, }) Student.associate = () => { app.model.Student.belongsTo(app.model.TimePlace, { foreignKey: 'timeplaceId', targetKey: 'id' }) app.model.Student.belongsTo(app.model.Question, { foreignKey: 'questionId', targetKey: 'id' }) } return Student; }
pradeepku123/PlaywrightJS
src/resource/user.testdata.ts
export const testUser = { userName: "Katharina_Bernier", password: "<PASSWORD>", };
pradeepku123/PlaywrightJS
src/tests/start.spec.ts
<reponame>pradeepku123/PlaywrightJS import { test, expect } from "@playwright/test"; import { testUser } from "../resource/user.testdata"; test.beforeEach(async ({ page }) => { await page.goto("http://localhost:3000/"); }); test.describe("Test Description", () => { test("login to application", async ({ page }) => { await page.click('input[name="username"]'); await page.fill('input[name="username"]', testUser.userName); await page.click('input[name="password"]'); await page.fill('input[name="password"]', testUser.password); }); test("TC-002 @TC", async ({ page }) => { const status = () => { console.log("Status"); }; status(); }); });
catervpillar/PlayWithUnicam-Games
quiz/quiz-editor/quiz-editor.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { QuizEditorPageRoutingModule } from './quiz-editor-routing.module'; import { QuizEditorPage } from './quiz-editor.page'; import { CreateQuizQuestionPageModule } from '../create-quiz-question/create-quiz-question.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, QuizEditorPageRoutingModule, CreateQuizQuestionPageModule ], declarations: [QuizEditorPage] }) export class QuizEditorPageModule {}
catervpillar/PlayWithUnicam-Games
quiz/services/quiz-logic.service.spec.ts
import { TestBed } from '@angular/core/testing'; import { QuizLogicService } from './quiz-logic.service'; describe('QuizLogicService', () => { let service: QuizLogicService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(QuizLogicService); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
catervpillar/PlayWithUnicam-Games
quiz/create-quiz-question/create-quiz-question.page.ts
<filename>quiz/create-quiz-question/create-quiz-question.page.ts<gh_stars>0 import { Component, Input, OnInit } from '@angular/core'; import { ModalController, NavParams } from '@ionic/angular'; import { QuizQuestion } from '../quiz-question'; @Component({ selector: 'app-create-quiz-question', templateUrl: './create-quiz-question.page.html', styleUrls: ['./create-quiz-question.page.scss'], }) export class CreateQuizQuestionPage implements OnInit { pageTitle = "Nuova domanda"; @Input() newQuizQuestion: QuizQuestion; question: QuizQuestion = new QuizQuestion("", [], "", "", 10, 1); questionCountdown: string = new Date("2022-01-01T00:00:10").toISOString(); constructor(private modalCtrl: ModalController, private navParams: NavParams) { } ngOnInit() { this.newQuizQuestion = this.navParams.get('question'); if (this.newQuizQuestion) { this.pageTitle = "Modifica domanda"; this.question = new QuizQuestion( this.newQuizQuestion.question, [], this.newQuizQuestion.imgUrl, this.newQuizQuestion.videoUrl, this.newQuizQuestion.countdownSeconds, this.newQuizQuestion.score ); this.newQuizQuestion.answers.forEach(a => { this.question.answers.push(a); }) var date = new Date(null); date.setSeconds(this.newQuizQuestion.countdownSeconds); this.questionCountdown = date.toISOString(); } } createQuestion() { var date = new Date(this.questionCountdown); this.question.countdownSeconds = (date.getMinutes() * 60) + date.getSeconds(); if (this.newQuizQuestion) { this.newQuizQuestion = this.question; } else { this.newQuizQuestion = new QuizQuestion(this.question.question, this.question.answers, this.question.imgUrl, this.question.videoUrl, this.question.countdownSeconds, this.question.score); } this.modalCtrl.dismiss(this.newQuizQuestion); } closeModal() { this.modalCtrl.dismiss(); } /** * Fa sì che gli <ion-input> corrispondenti alle domande/risposte di ogni elemento non vengano * renderizzate ad ogni nuova digitazione. * * @param index L'indice dell'elemento che si sta modificando. * @param item * @returns */ trackEditList(index, item) { return index; } addAnswer() { this.question.answers.push(""); } /** * Elimina una data risposta dalla casella selezionata. * @param answerIndex L'indice della risposta da eliminare. */ deleteAnswer(answerIndex) { this.question.answers.splice(answerIndex, 1); } }
catervpillar/PlayWithUnicam-Games
games-components.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { GooseGameEditorComponentModule } from './goose-game/components/goose-game-editor/goose-game-editor.module'; import { MemoryGameEditorPageModule } from './memory-game/components/memory-game-editor/memory-game-editor.module'; import { QuizEditorPageModule } from './quiz/quiz-editor/quiz-editor.module'; @NgModule({ declarations: [], imports: [ CommonModule, GooseGameEditorComponentModule, MemoryGameEditorPageModule, QuizEditorPageModule ], exports: [GooseGameEditorComponentModule, MemoryGameEditorPageModule, QuizEditorPageModule] }) export class GamesComponentsModule { }
catervpillar/PlayWithUnicam-Games
quiz/quiz.page.ts
import { Component, OnInit, Inject, ViewChild, ElementRef, Renderer2, OnDestroy } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { DomController, ModalController } from '@ionic/angular'; import { Timer } from 'src/app/components/timer-components/timer'; import { TimerController } from 'src/app/services/timer-controller/timer-controller.service'; import { LobbyManagerService } from 'src/app/services/lobby-manager/lobby-manager.service'; import { Router } from '@angular/router'; import { ErrorManagerService } from 'src/app/services/error-manager/error-manager.service'; import { HttpClient } from '@angular/common/http'; import { LoginService } from 'src/app/services/login-service/login.service'; import { AlertCreatorService } from 'src/app/services/alert-creator/alert-creator.service'; import { QuizLogicService } from './services/quiz-logic.service'; import { GameLogic } from '../game-logic'; import { QuizQuestion } from './quiz-question'; import { ClassificaPage } from 'src/app/modal-pages/classifica/classifica.page'; import jwt_decode from 'jwt-decode'; @Component({ selector: 'app-quiz', templateUrl: './quiz.page.html', styleUrls: ['./quiz.page.scss'], }) export class QuizPage implements OnInit, OnDestroy { score: number = 0; questionsTotalNumber: number; questions: QuizQuestion[] = []; shuffledAnswers: string[] = []; answeredQuestions: QuizQuestion[] = []; activeQuestion: QuizQuestion; activeQuestionIndex: number; selectedAnswer: string; timerDomanda: Timer = new Timer(30, false, () => { this.setActiveQuestion(); }); disableAnswers = false; toolbarColor: string = 'primary'; amIDone: boolean = false; /** * stringa per mostare il tempo (formato 'min:sec') */ display: String; backgrounds = ['primary', 'secondary', 'tertiary', 'success', 'warning', 'danger', 'medium']; private someoneHasWon = false; info_partita = { codice: null, codice_lobby: null, giocatore_corrente: null, id_gioco: null, info: null, vincitore: null }; lobby = { codice: null, admin_lobby: null, pubblica: false, min_giocatori: 0, max_giocatori: 0, nome: null, link: null, regolamento: null }; private timerInfoPartita; private timerPing; private timerClassifica; private workerTimer = new Worker(new URL('src/app/workers/timer-worker.worker', import.meta.url)); /** * Variabile booleana per indicare se l'utente sta uscendo dalla pagina o no: * * **true** se l'utente sta uscendo dalla pagina * * **false** altrimenti */ isLeavingPage: boolean; /** * Timer che viene avviato quando un giocatore vince */ timerFinale: Timer = new Timer(null, false, () => { this.stopTimer(); this.sendMatchData(); this.showRanking(); }); /** * timer della partita (conteggio dei secondi della partita) */ timerPartita; /** * tempo della partita in secondi */ seconds = 0; /** * Classifica della partita */ classifica: any[] = []; /** * Elenco dei giocatori ancora in gioco */ ancoraInGioco: any[] = []; /** * Giocatore locale */ localPlayer: string; constructor( private domCtrl: DomController, private renderer: Renderer2, private timerCtrl: TimerController, private lobbyManager: LobbyManagerService, private alertCreator: AlertCreatorService, private loginService: LoginService, private http: HttpClient, private errorManager: ErrorManagerService, private router: Router, private modalController: ModalController, private quizLogic: QuizLogicService) { } ngOnInit() { this.isLeavingPage = false; this.ping(); this.loadInfoLobby(); this.initializeTimers(); this.getGameConfig() .then(_ => { return this.loadPlayers() }) .then(_ => { this.setLocalPlayer(); this.questions = this.quizLogic.getQuizQuestions(); this.questionsTotalNumber = this.questions.length; this.setActiveQuestion(); this.startTimer(); this.timerFinale.setTimerTime(60); // this.timerDomanda.startTimer(); }); } ngOnDestroy() { this.quizLogic.reset(); this.stopTimers(); this.timerFinale.stopTimer(); this.isLeavingPage = true; } /** * Fa partire il timer del gioco. */ startTimer() { this.timerPartita = setInterval(() => { this.seconds++; this.display = this.transform(this.seconds); // console.log('secondi trascorsi:', this.seconds); }, 1000); } /** * Trasforma il contatore dei secondi passati in input. * Esso ritornerà infatti il tempo seguendo il formato: * * *"minuti:secondi"* * * @param value la stringa relativa al conteggio passato in input * @returns la stringa del tempo in formato 'min:sec' */ private transform(value) { var minutes = Math.floor(value / 60); var seconds = value - (minutes * 60); var minString: string; var secString: string; if (minutes < 10) minString = "0" + minutes; else minString = "" + minutes; if (seconds < 10) secString = "0" + seconds; else secString = "" + seconds; return minString + ":" + secString; } /** * Inizializza i timer della pagina. */ private initializeTimers() { if (typeof Worker !== 'undefined') { this.workerTimer.onmessage = () => { this.ping(); this.calculateRanking(); this.getInfoPartita(); }; this.workerTimer.postMessage(2000); } else { // Gli Web Worker non sono supportati. this.timerInfoPartita = this.timerCtrl.getTimer(() => { this.getInfoPartita() }, 2000); this.timerPing = this.timerCtrl.getTimer(() => { this.ping() }, 4000); this.timerClassifica = this.timerCtrl.getTimer(() => { this.calculateRanking() }, 2000); } } /** * Ferma i timer della pagina */ private stopTimers() { this.workerTimer.terminate(); this.timerCtrl.stopTimers(this.timerClassifica, this.timerInfoPartita, this.timerPing); } /** * ------------------------------ CHIAMATE REST ------------------------------ */ /** * Carica le informazioni della lobby. */ async loadInfoLobby() { (await this.lobbyManager.loadInfoLobby()).subscribe( async (res) => { this.lobby = res['results'][0]; }, async (res) => { this.handleError(res, 'Impossibile caricare la lobby!'); }); } /** * Effettua la chiamata REST per aggiornare il database con le informazioni passate in input. */ async sendMatchData() { const tokenValue = (await this.loginService.getToken()).value; const toSend = { 'token': tokenValue, 'info_giocatore': { "answered": (this.questionsTotalNumber - this.questions.length), "score": this.score, "time": this.seconds } } this.http.put('/game/save', toSend).subscribe( async (res) => { }, async (res) => { this.handleError(res, 'Invio dati partita fallito'); } ) } /** * Calcolare la classifica in modo dinamico. */ private async calculateRanking() { const token_value = (await this.loginService.getToken()).value; const headers = { 'token': token_value }; this.http.get('/game/status', { headers }).subscribe( async (res) => { this.info_partita = res['results']; this.saveRanking(); }, async (res) => { this.handleError(res, 'Recupero informazioni partita fallito!'); } ); } /** * Effettua la chiamata REST per ottenere le informazioni della partita di tutti i giocatori. */ async getInfoPartita() { if (!this.someoneHasWon) { var button = [{ text: 'Continua a giocare' }]; const token_value = (await this.loginService.getToken()).value; const headers = { 'token': token_value }; this.http.get('/game/status', { headers }).subscribe( async (res) => { this.info_partita = res['results']; // console.log('info_partita', this.info_partita); this.info_partita.info.giocatori.forEach(p => { if (p.info_giocatore.answered == this.questionsTotalNumber) { if (p.username != this.localPlayer) { this.alertCreator.createAlert("Veloce!", p.username + " ha già finito il quiz per primo!", button, true); this.someoneHasWon = true; this.timerFinale.startTimer(); } } }); }, async (res) => { this.handleError(res, 'Recupero informazioni partita fallito!'); } ); } } //TODO commentare getGameConfig(): Promise<void> { return this.quizLogic.initialize() .catch(errorRes => { this.handleError(errorRes, "File di configurazione mancante!"); }); } loadPlayers(): Promise<void> { return this.quizLogic.updatePlayers() .catch(errorRes => { this.handleError(errorRes, "Impossibile caricare i giocatori!"); }); } /** * Fa uscire il giocatore dalla partita. */ leaveMatch() { this.stopTimers(); return new Promise<void>(async (resolve, reject) => { (await this.lobbyManager.abbandonaLobby()).subscribe( async (res) => { this.router.navigateByUrl(this.quizLogic.redirectPath, { replaceUrl: true }); return resolve(); }, async (res) => { this.timerPing = this.timerCtrl.getTimer(() => { this.ping() }, 4000); this.errorManager.stampaErrore(res, 'Abbandono fallito'); return reject('Abbandono fallito'); } ); }) } /** * Effettua l'operazione di ping. */ ping(): Promise<void> { return this.quizLogic.ping() .catch(errorRes => { this.handleError(errorRes, "Ping fallito!"); }); } //TODO commentare terminaPartita(): Promise<void> { return this.quizLogic.terminaPartita(); } /** * Gestisce un errore causato da una chiamata REST e crea un alert * solo se l'utente non sta abbandonando la pagina. * @param res Response della chiamata REST * @param errorText Header dell'alert */ handleError(res, errorText: string) { if (!this.isLeavingPage) { this.stopTimers(); this.router.navigateByUrl(this.quizLogic.redirectPath, { replaceUrl: true }); this.errorManager.stampaErrore(res, errorText); this.isLeavingPage = true; } } /** * Prende il giocatore locale tramite il token e imposta la variabile 'localPlayer'. */ private async setLocalPlayer() { const token = (await this.loginService.getToken()).value; const decodedToken: any = jwt_decode(token); this.localPlayer = decodedToken.username; this.sendMatchData(); } /** * Ferma il timer della partita. */ private stopTimer() { clearInterval(this.timerPartita); } /** * Controlla se l'utente ha indovinato tutte le carte oppure no. * In caso positivo, viene mostrato un alert di fine partita e, successivamente, * la classifica finale. */ private checkEndMatch() { // var button = [{ text: 'Vai alla classifica', handler: () => { this.showRanking(); } }]; var button = [{ text: 'Vedi classifica', handler: () => { } }]; // var button = [{ text: 'Esci', handler: () => { this.leaveMatch() } }]; if (this.answeredQuestions.length == this.questionsTotalNumber) { this.sendMatchData(); this.terminaPartita(); this.alertCreator.createAlert("Complimenti!", "Hai completato il quiz in " + this.display, button, false); this.amIDone = true; this.someoneHasWon = true; this.stopTimer(); this.timerFinale.enabled = false; } } /** * Mostra la classifica finale della partita. * @returns presenta la modal */ private async showRanking() { this.saveRanking(); console.log('classifica', this.classifica); const modal = await this.modalController.create({ component: ClassificaPage, componentProps: { classifica: this.classifica }, cssClass: 'fullscreen' }); modal.onDidDismiss().then(async () => { this.stopTimers(); if (this.localPlayer == this.lobby.admin_lobby) this.router.navigateByUrl('/lobby-admin', { replaceUrl: true }); else this.router.navigateByUrl('/lobby-guest', { replaceUrl: true }); }); return await modal.present(); } /** * Inserisce all'interno di una lista tutti i giocatori con il relativo punteggio. * * Se il giocatore non ha ancora completato il quiz avrà come punteggio "ancora in gioco". * @returns la lista ordinata ottenuta richiamando il metodo 'sortRanking' */ private saveRanking() { // this.classifica.splice(0, this.classifica.length); this.ancoraInGioco.splice(0, this.ancoraInGioco.length); var toSave; this.info_partita.info.giocatori.forEach(p => { if (p.username == this.localPlayer) toSave = { "username": this.localPlayer, "answered": p.info_giocatore.answered, "time": p.info_giocatore.time, "score": p.info_giocatore.score }; else { if (p.info_giocatore.answered == this.questionsTotalNumber) { toSave = { "username": p.username, "answered": p.info_giocatore.answered, "time": p.info_giocatore.time, "score": p.info_giocatore.score } } else { toSave = { "username": p.username, "answered": p.info_giocatore.answered, "time": p.info_giocatore.time, "score": "ancora in gioco" } } } if (toSave.score == "ancora in gioco") this.ancoraInGioco.push(toSave); else { if (toSave.answered == this.questionsTotalNumber) { var isPresent = false; this.classifica.forEach(g => { if (g.username == toSave.username) isPresent = true; }) if (!isPresent) this.classifica.push(toSave); } } }); this.sortRanking(); this.updateScore(); } /** * Ordina la classifica. */ private sortRanking() { this.classifica.sort(function (a, b) { if (a.score == "ancora in gioco" || b.score == "ancora in gioco") return a.time; else { if (a.score == b.score) return a.time - b.time; else return b.score - a.score; } }); } /** * Quando il Timer finale arriva a 0 aggiorna il punteggio dei giocatori che non hanno indovinato tutte le carte, * passando da *"ancora in gioco"* al tempo del * giocatore che ha vinto più il tempo del Timer finale. */ private updateScore() { if (this.classifica.length > 0) { var tempoVittoria = this.classifica[0].time; this.classifica.forEach(giocatore => { if (giocatore.time >= (tempoVittoria + this.timerFinale.getTimerTime()) - 1) giocatore.punteggio = this.transform(giocatore.time); }); } } // /** // * Ritorna la lista delle carte, prendendole dal service 'gameLogic' // * @returns la lista delle carte utilizzate in partita // */ // getQuizQuestions() { // return this.quizLogic.getQuizQuestions(); // } /** * Chiede all'utente la conferma di abbandonare la partita */ confirmLeaveMatch() { this.alertCreator.createConfirmationAlert('Sei sicuro di voler abbandonare la partita?', async () => { this.leaveMatch(); }); } // METODI GIOCO------------------- setActiveQuestion() { if (this.questions.length > 0) { this.selectedAnswer = null; this.disableAnswers = false; // PER SELEZIONARE LA DOMANDA RANDOMICAMENTE // this.activeQuestionIndex = Math.floor(Math.random() * this.questions.length); // this.activeQuestion = this.questions[this.activeQuestionIndex]; // PER ANDARE IN ORDINE this.activeQuestion = this.questions.splice(0, 1)[0]; this.setAnswers(); this.shuffleAnswers(); this.toolbarColor = this.backgrounds[Math.floor(Math.random() * this.backgrounds.length)]; this.timerDomanda.setTimerTime(this.activeQuestion.countdownSeconds); this.timerDomanda.startTimer(); } } /** * Inserisce le risposte di una determinata domanda all'interno dell'array 'shuffledAnswers' */ setAnswers() { this.shuffledAnswers = []; for (let index = 0; index < this.activeQuestion.answers.length; index++) { this.shuffledAnswers.push(this.activeQuestion.answers[index]); } } /** * Mescola le domande da mostrare sulla modal */ shuffleAnswers() { for (var i = this.shuffledAnswers.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = this.shuffledAnswers[i]; this.shuffledAnswers[i] = this.shuffledAnswers[j]; this.shuffledAnswers[j] = temp; } } selectAnswer(answer: string) { this.timerDomanda.stopTimer(); this.selectedAnswer = answer; this.disableAnswers = true; if (this.selectedAnswer == this.activeQuestion.answers[0]) { this.score += this.activeQuestion.score; } // SE LA DOMANDA ERA STATA SELEZIONATA RANDOMICAMENTE // this.questions.splice(this.activeQuestionIndex, 1).forEach(q => { // this.answeredQuestions.push(q); // }); // SE LA DOMANDA ERA STATA PRESA IN ORDINE this.answeredQuestions.push(this.activeQuestion); this.sendMatchData(); setTimeout(() => { if (this.questions.length > 0) this.setActiveQuestion(); this.checkEndMatch(); }, 3000); } }
catervpillar/PlayWithUnicam-Games
quiz/create-quiz-question/create-quiz-question.module.ts
<gh_stars>0 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { CreateQuizQuestionPageRoutingModule } from './create-quiz-question-routing.module'; import { CreateQuizQuestionPage } from './create-quiz-question.page'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, CreateQuizQuestionPageRoutingModule ], declarations: [CreateQuizQuestionPage] }) export class CreateQuizQuestionPageModule {}
catervpillar/PlayWithUnicam-Games
quiz/quiz-editor/quiz-editor.page.ts
import { Component, Input, OnInit } from '@angular/core'; import { ModalController } from '@ionic/angular'; import { GameEditorComponent } from 'src/app/components/game-editor/game-editor.component'; import { AlertCreatorService } from 'src/app/services/alert-creator/alert-creator.service'; import { CreateQuizQuestionPage } from '../create-quiz-question/create-quiz-question.page'; import { QuizQuestion } from '../quiz-question'; @Component({ selector: 'app-quiz-editor', templateUrl: './quiz-editor.page.html', styleUrls: ['./quiz-editor.page.scss'], }) export class QuizEditorPage implements OnInit, GameEditorComponent { questions: QuizQuestion[] = []; bulkEdit = false; edit = {}; /** * Il valore della variabile config viene ottenuto dal component padre di questo editor. */ @Input('config') config: any = {}; constructor(private alertCreator: AlertCreatorService, private modalCtrl: ModalController) { } ngOnInit() { if (this.config.questions) { this.config.questions.forEach(question => { this.questions.push( new QuizQuestion( question.question, question.answers, question.img_url, question.video_url, question.countdown_seconds, question.score )); }); } } /** * Abilita il selezionamento multiplo degli elementi per l'eliminazione. */ toggleBulkEdit() { this.bulkEdit = !this.bulkEdit; this.edit = {}; } /** * Controlla se ci sono carte selezionate tramite le checkbox. * * @returns true se almeno un elemento è selezionato, false altrimenti */ checkSelectedQuestions() { var selected = false; let keys = Object.keys(this.edit); while (keys.length) { if (this.edit[keys.pop()]) selected = true; } return selected; } /** * Elimina le carte selezionate. */ deleteSelectedQuestions() { let toDelete = Object.keys(this.edit); const indexesToDelete = toDelete.filter(index => this.edit[index]).map(key => +key); while (indexesToDelete.length) { const i = indexesToDelete.pop(); this.questions.splice(i, 1); if (this.config.questions) this.config.questions.splice(i, 1); } } /** * Se la selezione caselle è abilitata, elimina solo le carte selezionate, se ve ne sono, * altrimenti mostra un errore. */ bulkDelete() { if (this.bulkEdit) { if (this.edit && Object.keys(this.edit).length != 0 && this.edit.constructor === Object && this.checkSelectedQuestions()) this.alertCreator.createConfirmationAlert("Sei sicuro di voler eliminare le domande selezionate?", () => { this.deleteSelectedQuestions(); this.toggleBulkEdit(); }); else this.alertCreator.createInfoAlert('Errore', 'Seleziona prima qualche elemento!'); } } /** * Apre la modal per la creazione di una nuova carta. */ async addQuestion() { const modal = await this.modalCtrl.create({ component: CreateQuizQuestionPage, cssClass: 'create-lobby' }); modal.onDidDismiss().then((data) => { const newQuestion = data['data']; if (newQuestion) { this.questions.push(newQuestion); if (!this.config.questions) this.config.questions = []; this.config.questions.push(newQuestion.getJSON()); } }); await modal.present(); } async editQuestion(question: QuizQuestion, index: number) { if (!this.bulkEdit) { const modal = await this.modalCtrl.create({ component: CreateQuizQuestionPage, componentProps: { question: question }, cssClass: 'lobby-pubbliche' }); modal.onDidDismiss().then((data) => { const newQuizQuestion = data['data']; if (newQuizQuestion) { this.config.questions[index] = newQuizQuestion.getJSON(); this.questions[index] = newQuizQuestion; } }); await modal.present(); } } deleteQuestion(question: QuizQuestion, index: number) { this.questions.splice(index, 1); if (this.config.questions) this.config.questions.splice(index, 1); } }
catervpillar/PlayWithUnicam-Games
quiz/quiz-question.ts
export class QuizQuestion { question: string; answers: string[]; imgUrl: string; videoUrl: string; countdownSeconds: number; score: number; constructor(question: string, answers: string[], imgUrl: string, videoUrl: string, countdownSeconds: number, score: number) { this.question = question; this.answers = answers; this.imgUrl = imgUrl; this.videoUrl = videoUrl; this.countdownSeconds = countdownSeconds; this.score = score; } getJSON() { var json: any = {}; json.question = this.question; json.answers = this.answers; json.img_url = this.imgUrl; json.video_url = this.videoUrl; json.countdown_seconds = this.countdownSeconds; json.score = this.score; return json; } }
catervpillar/PlayWithUnicam-Games
quiz/services/quiz-logic.service.ts
<reponame>catervpillar/PlayWithUnicam-Games<gh_stars>0 import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { ErrorManagerService } from 'src/app/services/error-manager/error-manager.service'; import { LobbyManagerService } from 'src/app/services/lobby-manager/lobby-manager.service'; import { LoginService } from 'src/app/services/login-service/login.service'; import { QuizQuestion } from '../quiz-question'; @Injectable({ providedIn: 'root' }) export class QuizLogicService { config: any; quizQuestions: QuizQuestion[] = []; lobbyPlayers = []; // players: MemoryPlayer[] = []; // currentPlayer: MemoryPlayer; // flippableCards: boolean; redirectPath: string; constructor( private lobbyManager: LobbyManagerService, private router: Router, private errorManager: ErrorManagerService, private loginService: LoginService, private http: HttpClient) { this.loginService.getUserType().then( tipoUtente => { if (tipoUtente) { if (tipoUtente == "ADMIN") this.redirectPath = '/admin/dashboard'; else this.redirectPath = '/player/dashboard'; } } ); } initialize() { this.quizQuestions = []; return new Promise<void>((resolve, reject) => { this.getGameConfig() .then(_ => { return resolve(); }) .catch(error => reject(error)) }); } reset() { this.config = {}; this.quizQuestions = []; this.lobbyPlayers = []; } async ping() { return new Promise<void>(async (resolve, reject) => { (await this.lobbyManager.ping()).subscribe( async (res) => { return resolve(); }, async (res) => { reject(res); } ); }) } getGameConfig() { return new Promise(async (resolve, reject) => { const token_value = (await this.loginService.getToken()).value; const headers = { 'token': token_value }; this.http.get('/game/config', { headers }).subscribe( async (res) => { this.config = res['results'][0].config; this.setQuizQuestions(); this.setPlayers() .then(_ => { return resolve(true); }) .catch(error => { return reject(error) }); }, async (res) => { return reject(res); } ); }); } async updatePlayers() { return new Promise<void>(async (resolve, reject) => { (await this.lobbyManager.getPartecipanti()).subscribe( async (res) => { this.lobbyPlayers = res['results']; // if (this.players.length == 0) // this.setGamePlayers(); return resolve(); }, async (res) => { return reject(res); }); }); } setGamePlayers() { // this.lobbyPlayers.forEach(player => { // const memoryPlayer = new MemoryPlayer(player.username) // this.players.push(memoryPlayer); // }); // this.currentPlayer = this.players[0]; } getCurrentPlayer() { // return this.currentPlayer; } endCurrentPlayerTurn() { // var index = this.players.indexOf(this.currentPlayer); // if (index < (this.players.length - 1)) // this.currentPlayer = this.players[index + 1]; // else this.currentPlayer = this.players[0]; // this.flippableCards = !this.flippableCards; } private setPlayers() { if (this.config.version == "single") { let promise = new Promise((resolve) => { return resolve(true); }); // this.players = this.dataKeeper.getPlayers(); // this.currentPlayer = this.players[0]; return promise; } else { return this.updatePlayers(); } } getQuizQuestions() { return this.quizQuestions; } private setQuizQuestions() { this.config.questions.forEach(q => { this.quizQuestions.push(new QuizQuestion(q.question, q.answers, q.img_url, q.video_url, q.countdown_seconds, q.score)); }); // this.shuffleQuestions(); } private shuffleQuestions() { var currentIndex = this.quizQuestions.length; var temporaryValue, randomIndex; while (currentIndex !== 0) { //TODO: Migliorare algoritmo per mischiare le domande randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = this.quizQuestions[currentIndex]; this.quizQuestions[currentIndex] = this.quizQuestions[randomIndex]; this.quizQuestions[randomIndex] = temporaryValue; } } async terminaPartita() { const tokenValue = (await this.loginService.getToken()).value; const toSend = { 'token': tokenValue } this.http.put('/partita/termina', toSend).subscribe( async (res) => { }, async (res) => { this.errorManager.stampaErrore(res, 'Terminazione partita fallita'); }); } }
iFlameing/WebAssemblyStudio
src/components/Sandbox.tsx
/* Copyright 2018 Mozilla Foundation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import * as React from "react"; import { Split } from "./Split"; import { Project, mimeTypeForFileType, SandboxRun } from "../models"; import { logLn } from "../actions/AppActions"; import appStore from "../stores/AppStore"; interface SandboxWindow extends Window { /** * Creates an object URL to a Blob containing the file's data. */ getFileURL(path: string): string; } export class Sandbox extends React.Component<{}, {}> { container: HTMLDivElement; private setContainer(container: HTMLDivElement) { if (container == null) { return; } this.container = container; } onResizeBegin = () => { this.container.style.pointerEvents = "none"; } onResizeEnd = () => { this.container.style.pointerEvents = "auto"; } onSandboxRun = (e: SandboxRun) => { this.run(e.project, e.src); } componentDidMount() { Split.onResizeBegin.register(this.onResizeBegin); Split.onResizeEnd.register(this.onResizeEnd); appStore.onSandboxRun.register(this.onSandboxRun); } componentWillUnmount() { Split.onResizeBegin.unregister(this.onResizeBegin); Split.onResizeEnd.unregister(this.onResizeEnd); appStore.onSandboxRun.unregister(this.onSandboxRun); } run(project: Project, src: string) { const iframe = document.createElement("iframe"); iframe.className = "sandbox"; iframe.src = URL.createObjectURL(new Blob([src], { type: "text/html" })); if (this.container.firstChild) { this.container.removeChild(this.container.firstChild); } this.container.appendChild(iframe); const contentWindow = iframe.contentWindow as SandboxWindow; const logger = { logLn, }; // Hijack Console contentWindow.console.log = (log => function() { logger.logLn(Array.prototype.join.call(arguments)); log.apply(contentWindow.console, arguments); })(contentWindow.console.log); contentWindow.console.info = (info => function() { logger.logLn(Array.prototype.join.call(arguments), "info"); info.apply(contentWindow.console, arguments); })(contentWindow.console.info); contentWindow.console.warn = (warn => function() { logger.logLn(Array.prototype.join.call(arguments), "warn"); warn.apply(contentWindow.console, arguments); })(contentWindow.console.warn); contentWindow.console.error = (error => function() { logger.logLn(Array.prototype.join.call(arguments), "error"); logger.logLn(Array.prototype.join.call(["Failed to fetch:https://localhost:28843/out/main.wsm"]),"error"); error.apply(contentWindow.console, arguments); })(contentWindow.console.error); // Hijack fetch contentWindow.fetch = (input: string, init?: RequestInit) => { const url = new URL(input, "http://example.org/src/main.html"); const file = project.getFile(url.pathname.substr(1)); if (file) { return Promise.resolve( new Response(file.getData(), { status: 200, statusText: "OK", headers: { "Content-Type": mimeTypeForFileType(file.type) } }) ); } return fetch(input, init); }; contentWindow.getFileURL = (path: string) => { const file = project.getFile(path); if (!file) { logger.logLn(`Cannot find file ${path}`, "error"); return; } const blob = new Blob([file.getData()], { type: mimeTypeForFileType(file.type) }); return window.URL.createObjectURL(blob); }; const ready = new Promise((resolve: (window: Window) => any) => { (iframe as any).onready = () => { resolve(contentWindow); }; }); } render() { return <div className="fill" ref={(ref) => this.setContainer(ref)} />; } }
iFlameing/WebAssemblyStudio
tests/components/NewProjectDialog/NewProjectDialog.spec.tsx
<reponame>iFlameing/WebAssemblyStudio /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ import "jest-enzyme"; import * as React from "react"; import { shallow } from "enzyme"; jest.mock("../../../src/utils/fetchTemplates", () => { return { default: async () => JSON.parse(require("fs").readFileSync(__dirname + "/templates.json").toString()), }; }); jest.mock("../../../src/service", () => { return { Service: { compileMarkdownToHtml(md) { return `<pre>${md}</pre>`; }, }, }; }); jest.mock("../../../src/config", () => { return { default: async () => { return { serviceUrl: "", clang: "", rustc: "", templates: "" }; }, }; }); import { NewProjectDialog, Template } from "../../../src/components/NewProjectDialog"; const createButtonIndex = 1; const cancelButtonIndex = 0; async function promiseWait(count) { return count > 0 && await Promise.resolve(count - 1).then(promiseWait); } describe("Tests for NewProjectDialog component", () => { const setup = (params: { onCreate?: (template: Template) => void; onCancel?: () => void; }) => { // tslint:disable-next-line const nop = () => {}; return shallow(<NewProjectDialog isOpen={true} onCreate={params.onCreate || nop} onCancel={params.onCancel || nop} />); }; it("NewProjectDialog renders correctly", () => { const dialog = setup({}); expect(dialog.find("ListBox")).toExist(); const buttons = dialog.find("Button"); expect(buttons.length).toBe(2); expect(buttons.at(createButtonIndex)).toHaveProp("label", "Create"); expect(buttons.at(createButtonIndex)).toHaveProp("title", "Create"); expect(buttons.at(cancelButtonIndex)).toHaveProp("label", "Cancel"); expect(buttons.at(cancelButtonIndex)).toHaveProp("title", "Cancel"); }); it("NewProjectDialog calls back onCreate", async () => { let chosenTemplate = null; const dialog = setup({ onCreate(template) { chosenTemplate = template; }, }); { const createButton = dialog.find("Button").at(createButtonIndex); expect(createButton).toHaveProp("isDisabled", true); } await promiseWait(3); // wait on templates loading and md-to-html dialog.update(); { const createButton = dialog.find("Button").at(createButtonIndex); expect(createButton).toHaveProp("isDisabled", false); createButton.simulate("click"); expect(chosenTemplate).toBeTruthy(); } }); it("NewProjectDialog calls back onCancel", () => { let cancelCalled = false; const dialog = setup({ onCancel() { cancelCalled = true; }, }); dialog.find("Button").at(cancelButtonIndex).simulate("click"); expect(cancelCalled).toBeTruthy(); }); });
iFlameing/WebAssemblyStudio
tests/components/Toast/Toasts.spec.tsx
<gh_stars>0 /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ import "jest-enzyme"; import * as React from "react"; import {shallow, mount} from "enzyme"; import {ToastContainer, Toast} from "../../../src/components/Toasts"; import {Button} from "../../../src/components/shared/Button"; import {GoX} from "../../../src/components/shared/Icons"; describe("Tests for Toasts", () => { const setup = () => { return shallow(<ToastContainer/>); }; const message: JSX.Element = <a href="https://webassembly.studio/">Label</a>; it("Default no toast rendered", () => { const wrapper = setup(); expect(wrapper.find(Toast)).toHaveLength(0); }); it("Render Toast with Dismiss Button", () => { const props = { message: <a href="https://webassembly.studio/">Label</a>, onDismiss: Function() }; const toast = shallow(<Toast {...props}/>); const button: ReactWrapper = toast.find(Button).last(); expect(button).toHaveProp("label", "Dismiss"); expect(button).toHaveProp("title", "Dismiss"); expect(button).toHaveProp("customClassName", "button-toast"); expect(button).toHaveProp("icon", <GoX />); expect(button).toHaveProp("onClick", props.onDismiss); }); it("Render ToastContainer Component with Toasts", () => { const wrapper = setup(); for (let i = 1; i <= 2; i++) { wrapper.instance().showToast(message); expect(wrapper.state().toasts.length).toBe(i); wrapper.update(); expect(wrapper.find(Toast)).toHaveLength(i); expect(wrapper.find(Toast).at(i - 1)).toHaveProp("message", message); } }); it("Toast Dismiss", () => { const wrapper = mount(<ToastContainer/>); wrapper.instance().showToast(message); wrapper.update(); wrapper.find(Toast).first().find(Button).last().simulate("click"); expect(wrapper.state().toasts.length).toBe(0); }); });
truongsontn96/hello-world
dist/module.d.ts
import { ExtendQueriesDatasource } from './datasource'; import { ExtendQueriesQueryCtrl } from './query_ctrl'; import { ExtendQueriesConfigCtrl } from './config_ctrl'; export { ExtendQueriesDatasource as Datasource, ExtendQueriesQueryCtrl as QueryCtrl, ExtendQueriesConfigCtrl as ConfigCtrl };
truongsontn96/hello-world
dist/module.ts
<gh_stars>0 import {ExtendQueriesDatasource} from './datasource'; import {ExtendQueriesQueryCtrl} from './query_ctrl'; import {ExtendQueriesConfigCtrl} from './config_ctrl'; export { ExtendQueriesDatasource as Datasource, ExtendQueriesQueryCtrl as QueryCtrl, ExtendQueriesConfigCtrl as ConfigCtrl };
truongsontn96/hello-world
dist/datasource.d.ts
declare var ExtendQueriesDatasource: any; export {ExtendQueriesDatasource};
truongsontn96/hello-world
dist/test/config_ctrl.d.ts
/// <reference path="../../headers/common.d.ts" /> export declare class ExtendQueriesConfigCtrl { static templateUrl: string; current: any; }
felipe2g/moon-ui
src/styles/theme.ts
<filename>src/styles/theme.ts export default { grid: { container: '130rem', gutter: '3.2rem' }, border: { radius: '0.3rem' }, font: { sizes: { xxsmall: '1.4rem', xsmall: '1.6rem', small: '1.8rem', medium: '2.2rem', large: '2.6rem', xlarge: '3.4rem', xxlarge: '5.2rem' } }, colors: { primary: '#298EF7', darkgray: '#121214', lightgray: '#333333', white: '#FFFFFF', lightblue: '#55A8FF', orange: '#FD951F', lightgreen: '#04D361', alertRed: '#C30052', unfocusedBlue: '#A0A3BD' }, spacings: { xxsmall: '0.8rem', xsmall: '1.6rem', small: '2.4rem', medium: '3.2rem', large: '6.0rem', xlarge: '6.4rem', xxlarge: '12.8rem' } }
felipe2g/moon-ui
src/components/Tag/stories.tsx
<reponame>felipe2g/moon-ui<gh_stars>0 import React from 'react' import { Story, Meta } from '@storybook/react/types-6-0' import Tag from '.' export default { title: 'Tag', component: Tag, args: { label: 'Default', backgroundColor: 'red', icon: null, fontColor: 'blue' } } as Meta export const Basic: Story = (args) => <Tag {...args} /> Basic.args = { label: 'Eu sou um comentário!' }
felipe2g/moon-ui
src/components/Comment/styles.ts
<gh_stars>0 import styled from 'styled-components' export const Comment = styled.div` display: block; background-color: #eff0f6; padding: 16px 24px; border-radius: 0 32px 32px 32px; span { color: #4e4b66; font-size: 16px; letter-spacing: 0.75px; line-height: 28px; word-break: break-all; } `
felipe2g/moon-ui
src/components/Comment/index.test.tsx
import Comment from './index' describe('Comment', () => { it('is truthy', () => { expect(Comment).toBeTruthy() }) })
felipe2g/moon-ui
src/components/Tag/index.tsx
<filename>src/components/Tag/index.tsx import React from 'react' import * as S from './styles' // import { FiTag } from 'react-icons/fi' interface Props { backgroundColor: string label: string fontColor: string icon: React.ReactNode } const Tag: React.FC<Props> = ({ backgroundColor, icon, label, fontColor }) => { return ( <S.Wrapper backgroundColor={backgroundColor} fontColor={fontColor} data-testid='tag-container' > {icon} <span>{label}</span> </S.Wrapper> ) } export default Tag
felipe2g/moon-ui
src/components/InputTextarea/index.tsx
<reponame>felipe2g/moon-ui<gh_stars>0 // eslint-disable-next-line no-unused-vars import React, { InputHTMLAttributes } from 'react' import * as S from './styles' interface Props extends InputHTMLAttributes<HTMLInputElement> { name: string color?: string placeholder: string label?: boolean } const InputTextarea: React.FC<Props> = ({ name, label, color, placeholder }) => { return ( <S.TextareaWrapper> <S.Label label={label} htmlFor={name}> {name} </S.Label> <S.InputTextarea name={name} color={color} placeholder={placeholder} /> </S.TextareaWrapper> ) } export default InputTextarea
felipe2g/moon-ui
src/components/Form/index.tsx
<filename>src/components/Form/index.tsx // eslint-disable-next-line no-unused-vars import React, { FormHTMLAttributes } from 'react' import * as S from './styles' interface Props extends FormHTMLAttributes<HTMLFormElement> { children: React.ReactNode } const Form: React.FC<Props> = ({ children, ...props }) => ( <S.FormWrapper {...props}>{children}</S.FormWrapper> ) export default Form
felipe2g/moon-ui
src/components/InputText/index.test.tsx
import InputText from '.' describe('InputText', () => { it('is truthy', () => { expect(InputText).toBeTruthy() }) })
felipe2g/moon-ui
src/components/InputTextarea/styles.ts
import styled from 'styled-components' interface InputTextareaProps { color?: string } interface LabelProps { label?: boolean } export const TextareaWrapper = styled.div` margin: 16px 0; display: flex; flex-direction: column; ` export const Label = styled.label<LabelProps>` display: ${(props) => (props.label ? '' : 'none')}; ` export const InputTextarea = styled.textarea<InputTextareaProps>` width: 100%; color: ${(props) => (props.color ? props.color : '')}; padding: 0.75rem; font-size: 13.3333px; border: 1px solid ${(props) => (props.color ? props.color : '#121214')}; border-radius: 4px; :focus { outline: none; } `
felipe2g/moon-ui
src/components/Form/stories.tsx
<reponame>felipe2g/moon-ui import React from 'react' // eslint-disable-next-line no-unused-vars import { Story, Meta } from '@storybook/react/types-6-0' import Form from '.' import InputText from '../InputText' import InputTextarea from '../InputTextarea' export default { title: 'Form', component: Form, args: { title: 'Title Default', description: 'Description Default' } } as Meta export const Basic: Story = (args) => ( <Form {...args}> <InputText name='Nome' placeholder='Digite aqui seu nome...' label /> <InputTextarea name='Descrição' placeholder='Digite aqui a descrição...' label /> </Form> )
felipe2g/moon-ui
src/components/InputText/stories.tsx
<reponame>felipe2g/moon-ui<filename>src/components/InputText/stories.tsx import React from 'react' // eslint-disable-next-line no-unused-vars import { Story, Meta } from '@storybook/react/types-6-0' import InputText from '.' export default { title: 'InputText', component: InputText, args: { name: 'Nome', color: '#121214', placeholder: 'Digite aqui...', label: true } } as Meta export const Basic: Story = (args) => { return ( <div style={{ width: '100%' }}> <InputText name={args.name} color={args.color} placeholder={args.placeholder} label={args.label} /> </div> ) } Basic.args = { name: 'Nome', color: '#121214', placeholder: 'Digite aqui...', label: true }
felipe2g/moon-ui
src/components/InputTextarea/index.test.tsx
<filename>src/components/InputTextarea/index.test.tsx import InputTextarea from '.' describe('InputTextarea', () => { it('is truthy', () => { expect(InputTextarea).toBeTruthy() }) })
felipe2g/moon-ui
src/components/Button/stories.tsx
import React from 'react' // eslint-disable-next-line no-unused-vars import { Story, Meta } from '@storybook/react/types-6-0' import Button from '.' export default { title: 'Button', component: Button } as Meta export const Primary: Story = (args) => ( <Button btnType='primary' size='default' label='Botão' onClick={() => console.log('clicou')} {...args} /> ) export const Secondary: Story = (args) => ( <Button btnType='secondary' size='default' label='Botão' {...args} /> ) Primary.args = { btnType: 'primary', label: 'Click me', size: 'default' } Secondary.args = { btnType: 'secondary', label: 'Click me', size: 'default' }
felipe2g/moon-ui
src/components/Button/styles.ts
<filename>src/components/Button/styles.ts import styled, { css } from 'styled-components' import theme from '../../styles/theme' interface WrapperProps { btnType: string size: string } export const Wrapper = styled.button<WrapperProps>` ${(props) => props.btnType === 'primary' ? css` background-color: ${theme.colors.primary}; color: ${theme.colors.white}; border: none; :hover { background-color: ${theme.colors.lightblue}; transition: all 0.2s ease 0s; } ` : null}; ${(props) => props.btnType === 'secondary' ? css` background-color: transparent; color: ${theme.colors.primary}; border: 2px solid ${theme.colors.primary}; ` : null}; border-radius: ${theme.border.radius}; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; text-decoration: none; ${(props) => { switch (props.size) { case 'small': return css` height: 30px; min-width: 72px; padding: 0 17px; span { font-size: 14px; font-weight: bold; letter-spacing: 1px; } ` case 'default': return css` height: 36px; min-width: 84px; padding: 0 23px; user-select: none; span { font-size: 16px; font-weight: bold; letter-spacing: 1px; } ` default: return css` height: 42px; padding: 0 29px; min-width: 102px; user-select: none; span { font-size: 16px; font-weight: bold; letter-spacing: 1px; } ` } }} `
felipe2g/moon-ui
src/components/Button/index.tsx
import React from 'react' import * as S from './styles' interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { btnType: 'primary' | 'secondary' label: string size: 'large' | 'default' | 'small' } const Button: React.FC<ButtonProps> = ({ btnType, label, size, ...props }) => ( <S.Wrapper btnType={btnType} size={size} {...props}> <span>{label}</span> </S.Wrapper> ) export default Button
felipe2g/moon-ui
src/components/Comment/index.tsx
<reponame>felipe2g/moon-ui import React from 'react' import * as S from './styles' interface Props { text: string } const Comment: React.FC<Props> = ({ text }) => { return ( <S.Comment> <span>{text}</span> </S.Comment> ) } export default Comment
felipe2g/moon-ui
src/components/InputText/styles.ts
import styled from 'styled-components' interface InputTextProps { color?: string } interface LabelProps { label?: boolean } export const InputTextWrapper = styled.div` margin: 16px 0; ` export const Label = styled.label<LabelProps>` display: ${(props) => (props.label ? '' : 'none')}; ` export const InputText = styled.input<InputTextProps>` width: 100%; color: ${(props) => (props.color ? props.color : '')}; padding: 0.75rem; font-size: 13.3333px; border: 1px solid ${(props) => (props.color ? props.color : '#121214')}; border-radius: 4px; :focus { outline: none; } `
felipe2g/moon-ui
src/index.tsx
import Button from './components/Button' import Comment from './components/Comment' import Form from './components/Form' import InputText from './components/InputText' import InputTextarea from './components/InputTextarea' import Tag from './components/Tag' export { Button, Comment, Form, InputText, InputTextarea, Tag }
felipe2g/moon-ui
src/components/Tag/index.test.tsx
<gh_stars>0 import Tag from './index' describe('Tag', () => { it('is truthy', () => { expect(Tag).toBeTruthy() }) })
felipe2g/moon-ui
example/src/App.tsx
import React from 'react' import { Comment } from 'rogan-ui' import 'rogan-ui/dist/index.css' const App = () => { return <Comment text="Um comentário de teste" /> } export default App
felipe2g/moon-ui
src/components/Tag/styles.ts
import styled from 'styled-components' interface TagProps { backgroundColor: string fontColor: string } export const Wrapper = styled.div<TagProps>` display: inline-flex; justify-content: center; align-items: center; padding: 8px 16px; border-radius: 36px; background-color: ${(props) => props.backgroundColor}; span { color: ${(props) => props.fontColor}; font-size: 13px; margin-left: 8px; user-select: none; } svg { color: ${(props) => props.fontColor}; } `
felipe2g/moon-ui
src/components/Comment/stories.tsx
import React from 'react' import { Story, Meta } from '@storybook/react/types-6-0' import Comment from '.' export default { title: 'Comment', component: Comment, args: { text: 'Default' } } as Meta export const Basic: Story = (args) => <Comment {...args} /> Basic.args = { text: 'Eu sou um comentário!' }
felipe2g/moon-ui
src/components/Form/styles.ts
<reponame>felipe2g/moon-ui<filename>src/components/Form/styles.ts import styled from 'styled-components' export const FormWrapper = styled.form` max-width: 500px; `
felipe2g/moon-ui
src/components/Form/index.test.tsx
<gh_stars>0 import Form from '.' describe('Form', () => { it('is truthy', () => { expect(Form).toBeTruthy() }) })
felipe2g/moon-ui
src/components/InputText/index.tsx
// eslint-disable-next-line no-unused-vars import React, { InputHTMLAttributes } from 'react' import * as S from './styles' interface Props extends InputHTMLAttributes<HTMLInputElement> { name: string color?: string placeholder: string label?: boolean } const InputText: React.FC<Props> = ({ name, label, color, placeholder }) => { console.log('label input text', label) return ( <S.InputTextWrapper> <S.Label label={label} htmlFor={name}> {name} </S.Label> <S.InputText name={name} type='text' color={color} placeholder={placeholder} /> </S.InputTextWrapper> ) } export default InputText
jacobdewey/SensorQuick
Sensor.ts
<reponame>jacobdewey/SensorQuick //% color=#D400D4 weight=124 icon="\uf194" namespace sensor { //% block export function sensorDifference(l: SensorDifferenceDectectionValue, otherMicrobits: number, j: Dimension): number { switch (l) { case SensorDifferenceDectectionValue.a: return input.compassHeading() - otherMicrobits break; case SensorDifferenceDectectionValue.b: return input.lightLevel() - otherMicrobits break; case SensorDifferenceDectectionValue.c: switch (j) { case Dimension.Strength: return input.acceleration(Dimension.Strength) - otherMicrobits break; case Dimension.X: return input.acceleration(Dimension.X) - otherMicrobits break; case Dimension.Y: return input.acceleration(Dimension.Y) - otherMicrobits break; case Dimension.Z: return input.acceleration(Dimension.Z) - otherMicrobits break; } case SensorDifferenceDectectionValue.d: return input.temperature() - otherMicrobits break } } }
jacobdewey/SensorQuick
SensorVar.ts
<reponame>jacobdewey/SensorQuick<filename>SensorVar.ts enum SensorDifferenceDectectionValue { //% block="magnetism" a, //% block="lightLevel" b, //% block="acceleration" c, //% block="temperature" d }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/utilities/utilities.module.ts
/** * Created by <NAME> (<EMAIL>) on 7/18/17. */ import { NgModule } from '@angular/core'; @NgModule({}) export class UtilitiesModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/synopse/synopse-werkzeugleiste/synopse-werkzeugleiste.component.ts
/** * Created by <NAME> (rfbaumgartner) on 05.07.17. */ import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-synopse-werkzeugleiste', templateUrl: 'synopse-werkzeugleiste.component.html', styleUrls: [ 'synopse-werkzeugleiste.component.css' ] }) export class SynopseWerkzeugleisteComponent implements OnInit { @Input() viewMode: string; @Output() viewModeChange: EventEmitter<string> = new EventEmitter<string>(); @Input() showText: boolean; @Output() showTextChange: EventEmitter<boolean> = new EventEmitter<boolean>(); neuladen() { window.location.reload(); } hilfe() { // TODO console.log('Hilfetext ergaenzen'); } ngOnInit() {} }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/textgrid/textgrid.component.ts
/** * Created by retobaumgartner on 21.06.17. */ import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-textgrid', templateUrl: 'textgrid.component.html', styleUrls: [ 'textgrid.component.css' ] }) export class TextgridComponent implements OnChanges { @Input() poems_in_grid: Array<any>; showGrid = true; showCols = false; ngOnChanges(changes: SimpleChanges) { for (let propName in changes) { let chng = changes[ propName ]; this.poems_in_grid = chng.currentValue; } /* for (let propName in changes) { let chng = changes[propName]; let cur = JSON.stringify(chng.currentValue); let prev = JSON.stringify(chng.previousValue); this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`); }*/ // changes.prop contains the old and the new value... } toGrid() { this.showGrid = true; this.showCols = false; } toCols() { this.showGrid = false; this.showCols = true; } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/searchForOneResourceComponent/searchForOneResource.component.ts
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core'; import { Http, Response } from '@angular/http'; import { globalSearchVariableService } from './../globalSearchVariablesService'; @Component({ moduleId: module.id, selector: 'rae-search-for-one-resource', templateUrl: 'searchForOneResource.component.html', styleUrls: [ 'searchForOneResource.component.css' ] }) export class SearchForOneResourceComponent implements OnInit { myProperties: Array<any>; searchResult: Array<any>; selectedResource: string; selectedProperty: string; firstInput: string; secondInput: string; concatenatedString: string; boolOperator: string; encodedURL: string; searchForVal: string; query: string; availableboolOperators = [ {name: 'equal to', operator: 'EQ'}, {name: 'not equal to', operator: '!EQ'}, {name: 'greater than', operator: 'GT'}, {name: 'greater or equal', operator: 'GT_EQ'}, {name: 'lower than', operator: 'LT'}, {name: 'lower or equal than', operator: 'LT_EQ'}, {name: 'exists', operator: 'EXISTS'}, {name: 'match', operator: 'MATCH'}, {name: 'like', operator: 'LIKE'}, {name: '!like', operator: '!LIKE'}, {name: 'match_boolean', operator: 'MATCH_BOOLEAN'} ]; arraySize: number; array = [ 1 ]; @Input() nthResourceSearch: number; @Input() myResources: Array<any>; constructor(private http: Http) { } ngOnInit() { //console.log('This is resource Search nr: ' + this.nthResourceSearch); //if( typeof this.myResources !== 'undefined') { //console.log('ResourceArray: ' + this.myResources[0].label); //} } increaseArrayElement() { this.arraySize = this.array[this.array.length - 1 ]; this.arraySize += 1; this.array.push(this.arraySize); //console.log('ResourceSearch: ' + this.nthResourceSearch + 'Constraint: ' + this.arraySize); } propertyQuery() { //console.log('Property Query for Resource: ' + this.selectedResource); if (this.selectedResource !== undefined) { //console.log('Path to request property:' + globalSearchVariableService.propertyListsQuery); this.encodedURL = encodeURIComponent(this.selectedResource); //console.log('Selected resource:' + this.encodedURL); return this.http.get(globalSearchVariableService.API_URL + globalSearchVariableService.propertyListsQuery + this.encodedURL) .map( (lambda: Response) => { const data = lambda.json(); //console.log(data); return data.properties; } ) .subscribe(response => this.myProperties = response); } } chooseProperty() { //console.log('SearchInstance ' + this.nthResourceSearch + ' chooses property ' + this.selectedProperty); } updateQuerySet(propertyTriple: Array<any>) { //console.log('Event has triggered this function in parent component! Propertytriple: ' + propertyTriple); propertyTriple.push(this.selectedResource); this.sendPropertyTripleBack.emit(propertyTriple); } @Output() sendPropertyTripleBack: EventEmitter<any> = new EventEmitter<any>(); }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/utilities/alphabetical-sorting.service.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche /** * Created by <NAME> (rfbaumgartner) on 24.07.17. */ import { Injectable } from '@angular/core'; @Injectable() export class AlphabeticalSortingService { germanAlphabeticalSortKey(key: string): string { // replace special characters of Latin-1 by base letter and append original string for internal sorting return key .toLowerCase() .replace(/[àáâãäå]/gi, 'a') .replace(/[æ]/gi, 'ae') .replace(/[ç]/gi, 'c') .replace(/[ð]/gi, 'd') .replace(/[èéêë]/gi, 'e') .replace(/[ìíîï]/gi, 'i') .replace(/[òóôõöø]/gi, 'o') .replace(/[ñ]/gi, 'n') .replace(/[ß]/gi, 'ss') .replace(/[ùúûü]/gi, 'u') .replace(/[ýÿ]/gi, 'y') .replace(/[^a-z0-9 ]/gi, '') .concat('\t', key.toLowerCase(), '\t', key); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/fassung/fassung.module.ts
/** * Created by <NAME> (rfbaumgartner) on 05.07.17. */ import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MdButtonModule, MdButtonToggleModule, MdCardModule, MdGridListModule, MdIconModule, MdInputModule, MdListModule } from '@angular/material'; import { BrowserModule } from '@angular/platform-browser'; import { DiplomatischerTextModule } from '../shared/diplomatischer-text/diplomatischer-text.module'; import { FassungRoutingModule } from './fassung-routing.module'; import { ImageFrameModule } from '../shared/image-frame/image-frame.module'; import { RegisterspalteModule } from '../shared/registerspalte/registerspalte.module'; import { FassungBlaetternComponent } from './fassung-blaettern/fassung-blaettern.component'; import { FassungComponent } from './fassung.component'; import { FassungDiplomatischComponent } from './fassung-diplomatisch/fassung-diplomatisch.component'; import { FassungSteckbriefComponent } from './fassung-steckbrief/fassung-steckbrief.component'; import { FassungWeitereComponent } from './fassung-weitere/fassung-weitere.component'; import { FassungWerkzeugleisteComponent } from './fassung-werkzeugleiste/fassung-werkzeugleiste.component'; import { TextComponent } from '../shared/text/text.component'; @NgModule({ imports: [ BrowserModule, DiplomatischerTextModule, FassungRoutingModule, FormsModule, HttpModule, ImageFrameModule, MdButtonModule, MdButtonToggleModule, MdCardModule, MdGridListModule, MdIconModule, MdInputModule, MdListModule, RegisterspalteModule, FassungRoutingModule ], declarations: [ FassungBlaetternComponent, FassungComponent, FassungDiplomatischComponent, FassungSteckbriefComponent, FassungWeitereComponent, FassungWerkzeugleisteComponent, TextComponent ], exports: [ FassungComponent ], providers: [] }) export class FassungModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/statisch/anleitung.component.ts
/** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-anleitung', templateUrl: 'anleitung.component.html' }) export class AnleitungComponent { title = 'Anleitung zur Online-Edition Kuno Raeber'; }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/suche.module.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche /** * Created by <NAME> (<EMAIL>) on 7/21/17. */ import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { MdButtonModule, MdButtonToggleModule, MdCardModule, MdGridListModule, MdIconModule, MdInputModule, MdMenuModule, MdCheckboxModule, MdSelectModule } from '@angular/material'; import { BrowserModule } from '@angular/platform-browser'; import { SucheRoutingModule } from './suche-routing.module'; import { SucheComponent } from './suche.component'; import { TextgridModule } from './textgrid/textgrid.module'; import { SearchForOneResourceModule } from './searchForOneResourceComponent/searchForOneResource.module'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, CommonModule, RouterModule.forChild([ { path: 'suche', component: SucheComponent } ]), SucheRoutingModule, MdButtonModule, MdButtonToggleModule, MdCardModule, MdGridListModule, MdIconModule, MdInputModule, MdMenuModule, MdCheckboxModule, BrowserAnimationsModule, MdSelectModule, TextgridModule, SearchForOneResourceModule ], declarations: [ SucheComponent ], exports: [ SucheComponent ], providers: [] }) export class SucheModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/shared/registerspalte/registerspalte.component.ts
/** * Created by <NAME> (rfbaumgartner) on 27.06.17. */ import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import { ActivatedRoute, Params, Router } from '@angular/router'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import { ExtendedSearch, KnoraProperty } from '../utilities/knora-api-params'; import { AlphabeticalSortingService } from '../utilities/alphabetical-sorting.service'; @Component({ moduleId: module.id, selector: 'rae-registerspalte', templateUrl: 'registerspalte.component.html', styleUrls: [ 'registerspalte.component.css' ], providers: [ AlphabeticalSortingService ] }) export class RegisterspalteComponent implements OnInit { rsEntry: Array<any>; nHits: number; konvolutId: string; konvolutType: string; sortingType: string; private sub: any; constructor(private http: Http, private route: ActivatedRoute, private router: Router, private sortingService: AlphabeticalSortingService) { } ngOnInit() { let searchParams = new ExtendedSearch(); searchParams.filterByRestype = 'http://www.knora.org/ontology/text#Convolute'; searchParams.property = new KnoraProperty('http://www.knora.org/ontology/text#hasTitle', '!EQ', ' '); searchParams.property = new KnoraProperty('http://www.knora.org/ontology/text#hasDescription', '!EQ', ' '); searchParams.showNRows = 500; this.route.params .switchMap((params: Params) => this.http.get(searchParams.toString())) .map(response => response.json()) .subscribe((res: any) => { this.rsEntry = res.subjects; this.nHits = res.nhits; this.sortAlphabetically(); this.sortingType = 'alphabetic'; }); this.konvolutType = this.route.snapshot.url[ 0 ].path; this.sub = this.route.params.subscribe(params => { this.konvolutId = params[ 'konvolut' ]; }); } // TODO: Sort alphabetically after init. How? sortAlphabetically() { this.rsEntry = this.rsEntry.sort((n1, n2) => { const k1 = this.sortingService.germanAlphabeticalSortKey(n1.value[ 0 ]); const k2 = this.sortingService.germanAlphabeticalSortKey(n2.value[ 0 ]); if (k1 > k2) { return 1; } if (k1 < k2) { return -1; } return 0; }); } sortChronologically() { // Sortiere nach obj_id bis eine interne Nummerierung da ist // TODO passe an entsprechende Datentypen der Felder an this.rsEntry = this.rsEntry.sort((n1, n2) => { let k1; let k2; if (this.konvolutType === 'notizbuecher' || this.konvolutType === 'manuskripte') { k1 = n1.obj_id; k2 = n2.obj_id; } else { k1 = n1.obj_id; k2 = n2.obj_id; } if (k1 > k2) { return 1; } if (k1 < k2) { return -1; } return 0; }); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/shared/textgrid/textgrid.component.ts
<gh_stars>0 /** * Created by retobaumgartner on 21.06.17. */ import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-textgrid', templateUrl: 'textgrid.component.html', styleUrls: [ 'textgrid.component.css' ] }) export class TextgridComponent implements OnChanges { @Input() contentType: string = 'suche'; // synopse OR konvolut OR suche @Input() viewMode: string = 'grid'; @Input() showText: boolean = true; @Input() poemsInGrid: Array<any>; ngOnChanges(changes: SimpleChanges) { for (let propName in changes) { if (propName === 'poemsInGrid') { let chng = changes[ propName ]; this.poemsInGrid = chng.currentValue; } } /* for (let propName in changes) { let chng = changes[propName]; let cur = JSON.stringify(chng.currentValue); let prev = JSON.stringify(chng.previousValue); this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`); }*/ // changes.prop contains the old and the new value... } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/defineOnePropertyForRequest/defineOnePropertyForRequest.module.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { FormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { BrowserModule } from '@angular/platform-browser'; import { MdButtonModule, MdButtonToggleModule, MdCardModule, MdGridListModule, MdIconModule, MdInputModule, MdMenuModule, MdCheckboxModule, MdSelectModule } from '@angular/material'; import { DefineOnePropertyForRequestComponent } from './defineOnePropertyForRequest.component'; @NgModule({ imports: [ CommonModule, MdButtonToggleModule, MdCardModule, RouterModule, MdButtonModule, MdButtonToggleModule, MdCardModule, MdGridListModule, MdIconModule, MdInputModule, MdMenuModule, MdCheckboxModule, MdSelectModule, FormsModule, BrowserAnimationsModule, BrowserModule ], declarations: [ DefineOnePropertyForRequestComponent ], exports: [ DefineOnePropertyForRequestComponent ] }) export class DefineOnePropertyForRequestModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/suche-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { SucheComponent } from './suche.component'; @NgModule({ imports: [ RouterModule.forChild([ { path: 'suche', component: SucheComponent } ]) ], exports: [ RouterModule ] }) export class SucheRoutingModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/register/register.module.ts
<gh_stars>0 /** * Created by <NAME> (rfbaumgartner) on 07.07.17. */ import { NgModule } from '@angular/core'; import { HttpModule } from '@angular/http'; import { MdButtonModule, MdListModule } from '@angular/material'; import { BrowserModule } from '@angular/platform-browser'; import { RegisterComponent } from './register.component'; import { RegisterNavigationComponent } from './register-navigation/register-navigation.component'; import { RegisterBeschreibungComponent } from './register-beschreibung/register-beschreibung.component'; import { RegisterTitelregisterComponent } from './titelregister/register-titelregister.component'; import { RouterModule } from '@angular/router'; @NgModule({ imports: [ BrowserModule, HttpModule, MdButtonModule, MdListModule, RouterModule.forChild([ { path: 'register', component: RegisterComponent }, { path: 'register/:zeitraum', component: RegisterComponent } ]) ], declarations: [ RegisterBeschreibungComponent, RegisterComponent, RegisterNavigationComponent, RegisterTitelregisterComponent ], exports: [ RegisterComponent ], providers: [] }) export class RegisterModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/shared/registerspalte/registerspalte.module.ts
/** * Created by <NAME> (rfbaumgartner) on 27.06.17. */ import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MdButtonToggleModule, MdListModule } from '@angular/material'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule } from '@angular/router'; import { RegisterspalteComponent } from './registerspalte.component'; import { CommonModule } from '@angular/common'; @NgModule({ imports: [ BrowserModule, CommonModule, FormsModule, HttpModule, MdButtonToggleModule, MdListModule, RouterModule ], declarations: [ RegisterspalteComponent ], exports: [ RegisterspalteComponent ], providers: [] }) export class RegisterspalteModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/register/register-beschreibung/register-beschreibung.component.ts
<filename>src/client/app/register/register-beschreibung/register-beschreibung.component.ts /** * Created by <NAME> (rfbaumgartner) on 07.07.17. */ import { Component, Input } from '@angular/core'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/switchMap'; @Component({ moduleId: module.id, selector: 'rae-register-beschreibung', templateUrl: 'register-beschreibung.component.html' }) export class RegisterBeschreibungComponent { @Input() selectedTab: string; }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/searchForOneResourceComponent/searchForOneResource.module.ts
<gh_stars>1-10 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { FormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { BrowserModule } from '@angular/platform-browser'; import { MdButtonModule, MdButtonToggleModule, MdCardModule, MdGridListModule, MdIconModule, MdInputModule, MdMenuModule, MdCheckboxModule, MdSelectModule } from '@angular/material'; import { SearchForOneResourceComponent } from './searchForOneResource.component'; import { DefineOnePropertyForRequestModule } from '../defineOnePropertyForRequest/defineOnePropertyForRequest.module'; @NgModule({ imports: [ CommonModule, MdButtonToggleModule, MdCardModule, RouterModule, MdButtonModule, MdButtonToggleModule, MdCardModule, MdGridListModule, MdIconModule, MdInputModule, MdMenuModule, MdCheckboxModule, MdSelectModule, FormsModule, BrowserAnimationsModule, BrowserModule, DefineOnePropertyForRequestModule ], declarations: [ SearchForOneResourceComponent ], exports: [ SearchForOneResourceComponent ] }) export class SearchForOneResourceModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/shared/text/text.service.ts
/** * Created by <NAME> (<EMAIL>) on 7/10/17. */ import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Config } from '../config/env.config'; import { KnoraRequest } from '../utilities/knora-api-params'; @Injectable() export class TextService { private _knoraUrl = Config.API; private static _extractData(res: Response) { const body = res.json(); return body.data || {}; } private static _handleError(error: Response | any) { let errMsg: string; if (error instanceof Response) { const body = error.json() || ''; const err = body.error || JSON.stringify(body); errMsg = `${error.status} - ${error.statusText || ''} ${err}`; } else { errMsg = error.message ? error.message : error.toString(); } console.error(errMsg); return Observable.throw(errMsg); } constructor(private http: Http) { } getText(params: KnoraRequest): Observable<Array<any>> { return this.http .get(params.toString()) //.map(response => <string[]> response.json()[1]) //.map(FassungKonstTextService._extractData) //.catch(FassungKonstTextService._handleError); .map(response => response.json().subjects); //.subscribe((res: Array<any>) => this.poems = res); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/utilities/knora-api-params.ts
import { Config } from '../config/env.config'; /** * Created by <NAME> (<EMAIL>) on 7/11/17. */ /** * Base abstract class for configuring a request to Knora API */ export abstract class KnoraRequest { protected _host = Config.API; protected abstract _searchtype: string; protected abstract _filterByRestype: string; protected abstract _filterByProject: string; protected abstract _showNRows: number; protected abstract _startAt: number; /** * Serialises string */ public abstract toString(): string; set filterByRestype(v: string) { this._filterByRestype = v; } set filterByProject(v: string) { this._filterByProject = v; } set showNRows(v: number) { this._showNRows = v; } set startAt(v: number) { this._startAt = v; } set host(v: string) { this._host = v; } } /** * Helper class for defining a property triple as requested by Knora API */ export class KnoraProperty { private _propertyId: string; private _compop: string; private _searchval: string; /** * Serialises property * @returns {string} Formatted string */ public toString() { return 'property_id=' + encodeURIComponent(this._propertyId) + '&compop=' + encodeURIComponent(this._compop) + '&searchval=' + encodeURIComponent(this._searchval); } constructor(readonly propertyId: string, readonly compop: string, readonly searchval: string) { this._propertyId = propertyId; this._compop = compop; this._searchval = searchval; } } /** * Helper class for configuring a fulltext search request to Knora API */ export class FulltextSearch extends KnoraRequest { set searchstring(v: string) { this._searchstring = v; } protected _searchstring: string = ''; protected _searchtype = 'fulltext'; protected _filterByRestype: string = ''; protected _filterByProject: string = ''; protected _showNRows: number = 0; protected _startAt: number = 0; /** * Serialises request * @returns {string} Formatted string */ public toString() { return this._host + this._searchstring + '?searchtype=' + this._searchtype + (this._filterByRestype.length > 0 ? '&filter_by_restype=' + encodeURIComponent(this._filterByRestype) : '') + (this._filterByProject.length > 0 ? '&filter_by_project=' + encodeURIComponent(this._filterByProject) : '') + (this._showNRows > 0 ? '&show_nrows=' + encodeURIComponent(this._showNRows.toString()) : '') + (this._startAt > 0 ? '&start_at=' + encodeURIComponent(this._startAt.toString()) : ''); } } /** * Helper class configuring an extended search request to Knora API. */ export class ExtendedSearch extends KnoraRequest { set filterByOwner(v: string) { this._filterByOwner = v; } set property(v: KnoraProperty) { this._property.push(v); } protected _searchtype = 'extended'; protected _filterByRestype: string = ''; protected _filterByProject: string = ''; protected _filterByOwner: string = ''; protected _property: Array<KnoraProperty> = []; protected _showNRows: number = 0; protected _startAt: number = 0; /** * Serialises request * @returns {string} Formatted string */ public toString() { let propString: string = ''; if (this._property.length > 0) { for (let e of this._property) { propString += '&'; propString += e.toString(); } } return this._host + '?searchtype=' + this._searchtype + (this._filterByRestype.length > 0 ? '&filter_by_restype=' + encodeURIComponent(this._filterByRestype) : '') + (this._filterByProject.length > 0 ? '&filter_by_project=' + encodeURIComponent(this._filterByProject) : '') + (this._filterByOwner.length > 0 ? '&filter_by_owner=' + encodeURIComponent(this._filterByOwner) : '') + propString + (this._showNRows > 0 ? '&show_nrows=' + encodeURIComponent(this._showNRows.toString()) : '') + (this._startAt > 0 ? '&start_at=' + encodeURIComponent(this._startAt.toString()) : ''); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/fassung/fassung-werkzeugleiste/fassung-werkzeugleiste.component.ts
<filename>src/client/app/fassung/fassung-werkzeugleiste/fassung-werkzeugleiste.component.ts /** * Created by <NAME> (rfbaumgartner) on 05.07.17. */ import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-fassung-werkzeugleiste', templateUrl: 'fassung-werkzeugleiste.component.html', styleUrls: [ 'fassung-werkzeugleiste.component.css' ] }) export class FassungWerkzeugleisteComponent implements OnInit { @Input() poemResizable: boolean; @Input() showRegister: boolean; @Output() poemResizableChange: EventEmitter<boolean> = new EventEmitter<boolean>(); @Output() showRegisterChange: EventEmitter<boolean> = new EventEmitter<boolean>(); @Input() idOfPrev: string; @Input() idOfNext: string; neuladen() { window.location.reload(); } hilfe() { // TODO console.log('Hilfetext ergaenzen'); } ngOnInit() {} }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/textgrid/paging.service.ts
<filename>src/client/app/suche/textgrid/paging.service.ts /** * Created by <NAME> (<EMAIL>) on 7/12/17. */ import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Http } from '@angular/http'; import { KnoraRequest } from '../utilities/knora-api-params'; @Injectable() export class DynamicPaging { private _offset = 0; private _size = 20; constructor(private http: Http) { } get size(): number { return this._size; } set size(v: number) { this._size = v; } loadText(req: KnoraRequest): Observable<Array<any>> { req.showNRows = this._size; req.startAt = this._offset; this._offset = this._offset + this._size; return this.getText(req); } getText(params: KnoraRequest): Observable<Array<any>> { return this.http .get(params.toString()) .map(response => response.json().subjects); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/register/register-navigation/register-navigation.component.ts
/** * Created by <NAME> (rfbaumgartner) on 07.07.17. */ import { Component, Input } from '@angular/core'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/switchMap'; @Component({ moduleId: module.id, selector: 'rae-register-navigation', templateUrl: 'register-navigation.component.html', styleUrls: [ 'register-navigation.component.css' ] }) export class RegisterNavigationComponent { @Input() selectedTab: string; }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/shared/text/text.component.ts
/** * Created by <NAME> (<EMAIL>) on 7/10/17. */ import { Component, OnInit } from '@angular/core'; import { TextService } from './text.service'; import { ActivatedRoute } from '@angular/router'; import { ExtendedSearch, KnoraProperty } from '../utilities/knora-api-params'; const _expressions: { [key: string]: string } = { 'notizbuecher': 'http://www.knora.org/ontology/text#Note', 'manuskripte': 'http://www.knora.org/ontology/text#Manuscript', 'typoskripte': 'http://www.knora.org/ontology/text#Typescript', 'drucke': 'http://www.knora.org/ontology/text#Print' }; @Component({ moduleId: module.id, selector: 'rae-text', templateUrl: './text.component.html', providers: [ TextService ] }) export class TextComponent implements OnInit { text: Array<any>; errorMsg: any; constructor(private konstTextService: TextService, private route: ActivatedRoute) { } ngOnInit() { let searchParams = new ExtendedSearch; searchParams.filterByRestype = _expressions[ this.route.snapshot.url[ 0 ].path ]; searchParams.property = new KnoraProperty('http://www.knora.org/ontology/text#hasTitle', '!EQ', ' '); searchParams.property = new KnoraProperty('http://www.knora.org/ontology/text#hasDescription', '!EQ', ' '); searchParams.showNRows = 500; this.route.snapshot.paramMap.get('fassung'); this.konstTextService .getText(searchParams) .subscribe( konstText => this.text = konstText, error => this.errorMsg = <any>error ); } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/suche/globalSearchVariablesService.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche<filename>src/client/app/suche/globalSearchVariablesService.ts export const globalSearchVariableService = Object.freeze({ initialVocabulary: 'http://www.knora.org/ontology/incunabula', API_URL: 'http://192.168.127.12:3333/v1', resourceTypesPath: '/resourcetypes?vocabulary=', propertyListsQuery: '/propertylists?restype=', extendedSearch: '/search/?searchtype=extended&filter_by_restype=', extendedProperty: '&property_id=', compareOperator: '&compop=', searchval: '&searchval=' //... more of your variables });
janCstoffregen/raeber-mit-generischer-suche
src/client/app/core/haupttext.component.ts
/** * Created by <NAME> (<EMAIL>) on 7/20/17. */ import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-haupttext', template: '<router-outlet></router-outlet>' }) export class HaupttextComponent { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/fassung/fassung-weitere/fassung-weitere.component.ts
/** * Created by retobaumgartner on 06.07.17. */ import { Component, Input } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-fassung-weitere', templateUrl: 'fassung-weitere.component.html' }) export class FassungWeitereComponent { @Input() synopsenTags: Array<string>; weitereFassungen: Array<any> = [{'id': 'wolke 2', 'text': 'manu'}, {'id': 'wolke 3', 'text': 'typo'}]; // TODO }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/konvolut/konvolut-steckbrief/konvolut-steckbrief.component.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche /** * Created by retobaumgartner on 06.06.17. */ import { Component, Input, OnInit } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-konvolut-steckbrief', templateUrl: 'konvolut-steckbrief.component.html', styleUrls: [ 'konvolut-steckbrief.component.css' ] }) export class KonvolutSteckbriefComponent implements OnInit { @Input() id: string; ngOnInit() { } }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/core/core.module.ts
<gh_stars>0 /** * Created by <NAME> (<EMAIL>) on 7/20/17. */ import { NgModule } from '@angular/core'; import { FusszeileComponent } from './fusszeile.component'; import { KopfzeileComponent } from './kopfzeile.component'; import { NavigationsleisteComponent } from './navigationsleiste.component'; import { CommonModule } from '@angular/common'; import { HaupttextComponent } from './haupttext.component'; import { RouterModule } from '@angular/router'; import { PageNotFoundComponent } from './404.component'; import { KonvolutModule } from '../konvolut/konvolut.module'; import { FassungModule } from '../fassung/fassung.module'; import { RegisterModule } from '../register/register.module'; import { StatischModule } from '../statisch/statisch.module'; import { SucheModule } from '../suche/suche.module'; import { SynopseModule } from '../synopse/synopse.module'; @NgModule({ imports: [ CommonModule, // Order of imports is important! StatischModule, KonvolutModule, FassungModule, RegisterModule, SucheModule, SynopseModule, RouterModule.forRoot([ { path: '', redirectTo: '/start', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]) ], declarations: [ FusszeileComponent, KopfzeileComponent, HaupttextComponent, NavigationsleisteComponent, PageNotFoundComponent ], exports: [ KopfzeileComponent, HaupttextComponent, FusszeileComponent ] }) export class CoreModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/statisch/statisch.module.ts
/** * Created by <NAME> (<EMAIL>) on 7/21/17. */ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { routingComponents, StatischRoutingModule } from './statisch-routing.module'; @NgModule({ imports: [ CommonModule, StatischRoutingModule ], declarations: [ routingComponents ], exports: [ routingComponents ] }) export class StatischModule { }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/statisch/werkausgabe.component.ts
<reponame>janCstoffregen/raeber-mit-generischer-suche /** * Created by <NAME> (<EMAIL>) on 6/7/17. */ import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-werkausgabe', templateUrl: 'werkausgabe.component.html' }) export class WerkausgabeComponent { title = 'Kuno Raeber. Werke in 7 Bänden'; }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/konvolut/konvolut-werkzeugleiste/konvolut-werkzeugleiste.component.ts
<gh_stars>0 /** * Created by <NAME> (rfbaumgartner) on 05.07.17. */ import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ moduleId: module.id, selector: 'rae-konvolut-werkzeugleiste', templateUrl: 'konvolut-werkzeugleiste.component.html', styleUrls: [ 'konvolut-werkzeugleiste.component.css' ] }) export class KonvolutWerkzeugleisteComponent implements OnInit { @Input() viewMode: string; @Output() viewModeChange: EventEmitter<string> = new EventEmitter<string>(); hilfe() { // TODO console.log('Hilfetext ergaenzen'); } ngOnInit() {} }
janCstoffregen/raeber-mit-generischer-suche
src/client/app/konvolut/super-konvolut.component.ts
/** * Created by <NAME> (rfbaumgartner) on 29.06.17. */ import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import { ActivatedRoute, Params, Router } from '@angular/router'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/switchMap'; import { ExtendedSearch, KnoraProperty } from '../shared/utilities/knora-api-params'; @Component({ moduleId: module.id, selector: 'rae-super-konvolut', templateUrl: 'super-konvolut.component.html' }) export class SuperKonvolutComponent implements OnInit { poems: Array<any>; // for testings searchQuery: string; konvolut_id: string; konvolut_type: string; private sub: any; private _esearch = new ExtendedSearch(); constructor(private http: Http, private route: ActivatedRoute, private router: Router) { } ngOnInit() { this.konvolut_type = this.route.snapshot.url[ 0 ].path; this._esearch.filterByRestype = 'http://www.knora.org/ontology/text#Convolute'; this._esearch.property = new KnoraProperty('http://www.knora.org/ontology/text#hasTitle', '!EQ', ' '); this._esearch.property = new KnoraProperty('http://www.knora.org/ontology/text#hasDescription', '!EQ', ' '); this._esearch.showNRows = 500; this.route.params .switchMap((params: Params) => this.http.get(this._esearch.toString())) .map(response => response.json().subjects) .subscribe((res: Array<any>) => this.poems = res); this.konvolut_type = this.route.snapshot.url[ 0 ].path; this.sub = this.route.params.subscribe(params => { this.konvolut_id = params[ 'id' ]; }); console.log('search/schlaf?searchtype=fulltext'); } }