repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
Nebulis/blog
|
src/components/images/asia/japan/shared-japan-images.tsx
|
<filename>src/components/images/asia/japan/shared-japan-images.tsx
import { graphql, useStaticQuery } from "gatsby"
import Img from "gatsby-image"
import * as React from "react"
import { ExtraImageProps } from "../../../../types/shared"
const alt = {
mainNagoya: "Nagoya",
mainFuji: "Mount Fuji",
mainTokyo: "Tokyo",
}
export const SharedJapanImages: React.FunctionComponent<ExtraImageProps & { image: keyof typeof alt }> = ({
className = "",
image,
fluidObject = {},
imgStyle = {},
}) => {
const data = useStaticQuery(graphql`
query {
mainArashiyama: file(relativePath: { eq: "asia/japan/carousel-japan.jpg" }) {
childImageSharp {
fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) {
...GatsbyImageSharpFluid
}
}
}
mainHimeji: file(relativePath: { eq: "asia/japan/carousel-japan-2.jpg" }) {
childImageSharp {
fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) {
...GatsbyImageSharpFluid
}
}
}
mainNagoya: file(relativePath: { eq: "asia/japan/nagoya/castle/nagoya-castle-main.jpg" }) {
childImageSharp {
fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) {
...GatsbyImageSharpFluid
}
}
}
mainFuji: file(relativePath: { eq: "asia/japan/fuji/kawaguchiko-lake/kawaguchiko-lake-main.jpg" }) {
childImageSharp {
fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) {
...GatsbyImageSharpFluid
}
}
}
mainTokyo: file(relativePath: { eq: "asia/japan/tokyo/two-days-in-tokyo/two-days-in-tokyo-main.jpg" }) {
childImageSharp {
fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) {
...GatsbyImageSharpFluid
}
}
}
}
`)
return (
<Img
fluid={{ ...data[image].childImageSharp.fluid, ...fluidObject }}
alt={alt[image]}
className={className}
imgStyle={imgStyle}
/>
)
}
|
wise1994/taro-apollo-hooks
|
src/client.ts
|
<reponame>wise1994/taro-apollo-hooks
import ApolloClient from 'apollo-client';
let client: ApolloClient<any> | null = null;
export function setClient(overrideClient: ApolloClient<any>) {
client = overrideClient;
}
export function getClient() {
return client;
}
export default client;
|
Hyoretsu/ccreddit-mod
|
src/init/cookiesPerClickHook/index.ts
|
const cookiesPerClickHookContent = (cookiesPerClick: number): number => {
let cpc = cookiesPerClick;
if (Game.Has('Misfortune #604')) {
cpc += Game.cookiesPs * 0.01;
}
return cpc;
};
export default cookiesPerClickHookContent;
|
Hyoretsu/ccreddit-mod
|
src/customFuncs/index.ts
|
<filename>src/customFuncs/index.ts
export { default as Upgrades } from './Upgrades';
export { default as TieredUpgrades } from './TieredUpgrades';
export { default as HeavenlyUpgrades } from './HeavenlyUpgrades';
|
Hyoretsu/ccreddit-mod
|
src/init/checkHook/index.ts
|
<filename>src/init/checkHook/index.ts
import { haloIdleverseDesc } from '../createHook';
const auraTierChecks = (): (() => void)[] => {
const checkFuncsArray = Game.ObjectsById.filter(building => building.vanilla === 1 && building.name !== 'Cursor').map(
building => () => {
if (Game.Has('Aura gloves') && building.level >= 5 && building.amount >= 1) {
Game.Unlock(building.tieredUpgrades.aura.name);
}
},
);
return checkFuncsArray;
};
const haloTierChecks = (): (() => void)[] => {
const checkFuncsArray = Game.ObjectsById.filter(building => building.vanilla === 1 && building.name !== 'Cursor').map(
building => () => {
if (Game.Has('Halo gloves') && building.amount >= 1) {
Game.Unlock(building.tieredUpgrades.halo.name);
}
},
);
return checkFuncsArray;
};
const luminousTierChecks = (): (() => void)[] => {
const checkFuncsArray = Game.ObjectsById.filter(building => building.vanilla === 1 && building.name !== 'Cursor').map(
building => () => {
if (Game.Has('Luminous gloves') && building.level >= 10 && building.amount >= 1) {
Game.Unlock(building.tieredUpgrades.luminous.name);
}
},
);
return checkFuncsArray;
};
const checkHookContent = [
...auraTierChecks(),
...haloTierChecks(),
(): void => {
const upgrade = Game.Upgrades['Halo from the other side'];
upgrade.desc = upgrade.desc.replace(upgrade.desc.split(/<\/?q>/)[1], haloIdleverseDesc());
},
...luminousTierChecks(),
];
export default checkHookContent;
|
Hyoretsu/ccreddit-mod
|
src/save/index.ts
|
import { modName } from '@config';
const save = (): string => {
const saveObj: ISave = {
boughtUpgrades: [],
unlockedUpgrades: [],
};
Game.UpgradesById.filter(upgrade => upgrade.mod === modName).forEach(upgrade => {
if (upgrade.bought) {
saveObj.boughtUpgrades.push(upgrade.name);
} else if (upgrade.unlocked) {
saveObj.unlockedUpgrades.push(upgrade.name);
}
});
return JSON.stringify(saveObj);
};
export default save;
|
Hyoretsu/ccreddit-mod
|
src/main.ts
|
import { modName } from './config';
import init from './init';
import save from './save';
import load from './load';
const CCIdeas: Game.Mod = {
init,
save,
load,
};
Game.registerMod(modName, CCIdeas);
|
Hyoretsu/ccreddit-mod
|
src/init/customMods/index copy.ts
|
<filename>src/init/customMods/index copy.ts
export const misfortunePrice = 66666666666666666666666666666;
interface InjectObject {
cpsMult: string[];
getTieredCpsMult: string[];
kittenUpgrade: string[];
modifyBuildingPrice: string[];
offlineCps: string[];
ticker: string[];
upgradeGetPrice: string[];
}
const customMods = (): void => {
// Create injections object
const injects: InjectObject = {
cpsMult: [],
getTieredCpsMult: [],
kittenUpgrade: [],
modifyBuildingPrice: [],
offlineCps: [],
ticker: [],
upgradeGetPrice: [],
};
// Insert custom CSS
const link = document.createElement('link');
Object.assign(link, {
type: 'text/css',
rel: 'stylesheet',
href: 'https://hyoretsu.github.io/ccideas-mod/static/styles.css',
});
document.getElementsByTagName('head')[0].appendChild(link);
let tierCount = 10;
const addTierCount = () => {
tierCount *= 10;
};
// Tier creation
class Tier {
special?: 1;
unlock: number;
upgrades: [];
constructor(public name: string, public color: string, public iconRow: number, public price?: number) {
this.color = color;
this.iconRow = iconRow;
this.name = name;
this.price = price || Game.Tiers[Object.keys(Game.Tiers).length - 3].price * tierCount;
this.special = 1;
this.unlock = -1;
this.upgrades = [];
addTierCount();
}
}
Object.assign(Game.Tiers, {
aura: new Tier('Aura', '#ff7e00', 3),
luminous: new Tier('Luminous', '#faedb9', 4),
halo: new Tier('Halo', '#ffcc2f', 5),
misfortune: new Tier('Misfortune', '#7e5a40', 0, misfortunePrice),
});
// Misfortune tier injections
injects.cpsMult.push("if(Game.Has('Misfortune #600')){mult*=1.01};if(Game.Has('Misfortune #601')){mult*=1.06}");
injects.kittenUpgrade.push("if(Game.Has('Misfortune #603')){catMult*=1+Game.milkProgress*0.05*milkMult}");
injects.getTieredCpsMult.push(
'if(Game.Has(me.tieredUpgrades.misfortune.name)){switch(Game.elderWrath){case 1:mult*=1.02;break;case 2:mult*=1.04;break;case 3:mult*=1.06;break;}}',
);
injects.modifyBuildingPrice.push(
"if(Game.Has(building.tieredUpgrades.misfortune.name)){switch(Game.elderWrath){case 1:price*=0.98;break;case 2:price*=0.96;break;case 3:price*=0.94;break;}}if(Game.Has('Misfortune #600')){price*=0.99;}",
);
injects.offlineCps.push("if(Game.Has('Misfortune #602')){percent+=1}");
injects.ticker.push(
// eslint-disable-next-line no-template-curly-in-string
'if(!manual&&Game.Has("Misfortune cookies")&&Math.random()<(Game.HasAchiev("O Fortuna")?0.04:0.02)){const misfortunes=[];Game.Tiers.misfortune.upgrades.forEach(upgrade=>{if(!upgrade.unlocked){ misfortunes.push(upgrade);}});if(misfortunes.length>0){list=[];const chosenNews=choose(misfortunes);Game.TickerEffect={type:"fortune",sub:chosenNews};console.log(chosenNews);list=[`<span id="misfortune"><div class="icon"></div>${chosenNews.name.split(" ")[1]} : ${chosenNews.baseDesc.split("<q>")[1].split("</q>")[0]}</span>`,]}}',
);
injects.upgradeGetPrice.push("if(Game.Has('Misfortune #600')){price*=0.99}");
// Inject code into vanilla fuctions
Game.CalculateGains = new Function(
`return ${Game.CalculateGains.toString()
.split('var rawCookiesPs=Game.cookiesPs*mult;')
.join(`${injects.getTieredCpsMult.join('\n')}` + '\n\nvar rawCookiesPs=Game.cookiesPs*mult;')}`,
)();
Game.GetTieredCpsMult = new Function(
`return ${Game.GetTieredCpsMult.toString()
.split('return mult')
.join(`${injects.getTieredCpsMult.join('\n')}` + '\n\nreturn mult')}`,
)();
Game.CalculateGains = new Function(
`return ${Game.CalculateGains.toString()
.split("Game.cookiesMultByType['kittens']=catMult;")
.join(`${injects.kittenUpgrade.join('\n')}` + "\n\nGame.cookiesMultByType['kittens']=catMult;")}`,
)();
Game.modifyBuildingPrice = new Function(
`return ${Game.modifyBuildingPrice
.toString()
.split('return price')
.join(`${injects.modifyBuildingPrice.join('\n')}` + '\n\nreturn price')}`,
)();
Game.LoadSave = new Function(
`return ${Game.LoadSave.toString()
.split('var percent=5;')
.join('var percent=5;\n\n' + `${injects.offlineCps.join('\n')}`)}`,
)();
Game.getNewTicker = new Function(
`return ${Game.getNewTicker
.toString()
.split('Game.TickerAge=Game.fps*10;')
.join(`${injects.ticker.join('\n')}` + '\n\nGame.TickerAge=Game.fps*10;')}`,
)();
Game.Upgrade.prototype.getPrice = new Function(
`return ${Game.Upgrade.prototype.getPrice
.toString()
.split(/\t{3}}/)
.join(`${injects.upgradeGetPrice.join('\n')}` + '\n}')}`,
)();
};
export default customMods;
|
Hyoretsu/ccreddit-mod
|
src/@types/global.d.ts
|
<reponame>Hyoretsu/ccreddit-mod<filename>src/@types/global.d.ts<gh_stars>1-10
type PriceFunc = (data: Game.Upgrade) => number;
interface ICreateUpgradeDTO {
name: string;
description?: string;
quote?: string;
price: number;
icon: Icon;
order?: number;
cookie?: {
upgradeReq: string;
mult: number;
};
}
interface ICreateTieredUpgradeDTO {
name: string;
description?: string;
quote?: string;
price?: number;
priceFunc?: PriceFunc;
icon?: Game.Icon;
building?: string;
tier: number | string;
kitten?: true;
order?: number;
}
interface ICreateHeavenlyUpgradeDTO {
name: string;
description: string;
quote?: string;
price: number;
icon: Game.Icon;
parents: string[];
position: [x: number, y: number];
order: number;
}
interface ISave {
boughtUpgrades: string[];
unlockedUpgrades: string[];
}
|
Hyoretsu/ccreddit-mod
|
src/init/customMods/index.ts
|
const misfortunePrice = 66666666666666666666666666666;
const customMods = (): void => {
const tickerAddons: string[] = [];
const modifyBuildingPriceAddons: string[] = [];
const upgradeGetPriceAddons: string[] = [];
const getTieredCpsMultAddons: string[] = [];
const offlineCpsAddons: string[] = [];
const kittenUpgradeAddons: string[] = [];
// Insert custom CSS
const link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = 'https://hyoretsu.github.io/ccideas-mod/static/styles.css';
document.getElementsByTagName('head')[0].appendChild(link);
const baseTierPrice = Game.Tiers[Object.keys(Game.Tiers).length - 3].price;
let tierCount = 10;
const addTierCount = () => {
tierCount *= 10;
};
const haloTier = {
halo: {
color: '#ffcc2f',
iconRow: 5,
name: 'Halo',
price: baseTierPrice * tierCount,
unlock: -1,
upgrades: [],
},
};
addTierCount();
const auraTier = {
aura: {
color: '#ff7e00',
iconRow: 3,
name: 'Aura',
price: baseTierPrice * tierCount,
unlock: -1,
upgrades: [],
},
};
addTierCount();
const luminousTier = {
luminous: {
color: '#faedb9',
iconRow: 4,
name: 'Luminous',
price: baseTierPrice * tierCount,
unlock: -1,
upgrades: [],
},
};
addTierCount();
const misfortuneTier = {
misfortune: {
color: '#7e5a40',
iconRow: 0,
name: 'Misfortune',
price: misfortunePrice,
special: 1,
unlock: -1,
upgrades: [],
},
};
Object.assign(Game.Tiers, auraTier, haloTier, luminousTier, misfortuneTier);
tickerAddons.push(
// eslint-disable-next-line no-template-curly-in-string
'if(!manual&&Game.Has("Misfortune cookies")&&Math.random()<(Game.HasAchiev("O Fortuna")?0.04:0.02)){const misfortunes=[];Game.Tiers.misfortune.upgrades.forEach(upgrade=>{if(!upgrade.unlocked){ misfortunes.push(upgrade);}});if(misfortunes.length>0){list=[];const chosenNews=choose(misfortunes);Game.TickerEffect={type:"fortune",sub:chosenNews};console.log(chosenNews);list=[`<span id="misfortune"><div class="icon"></div>${chosenNews.name.split(" ")[1]} : ${chosenNews.baseDesc.split("<q>")[1].split("</q>")[0]}</span>`,]}}',
);
modifyBuildingPriceAddons.push(
"if(building.vanilla===1&&Game.Has(building.tieredUpgrades.misfortune.name)){switch(Game.elderWrath){case 1:price*=0.98;break;case 2:price*=0.96;break;case 3:price*=0.94;break;}}if(Game.Has('Misfortune #600')){price*=0.99;}",
);
upgradeGetPriceAddons.push("if(Game.Has('Misfortune #600')){price*=0.99}");
getTieredCpsMultAddons.push(
'if(me.vanilla===1&&Game.Has(me.tieredUpgrades.misfortune.name)){switch(Game.elderWrath){case 1:mult*=1.02;break;case 2:mult*=1.04;break;case 3:mult*=1.06;break;}}',
);
offlineCpsAddons.push("if(Game.Has('Misfortune #602')){percent+=1}");
kittenUpgradeAddons.push("if(Game.Has('Misfortune #603')){catMult*=1+Game.milkProgress*0.05*milkMult}");
// Inject code into vanilla fuctions
Game.getNewTicker = new Function(
`return ${Game.getNewTicker
.toString()
.split('Game.TickerAge=Game.fps*10;')
.join(`${tickerAddons.join('\n')}` + '\n\nGame.TickerAge=Game.fps*10;')}`,
)();
Game.modifyBuildingPrice = new Function(
`return ${Game.modifyBuildingPrice
.toString()
.split('return price')
.join(`${modifyBuildingPriceAddons.join('\n')}` + '\n\nreturn price')}`,
)();
Game.Upgrade.prototype.getPrice = new Function(
`return ${Game.Upgrade.prototype.getPrice
.toString()
.split(/\t{3}}/)
.join(`${upgradeGetPriceAddons.join('\n')}` + '\n}')}`,
)();
Game.GetTieredCpsMult = new Function(
`return ${Game.GetTieredCpsMult.toString()
.split('return mult')
.join(`${getTieredCpsMultAddons.join('\n')}` + '\n\nreturn mult')}`,
)();
Game.LoadSave = new Function(
`return ${Game.LoadSave.toString()
.split('var percent=5;')
.join('var percent=5;\n\n' + `${offlineCpsAddons.join('\n')}`)}`,
)();
Game.CalculateGains = new Function(
`return ${Game.CalculateGains.toString()
.split("Game.cookiesMultByType['kittens']=catMult;")
.join(`${kittenUpgradeAddons.join('\n')}` + "\n\nGame.cookiesMultByType['kittens']=catMult;")}`,
)();
};
export { misfortunePrice };
export default customMods;
|
Hyoretsu/ccreddit-mod
|
src/customFuncs/TieredUpgrades.ts
|
import { buildingsList, modName, tierDescs, tierRows, upgradeIconsUrl } from '@config';
const TieredUpgrades = (data: ICreateTieredUpgradeDTO[]): void => {
data.forEach(upgradeData => {
const quote = upgradeData.quote ? `<q>${upgradeData.quote}</q>` : '';
const tierDesc = tierDescs[upgradeData.tier] || tierDescs.default;
// @ts-ignore
const desc = (upgradeData.description || upgradeData.building.replace(/y$/, 'ie') + tierDesc) + quote;
let icon: Game.Icon;
if (upgradeData.icon) {
icon = [upgradeData.icon[0], upgradeData.icon[1], upgradeIconsUrl];
} else {
// @ts-ignore If this is ever reached, there will be a building in upgradeData
icon = [buildingsList.indexOf(upgradeData.building) + 3, tierRows[upgradeData.tier], upgradeIconsUrl];
}
// @ts-ignore If "price" isn't present, "building" will
const price = upgradeData.price || Game.Objects[upgradeData.building].basePrice * Game.Tiers[upgradeData.tier].price;
const upgrade = new Game.Upgrade(upgradeData.name, desc, price, icon);
upgrade.mod = modName;
if (upgradeData.building) {
if (!upgradeData.order) {
upgradeData.building === 'Cursor'
? (upgrade.order = 100)
: (upgrade.order = Math.floor(Game.Objects[upgradeData.building].tieredUpgrades[1].order) + 0.9999);
}
Game.SetTier(upgradeData.building, upgradeData.tier);
} else {
upgradeData.priceFunc && (upgrade.priceFunc = upgradeData.priceFunc);
upgrade.tier = upgradeData.tier;
}
upgradeData.order && (upgrade.order = upgradeData.order);
if (upgradeData.kitten) {
upgrade.kitten = 1;
Game.UpgradesByPool.kitten.push(upgrade);
}
Game.Tiers[upgradeData.tier].upgrades.push(upgrade);
});
};
export default TieredUpgrades;
|
Hyoretsu/ccreddit-mod
|
src/init/index.ts
|
<filename>src/init/index.ts
import checkHookContent from './checkHook';
import cookiesPerClickHookContent from './cookiesPerClickHook';
import cpsHookContent from './cpsHook';
import createHook from './createHook';
import customMods from './customMods';
const init = (): void => {
customMods();
Game.registerHook('check', checkHookContent);
Game.registerHook('cookiesPerClick', cookiesPerClickHookContent);
Game.registerHook('cps', cpsHookContent);
createHook();
};
export default init;
|
Hyoretsu/ccreddit-mod
|
src/init/cpsHook/index.ts
|
<gh_stars>1-10
const cpsHookContent = (originalCps: number): number => {
let cps = originalCps;
if (Game.Has('Misfortune #600')) {
cps *= 1.01;
}
if (Game.Has('Misfortune #601')) {
cps *= 1.06;
}
return cps;
};
export default cpsHookContent;
|
Hyoretsu/ccreddit-mod
|
src/load/index.ts
|
<reponame>Hyoretsu/ccreddit-mod<filename>src/load/index.ts
let newName: string;
const checkIfChanged = (upgradeName: string): void => {
const oldUpgradeNames = [
'Aura furnace',
'Aura oven',
'Aura seeds',
'Aura pickaxe',
'Aura cogs',
'Aura cash',
'Aura spells',
'Aura fuel',
'Aura transmutation',
'Aura portal',
'Aura condensers',
'Aura fractals',
'Aura universe',
];
const newUpgradeNames = [
'Aura oven',
'Auraven',
'Hoe-Fu',
'Planebreakers',
'Perfect workers',
'Aura banking',
'Conversion rates',
'Aura-fueled ships',
'Qi-kies',
'Self inflection',
'Aura manipulators',
"Hilbert's Secret Technique",
'Auraverse',
];
const oldIndex = oldUpgradeNames.indexOf(upgradeName);
if (oldIndex >= 0) {
newName = newUpgradeNames[oldIndex];
}
};
const load = (saveString: string): void => {
const save: ISave = JSON.parse(saveString);
save.unlockedUpgrades.forEach(upgrade => {
checkIfChanged(upgrade);
Game.Unlock(newName || upgrade);
});
save.boughtUpgrades.forEach(upgrade => {
checkIfChanged(upgrade);
Game.Upgrades[newName || upgrade].bought = 1;
});
};
export default load;
|
Hyoretsu/ccreddit-mod
|
src/customFuncs/Upgrades.ts
|
import { modName, upgradeIconsUrl } from '@config';
const Upgrades = (data: ICreateUpgradeDTO[]): any => {
data.forEach(upgradeData => {
const quote = upgradeData.quote ? `<q>${upgradeData.quote}</q>` : '';
// @ts-ignore If a description isn't provided, it'll be a cookie
const desc = (upgradeData.description || `Cookie production multiplier <b>+${upgradeData.cookie.mult}%</b>.`) + quote;
const icon: Game.Icon = [upgradeData.icon[0], upgradeData.icon[1], upgradeIconsUrl];
const upgrade = new Game.Upgrade(upgradeData.name, desc, upgradeData.price, icon);
upgrade.mod = modName;
upgradeData.order && (upgrade.order = upgradeData.order);
if (upgradeData.cookie) {
upgrade.pool = 'cookie';
upgrade.power = upgradeData.cookie.mult;
upgrade.unlockAt = {
cookies: upgradeData.price / 20,
name: upgradeData.name,
require: upgradeData.cookie.upgradeReq,
};
Game.cookieUpgrades.push(upgrade);
Game.UnlockAt.push(upgrade.unlockAt);
}
return upgrade;
});
};
export default Upgrades;
|
Hyoretsu/ccreddit-mod
|
src/init/createHook/index.ts
|
<reponame>Hyoretsu/ccreddit-mod<gh_stars>1-10
import * as buildings from '@config';
import { Upgrades, TieredUpgrades, HeavenlyUpgrades } from 'customFuncs';
import { misfortunePrice } from '../customMods';
let upgrades: any[];
const buildingCookies = (): ICreateUpgradeDTO[] => {
const suffix = 'cookies';
const order = 10028;
const price = 1e12;
const cookie = {
upgradeReq: 'Box of chocolate buildings',
mult: 3,
};
upgrades = [
// Missing quote
{
name: `${buildings.cursor} ${suffix}`,
price,
icon: [3, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.grandma} ${suffix}`,
price: price * 10,
icon: [4, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.farm} ${suffix}`,
price: price * 100,
icon: [5, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.mine} ${suffix}`,
price: price * 1000,
icon: [6, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.factory} ${suffix}`,
price: price * 10000,
icon: [7, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.bank} ${suffix}`,
price: price * 100000,
icon: [8, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.temple} ${suffix}`,
price: price * 1e6,
icon: [9, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.wizardTower} ${suffix}`,
price: price * 1e7,
icon: [10, 6],
order,
cookie,
},
{
name: `${buildings.shipment} ${suffix}`,
price: price * 1e8,
icon: [11, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.alchemyLab} ${suffix}`,
price: price * 1e9,
icon: [12, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.portal} ${suffix}`,
price: price * 1e10,
icon: [13, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.timeMachine} ${suffix}`,
price: price * 1e11,
icon: [14, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.antimatterCondenser} ${suffix}`,
price: price * 1e12,
icon: [15, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.prism} ${suffix}`,
price: price * 1e13,
icon: [16, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.chancemaker} ${suffix}`,
price: price * 1e14,
icon: [17, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.fractalEngine} ${suffix}`,
price: price * 1e15,
icon: [18, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.javascriptConsole} ${suffix}`,
price: price * 1e16,
icon: [19, 6],
order,
cookie,
},
// Missing quote
{
name: `${buildings.idleverse} ${suffix}`,
price: price * 1e17,
icon: [20, 6],
order,
cookie,
},
];
return upgrades;
};
const aura = (): ICreateTieredUpgradeDTO[] => {
const tier = 'aura';
upgrades = [
{
// Bob's
name: 'Auraven',
quote:
'Your grandmas have successfully mastered the art of baking, and are now able to use their aura to aid them in the process.',
building: buildings.grandma,
tier,
},
// Bob's
{
name: 'Hoe-Fu',
quote: 'Quite similar to Shovel-Fu, but with less breaking and more tilling.',
building: buildings.farm,
tier,
},
// Bob's
{
name: 'Planebreakers',
quote: 'By mining into the very fabric of reality itself, you found a way to get just a tiny bit more cookies.',
building: buildings.mine,
tier,
},
// Bob's
{
name: '<NAME>',
quote:
"Before you were using humans to work in your factories, but now you're using Nameks. Your productivity has increased by over 9000 percent!",
building: buildings.factory,
tier,
},
// Bob's
{
name: '<NAME>',
quote: 'Overdraw into the 4th dimension!',
building: buildings.bank,
tier,
},
{
name: 'Aura-filled temples',
quote:
'After many years of devoting themselves, the followers have started to awaken a power called aura. Praying while cultivating it pleases the gods even more.',
building: buildings.temple,
tier,
},
// Bob's
{
name: 'Conversion rates',
quote:
'Apparently by converting aura you get about twice the amount of mana. Gonna have to fire some people for that one.',
building: buildings.wizardTower,
tier,
},
{
// Bob's
name: 'Aura-fueled ships',
quote:
'Having no need for aura themselves, your astronauts distilled it into their fuel, making it even more efficient.',
building: buildings.shipment,
tier,
},
// Bob's
{
name: 'Qi-kies',
quote:
'Through your vast comprehension of the alchemical laws, you are now able to create cookies from your own qi – qi-kies, if you will.',
building: buildings.alchemyLab,
tier,
},
// Bob's
{
name: 'Self inflection',
quote:
'By creating portals from qi, it seems that you can travel inside yourself. A little odd, but more cookies nonetheless.',
building: buildings.portal,
tier,
},
{
name: '<NAME>',
quote: 'Through your comprehension of the Time Dao, you can now travel through time using your qi.',
building: buildings.timeMachine,
tier,
},
// Bob's
{
name: 'Aura manipulators',
quote: "There couldn't be that many consequences for manipulating the- [TRANSMISSION LOST].",
building: buildings.antimatterCondenser,
tier,
},
{
name: '<NAME>',
quote: "Light is energy, isn't it? Now you're making cookies out of aura.",
building: buildings.prism,
tier,
},
{
name: '<NAME>',
// Bob's
quote:
"Yes, you've found a way to use your understanding of the world to affect your luck and get more cookies. *sigh* Don't you think you have enough luck already?",
building: buildings.chancemaker,
tier,
},
// Bob's
{
name: "Hilbert's Secret Technique",
quote: "It's unreadable, just a whole lot of random squiggles.",
building: buildings.fractalEngine,
tier,
},
{
name: '<NAME>',
quote: "It's an algorithm, I swear! It really doubles your cookie production. Don't ask how it works.",
building: buildings.javascriptConsole,
tier,
},
{
// Bob's
name: 'Auraverse',
quote:
"It is said that when one's understanding of the Martial Dao gets too profound, an ocean starts forming inside of his own body, eventually becoming a full-fledged world.",
building: buildings.idleverse,
tier,
},
];
return upgrades;
};
export const haloIdleverseDesc = (): string => `I must've called about ${Beautify(Game.cookiesPs)} times.`;
const halo = (): ICreateTieredUpgradeDTO[] => {
const tier = 'halo';
upgrades = [
{
name: 'Halo flames',
quote: "They're easier to work with.",
building: buildings.grandma,
tier,
},
{
name: 'Halo scarecrow hat',
quote: 'It serves to ward off animals in the dark.',
building: buildings.farm,
tier,
},
{
name: 'Halo cap',
quote: 'It really helps to see in the dark!',
building: buildings.mine,
tier,
},
{
name: 'Halo light bulbs',
quote:
"These'll be sure to provide good lighting to all those workers throughout the nigh- I mean, when they need it in their law-abiding work hours.",
building: buildings.factory,
tier,
},
{
name: 'Halo coins',
quote: "They don't have the shape you're used to seeing, but that saves resources.",
building: buildings.bank,
tier,
},
// Missing quote
{
name: 'Halo headgear',
building: buildings.temple,
tier,
},
// Bob's
{
name: 'Halo hats',
quote: 'Wards off 99% of dark magic!',
building: buildings.wizardTower,
tier,
},
{
name: 'Halo nose cone',
quote: "Outer space is so dark, isn't it? Well, not anymore.",
building: buildings.shipment,
tier,
},
// Seriously?
{
name: 'Halo transmutation',
building: buildings.alchemyLab,
tier,
},
{
name: 'Halo portal',
quote: "You're now getting cookies from halos here and there.",
building: buildings.portal,
tier,
},
// Missing quote
{
name: 'Halo bezel',
building: buildings.timeMachine,
tier,
},
{
name: 'Halo condensers',
// Bob's
quote:
'... and the factor of holiness per halo condensed is a function where n is the number of halos and g is the universal condescension constant, 2^ng.',
building: buildings.antimatterCondenser,
tier,
},
// Bob's
{
name: 'Halo refraction',
quote:
"A halo also gives off light, doesn't it? I guess at this point it doesn't really matter, you'll find a way to make cookies with them.",
building: buildings.prism,
tier,
},
// Bob's
{
name: 'No dice',
quote: 'I have them all :)',
building: buildings.chancemaker,
tier,
},
{
name: 'Halo fractals',
// Bob's
quote: 'Reflect upon yourself, then again, then again, then again, and now you have a massive space filling curve.',
building: buildings.fractalEngine,
tier,
},
{
name: 'Halo LED',
quote: "It's shiny.",
building: buildings.javascriptConsole,
tier,
},
// Bob's
{
name: 'Halo from the other side',
quote: haloIdleverseDesc(),
building: buildings.idleverse,
tier,
},
];
return upgrades;
};
const luminous = (): ICreateTieredUpgradeDTO[] => {
const tier = 'luminous';
upgrades = [
{
name: 'Luminous grandmas',
quote: 'Your grandmas have called their long-lost relatives to help them bake more cookies.',
building: buildings.grandma,
tier,
},
{
name: 'Luminous seeds',
quote:
"Through your advancements in the field of agriculture, you've discovered some sort of luminescent seed. It's still unclear whether it's safe or not, but it yields more crops than normal ones.",
building: buildings.farm,
tier,
},
{
name: 'Luminous refining',
quote:
'By mixing the cookie dough you mine with a mysterious luminescent powder, you are able to make them yield more and become tastier.',
building: buildings.mine,
tier,
},
{
name: 'Luminous labor',
quote:
"By doing some shenanigans to a strange luminous powder that was recently discovered, you managed to create an entirely new workforce. They're fast, efficient and don't need to rest!",
building: buildings.factory,
tier,
},
{
name: 'Luminous cash',
quote:
"You've created a new currency coated in a strange luminous powder. You don't really know what it is or where it came from, but gold is shiny, so it's obviously more valuable, right?",
building: buildings.bank,
tier,
},
{
name: 'Luminous temples',
quote: 'This strange powder shines. You put it all around your temples. Gods like shiny things.',
building: buildings.temple,
tier,
},
{
name: 'Luminous catalyst',
quote:
'Wizards have discovered that by condensing mana, they are able to make a mysterious luminescent powder. This, in turn, is highly effective as a catalyst when using spells.',
building: buildings.wizardTower,
tier,
},
{
name: 'Luminous fuel',
quote:
'By mixing normal fuel and a solution of a mysterious luminous powder and alchohol, it becomes highly more potent.',
building: buildings.shipment,
tier,
},
{
name: 'Luminous transmutation',
quote: "This mysterious luminous powder is very dense, so you're able transmute it into a lot more cookies.",
building: buildings.alchemyLab,
tier,
},
{
name: 'Luminous portal',
quote: "The portal to heaven will surely have a godly light, right? And it'll obviously be packed with cookies.",
building: buildings.portal,
tier,
},
{
name: 'Luminous travel',
quote:
"By using a strange luminous powder in your time machines, you can know where exactly you're going in spacetime more precisely. Yes, it works. Don't ask how.",
building: buildings.timeMachine,
tier,
},
// Seriously?
{
name: 'Luminous condensers',
building: buildings.antimatterCondenser,
tier,
},
{
name: 'Luminous prism',
quote:
"Well, you convert light into cookies. So if the prism is coated in luminous powder it'll obviously create more cookies.",
building: buildings.prism,
tier,
},
{
name: 'Luminous dice',
quote: "Now there are sparks whenever you spawn cookies. It's entertaining, so people do it more often.",
building: buildings.chancemaker,
tier,
},
// Seriously?
{
name: 'Luminous fractals',
building: buildings.fractalEngine,
tier,
},
{
name: 'Luminous hardware',
quote: 'Hey, it works okay? RGB mice and keyboard boost computer performance.',
building: buildings.javascriptConsole,
tier,
},
{
name: 'Luminous universe',
quote:
'Brand new galaxies to explore, full with a strange luminous material everywhere... Regardless, that means tons of extra cookies to get!',
building: buildings.idleverse,
tier,
},
];
return upgrades;
};
const misfortune = (): ICreateTieredUpgradeDTO[] => {
const tier = 'misfortune';
const priceFunc: PriceFunc = upgrade => {
return Math.min(upgrade.basePrice, Game.unbuffedCps * 60 * 60 * 24);
};
const order = 19101;
upgrades = [
{
name: 'Misfortune #501',
quote: 'The decay of a finger will leave 4 others still pointing.',
building: buildings.cursor,
tier,
order,
},
{
name: 'Misfortune #502',
quote: 'A wrinkle is a crack on the only home you have.',
building: buildings.grandma,
tier,
order,
},
{
name: 'Misfortune #503',
// Kiz3r's
quote: 'Famine is inevitable.',
building: buildings.farm,
tier,
order,
},
{
name: 'Misfortune #504',
// Kiz3r's
quote: "The collapse under your life's work.",
building: buildings.mine,
tier,
order,
},
{
name: 'Misfortune #505',
quote: 'True worth is not in what you make yourself, but in what you make others do for you.',
building: buildings.factory,
tier,
order,
},
{
name: 'Misfortune #506',
quote: 'The value of money means everything to a banker.',
building: buildings.bank,
tier,
order,
},
{
name: 'Misfortune #507',
quote: 'No idol deserves worship.',
building: buildings.temple,
tier,
order,
},
{
name: 'Misfortune #508',
quote: 'Magic is about two things — deceiving and pleasing.',
building: buildings.wizardTower,
tier,
order,
},
{
name: 'Misfortune #509',
quote: 'Every mile travelled maddens you just as much.',
building: buildings.shipment,
tier,
order,
},
{
name: 'Misfortune #510',
// Kiz3r's
quote: "You're turning diamonds into coal.",
building: buildings.alchemyLab,
tier,
order,
},
{
name: 'Misfortune #511',
// Kiz3r's
quote: 'Welcoming unwanted visitors.',
building: buildings.portal,
tier,
order,
},
{
name: 'Misfortune #512',
// Kiz3r's
quote: 'You cannot run from time.',
building: buildings.timeMachine,
tier,
order,
},
{
name: 'Misfortune #513',
quote: 'The world is made of what we take from it.',
building: buildings.antimatterCondenser,
tier,
order,
},
{
name: 'Misfortune #514',
quote: 'Staring at endless darkness can blind you forever from the light.',
building: buildings.prism,
tier,
order,
},
{
name: 'Misfortune #515',
// Kiz3r's
quote: "Life's the gamble you will never win.",
building: buildings.chancemaker,
tier,
order,
},
{
name: 'Misfortune #516',
// Kiz3r's
quote: 'Losing yourself by finding others.',
building: buildings.fractalEngine,
tier,
order,
},
{
name: 'Misfortune #517',
quote: "If things are working in your computer, they won't in others'.",
building: buildings.javascriptConsole,
tier,
order,
},
{
name: 'Misfortune #518',
quote: 'There are too many of everyone, including you.',
building: buildings.idleverse,
tier,
order,
},
{
name: 'Misfortune #600',
description: 'Upgrades and buildings cost <b>-1%</b>; you gain <b>+1%</b> CpS.',
quote: 'True poverty is counted in betrayals.',
price: misfortunePrice * 1e5,
priceFunc,
icon: [0, 0],
tier,
order,
},
{
name: 'Misfortune #601',
description: 'You gain <b>+6%</b> CpS.',
quote: 'Some people dream of escaping misery; others dream of cookies.',
price: misfortunePrice * 1e8,
priceFunc,
icon: [0, 0],
tier,
order,
},
{
name: 'Misfortune #602',
description:
'You gain <b>+1%</b> of your regular CpS while the game is closed <small>(provided you have the Twin Gates of Transcendence heavenly upgrade)</small>.',
// Kiz3r's
quote: "Help, I'm trapped in a CC mod!",
price: misfortunePrice * 1e11,
priceFunc,
icon: [0, 0],
tier,
order,
},
{
name: 'Misfortune #603',
description: 'You gain <b>more CpS</b> the more milk you have.',
quote: 'Believe the superstitions; black cats are bad luck.',
price: misfortunePrice * 1e14,
priceFunc,
icon: [1, 0],
tier,
kitten: true,
order,
},
{
name: 'Misfortune #604',
description: 'Clicking gains <b>+1% of your CpS</b>.',
// Think of something better
quote: 'Remember to not stay in touch.',
price: misfortunePrice * 1e11,
priceFunc,
icon: [2, 0],
tier,
order,
},
// {
// name: 'Misfortune #666',
// description: 'Grandmas are <b>twice</b> as efficient.',
// // Kiz3r's
// quote: 'Old but not wise.',
// price: 6.666e51,
// icon: [19, 2],
// tier,
// order,
// },
];
return upgrades;
};
const createHook = (): void => {
Upgrades([...buildingCookies()]);
TieredUpgrades([...halo(), ...aura(), ...luminous(), ...misfortune()]);
HeavenlyUpgrades([
{
name: 'Box of chocolate buildings',
description: 'Contains an assortment of cookies shaped like the buildings that produce those same cookies.',
quote: "Wait, I've seen these before...",
price: 1000,
icon: [1, 1],
parents: ['Starter kit'],
position: [-460, -430],
order: 256,
},
{
name: 'Misfortune cookies',
description: 'The news ticker may occasionally have <b>misfortunes</b>, which may be clicked for "something".',
quote: "These taste quite bad — but then again, what's even the point?",
price: 66666666666,
icon: [0, 1],
parents: ['Distilled essence of redoubled luck'],
position: [75, 495],
order: 644,
},
]);
};
export default createHook;
|
Hyoretsu/ccreddit-mod
|
src/customFuncs/HeavenlyUpgrades.ts
|
<reponame>Hyoretsu/ccreddit-mod<gh_stars>1-10
import { modName, upgradeIconsUrl } from '@config';
const HeavenlyUpgrades = (data: ICreateHeavenlyUpgradeDTO[]): void => {
data.forEach(upgradeData => {
const desc = `${upgradeData.description}${upgradeData.quote ? `<q>${upgradeData.quote}</q>` : ''}`;
const icon: Game.Icon = [upgradeData.icon[0], upgradeData.icon[1], upgradeIconsUrl];
const upgrade = new Game.Upgrade(upgradeData.name, desc, upgradeData.price, icon);
upgrade.mod = modName;
upgrade.pool = 'prestige';
upgrade.order = upgradeData.order;
upgradeData.parents.forEach(parent => {
upgrade.parents.push(Game.Upgrades[parent]);
});
[upgrade.posX, upgrade.posY] = upgradeData.position;
Game.PrestigeUpgrades.push(upgrade);
});
};
export default HeavenlyUpgrades;
|
ndabAP/vuetify
|
src/globals.d.ts
|
/* eslint-disable max-len */
import {
VueConstructor,
ComponentOptions,
FunctionalComponentOptions,
VNodeData
} from 'vue'
import { CombinedVueInstance, Vue } from 'vue/types/vue'
import {
RecordPropsDefinition,
ThisTypedComponentOptionsWithArrayProps,
ThisTypedComponentOptionsWithRecordProps
} from 'vue/types/options'
declare global {
interface Window {
Vue: VueConstructor
}
interface HTMLImageElement {
decode: () => Promise<never>
}
function parseInt(s: string | number, radix?: number): number
function parseFloat(string: string | number): number
export const __VUETIFY_VERSION__: string
export const __REQUIRED_VUE__: string
}
declare module 'vue/types/vue' {
export type OptionsVue<Instance extends Vue, Data, Methods, Computed, Props, Options = {}> = VueConstructor<
CombinedVueInstance<Instance, Data, Methods, Computed, Props> & Vue,
Options
>
export interface Vue {
_uid: number
/** bindObjectListeners */
_g (data: VNodeData, value: {}): VNodeData
}
export interface RawComponentOptions<
V extends Vue = Vue,
Data = {} | undefined,
Methods = {} | undefined,
Computed = {} | undefined,
Props = {} | undefined
> {
name?: string
data: Data
methods: Methods
computed: {
[C in keyof Computed]: (this: V) => Computed[C]
}
props: Props
}
interface VueConstructor<
V extends Vue = Vue,
Options = Record<string, any>
> {
version: string
/* eslint-disable-next-line camelcase */
$_vuetify_subcomponents?: Record<string, VueConstructor>
options: Options
extend<Data, Methods, Computed, Options, PropNames extends string = never> (options?: ThisTypedComponentOptionsWithArrayProps<V, Data, Methods, Computed, PropNames> & Options): OptionsVue<V, Data, Methods, Computed, Record<PropNames, any>, Options>
extend<Data, Methods, Computed, Props, Options> (options?: ThisTypedComponentOptionsWithRecordProps<V, Data, Methods, Computed, Props> & Options): OptionsVue<V, Data, Methods, Computed, Props, Options>
extend<Options, PropNames extends string = never> (definition: FunctionalComponentOptions<Record<PropNames, any>, PropNames[]> & Options): OptionsVue<V, {}, {}, {}, Record<PropNames, any>, Options>
extend<Props, Options> (definition: FunctionalComponentOptions<Props, RecordPropsDefinition<Props>> & Options): OptionsVue<V, {}, {}, {}, Props, Options>
extend<V extends Vue = Vue> (options?: ComponentOptions<V> & Options): OptionsVue<V, {}, {}, {}, {}, Options>
}
}
|
ndabAP/vuetify
|
src/mixins/routable.ts
|
<filename>src/mixins/routable.ts
import Vue, { VNodeData } from 'vue'
import { PropValidator } from 'vue/types/options'
import Ripple from '../directives/ripple'
export default Vue.extend({
name: 'routable',
directives: {
Ripple
},
props: {
activeClass: String,
append: Boolean,
disabled: Boolean,
exact: {
type: Boolean,
default: undefined
} as PropValidator<boolean | undefined>,
exactActiveClass: String,
href: [String, Object],
to: [String, Object],
nuxt: Boolean,
replace: Boolean,
ripple: [Boolean, Object],
tag: String,
target: String
},
methods: {
/* eslint-disable-next-line no-unused-vars */
click (e: MouseEvent): void { /**/ },
generateRouteLink (classes: any) {
let exact = this.exact
let tag
const data: VNodeData = {
attrs: { disabled: this.disabled },
class: classes,
props: {},
directives: [{
name: 'ripple',
value: (this.ripple && !this.disabled) ? this.ripple : false
}] as any, // TODO
[this.to ? 'nativeOn' : 'on']: {
...this.$listeners,
click: this.click
}
}
if (typeof this.exact === 'undefined') {
exact = this.to === '/' ||
(this.to === Object(this.to) && this.to.path === '/')
}
if (this.to) {
// Add a special activeClass hook
// for component level styles
let activeClass = this.activeClass
let exactActiveClass = this.exactActiveClass || activeClass
// TODO: apply only in VListTile
if ((this as any).proxyClass) {
activeClass += ' ' + (this as any).proxyClass
exactActiveClass += ' ' + (this as any).proxyClass
}
tag = this.nuxt ? 'nuxt-link' : 'router-link'
Object.assign(data.props, {
to: this.to,
exact,
activeClass,
exactActiveClass,
append: this.append,
replace: this.replace
})
} else {
tag = (this.href && 'a') || this.tag || 'a'
if (tag === 'a' && this.href) data.attrs!.href = this.href
}
if (this.target) data.attrs!.target = this.target
return { tag, data }
}
}
})
|
ndabAP/vuetify
|
src/directives/scroll.ts
|
<filename>src/directives/scroll.ts
import { VNodeDirective } from 'vue/types/vnode'
interface ScrollHTMLElement extends HTMLElement {
_onScroll?: {
callback: EventListenerOrEventListenerObject
options: boolean | AddEventListenerOptions
target: EventTarget
}
}
interface ScrollVNodeDirective extends VNodeDirective {
arg: string
value: EventListenerOrEventListenerObject
options?: boolean | AddEventListenerOptions
}
function inserted (el: ScrollHTMLElement, binding: ScrollVNodeDirective) {
const callback = binding.value
const options = binding.options || { passive: true }
const target = binding.arg ? document.querySelector(binding.arg) : window
if (!target) return
target.addEventListener('scroll', callback, options)
el._onScroll = {
callback,
options,
target
}
}
function unbind (el: ScrollHTMLElement) {
if (!el._onScroll) return
const { callback, options, target } = el._onScroll
target.removeEventListener('scroll', callback, options)
delete el._onScroll
}
export default {
inserted,
unbind
}
|
vamtiger-project/vamtiger-copy
|
build/vamtiger-copy.d.ts
|
export { default as copy } from './copy';
|
vamtiger-project/vamtiger-copy
|
build/types.d.ts
|
export declare enum StringConstant {
slash = "/"
}
export declare enum CommandlineArguments {
source = "source",
destination = "destination",
exclude = "exclude",
help = "help"
}
export declare enum ShortCommandlineArguments {
source = "s",
destination = "d",
exclude = "e",
help = "h"
}
export declare enum CommandlineArgumentsDescription {
source = "Source path",
destination = "Destination path",
exclude = "Patterns to exclude",
help = "List commandline options"
}
export interface ICopy {
source: string;
destination: string;
exclude?: string;
currentWorkingDirectory?: string;
}
export interface IGetGroupedFolders {
paths: string[];
}
|
vamtiger-project/vamtiger-copy
|
build/copy.d.ts
|
import { ICopy } from './types';
export default function ({ source: currentSource, destination: currentDestination, exclude: pattern, currentWorkingDirectory }: ICopy): Promise<void>;
|
bsnc-conlab/hdacjs-authorization-ui
|
src/js/KeyListNew.tsx
|
import * as React from 'react';
import { generatedata } from './lib/generatedata';
import * as ReactDOM from 'react-dom'
import JqxButton from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxbuttons';
import JqxInput from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxinput';
import JqxDropDownList, { IDropDownListProps } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxdropdownlist';
import JqxGrid, { IGridProps, jqx } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxgrid';
import '../effect/jqx.css';
export interface IState extends IGridProps {
dropDownSource: IDropDownListProps['source'];
}
export default class KeyListNew extends React.PureComponent<{storage: number, delete: Function}, IState> {
screen = window.outerWidth;
private myGrid = React.createRef<JqxGrid>();
private mySelectRowBtn = React.createRef<JqxButton>();
private myInput1 = React.createRef<JqxInput>();
private selectedRowIndex = React.createRef<HTMLSpanElement>();
private unselectedRowIndex = React.createRef<HTMLSpanElement>();
private selected = 0;
constructor(props: {storage: number, delete: Function}) {
super(props);
this.scrollToBtnOnClick = this.scrollToBtnOnClick.bind(this);
this.enableHoverOnChange = this.enableHoverOnChange.bind(this);
this.myGridOnRowSelect = this.myGridOnRowSelect.bind(this);
const source: any = {
datafields: [
{ name: 'no', type: 'number' },
{ name: 'address', type: 'string' },
{ name: 'UncomperssedPub', type: 'string' },
{ name: 'ComperssedPub', type: 'string' },
{ name: 'pri', type: 'string' },
{ name: 'isEnc', type: 'string' },
],
datatype: 'array',
localdata: generatedata(this.props.storage, false)
};
const rendertoolbar = (toolbar: any): void => {
const deleteRowClick = () => {
const selectedrowindex = this.myGrid.current!.getselectedrowindex();
const rowscount = this.myGrid.current!.getdatainformation().rowscount;
if (selectedrowindex >= 0 && selectedrowindex < parseFloat(rowscount!)) {
const id = this.myGrid.current!.getrowid(selectedrowindex);
var keys = Object.keys(localStorage);
var value = JSON.parse(localStorage.getItem(keys[selectedrowindex])!);
localStorage.removeItem(value.address);
this.myGrid.current!.deleterow(id);
this.props.delete();
}
(document.getElementById('signIn2') as HTMLInputElement).value = "";
(document.getElementById('signIn2') as HTMLInputElement).removeAttribute("disabled");
}
ReactDOM.render(
<div>
<div id="buttonContainer1" style={{ float: 'right', marginRight: '5px' }}>
<JqxButton onClick={deleteRowClick} height={35} width={150} value={'Delete Selected Row'} />
</div>
</div>,
toolbar[0]
);
};
this.state = {
columns: [
{ text: 'Address', datafield: 'address', width: (window.outerWidth - 150) / 4 },
{ text: 'Uncomperssed Pubkey', datafield: 'UncomperssedPub', width: (window.outerWidth - 150) / 4 },
{ text: 'Comperssed Pubkey', datafield: 'ComperssedPub', width: (window.outerWidth - 150) / 4 },
{ text: 'Privatekey', datafield: 'pri', width: (window.outerWidth - 150) / 4 },
{ text: 'Is Encrypted', datafield: 'isEnc', width: 80 },
],
dropDownSource: ['none', 'single row', 'multiple rows', 'multiple rows extended'],
ready: () => {
this.myGrid.current!.selectrow(2);
},
rendertoolbar,
source: new jqx.dataAdapter(source)
}
}
componentDidUpdate(prevProps: { storage: number; }, prevState: any) {
if (this.props.storage !== prevProps.storage) {
const source: any = {
datafields: [
{ name: 'no', type: 'number' },
{ name: 'address', type: 'string' },
{ name: 'UncomperssedPub', type: 'string' },
{ name: 'ComperssedPub', type: 'string' },
{ name: 'pri', type: 'string' },
{ name: 'isEnc', type: 'string' },
],
datatype: 'array',
localdata: generatedata(this.props.storage, false)
};
this.setState({
...this.state,
source: new jqx.dataAdapter(source)
})
}
}
public render() {
return (
<div style={{ fontSize: '13px', fontFamily: 'Verdana', float: 'left' }}>
<JqxGrid ref={this.myGrid} onRowselect={this.myGridOnRowSelect}
width={this.screen - 50} height={350} source={this.state.source} columns={this.state.columns} style={{ float: 'left', position: 'relative', left: '25px' }}
showtoolbar={true} rendertoolbar={this.state.rendertoolbar} />
<div style={{ marginTop: '20px' }}>
</div>
</div>
);
}
private scrollToBtnOnClick(): void {
const index = parseInt(this.myInput1.current!.getOptions('value'), 10);
if (!isNaN(index)) {
this.myGrid.current!.ensurerowvisible(index);
}
};
private enableHoverOnChange(event: any): void {
this.myGrid.current!.setOptions({ enablehover: event.args.checked });
};
private myGridOnRowSelect(event: any): void {
this.selected = event.args.rowindex;
var keys = Object.keys(localStorage);
var addr = keys[this.selected];
var value = JSON.parse(localStorage.getItem(addr)!);
if (value.isEncrypted == false) {
(document.getElementById('signIn3') as HTMLInputElement).style.display = "none";
(document.getElementById('signIn3') as HTMLInputElement).value = "";
(document.getElementById('aTag_pin') as HTMLInputElement).style.display = "none";
(document.getElementById('effectDecIn4') as HTMLInputElement).style.display = "none";
(document.getElementById('rsaDecIn3') as HTMLInputElement).style.display = "none";
(document.getElementById('aTag_pin2') as HTMLInputElement).style.display = "none";
(document.getElementById('aTag_pin3') as HTMLInputElement).style.display = "none";
}
else {
(document.getElementById('signIn3') as HTMLInputElement).style.display = "block";
(document.getElementById('aTag_pin') as HTMLInputElement).style.display = "block";
(document.getElementById('effectDecIn4') as HTMLInputElement).style.display = "block";
(document.getElementById('rsaDecIn3') as HTMLInputElement).style.display = "block";
(document.getElementById('aTag_pin3') as HTMLInputElement).style.display = "block";
(document.getElementById('aTag_pin2') as HTMLInputElement).style.display = "block";
}
(document.getElementById('signIn2') as HTMLInputElement).value = value.privateKey;
sessionStorage.setItem('selected', addr);
(document.getElementById('signIn2') as HTMLInputElement).setAttribute("disabled", "disabled");
};
}
|
bsnc-conlab/hdacjs-authorization-ui
|
src/js/lib/generatedata.ts
|
interface INameToValueMap
{
[key: string]: any;
}
export function generatedata(rowscount?: number, hasNullValues?: boolean): any[] {
let data = new Array();
if (rowscount == undefined) rowscount = 100;
var keys = Object.keys(localStorage);
for (let i = 0; i < rowscount; i++) {
let row: INameToValueMap = {};
let value = JSON.parse(localStorage.getItem(keys[i])!);
row['no'] = i+1;
row['address'] = value.address;
row['UncomperssedPub'] = value.uncompressedPubkey
row['ComperssedPub'] = value.compressedPubkey
row['pri'] = value.privateKey;
row['isEnc'] = value.isEncrypted;
let date = new Date();
date.setFullYear(2019, Math.floor(Math.random() * 11), Math.floor(Math.random() * 27));
date.setHours(0, 0, 0, 0);
row['date'] = date;
data[i] = row;
}
return data;
}
export function generateData(rowscount?: number): any[] {
return generatedata(rowscount);
}
|
qsmalljr/vhl
|
vhl-test/platforms/android/app/src/main/assets/app/clinicalcare/clinicalcare-view-model.ts
|
import { Observable } from "data/observable";
const observableModule = require("data/observable");
var utilsModule = require("tns-core-modules/utils/utils");
export class clinicalcareViewModel extends Observable {
constructor() {
super();
var sections = [
{ name: "CALIFORNIA", desc: "Stanford Hospital and Clinics/Stanford University School of Medicine" , contact: "Contact: <NAME>, Clinic Coordinator", tel: "Tel: 650.736.0262; Fax: 650.495.6813", email: "E-mail: <EMAIL>", web: "Click for Website", adult: "ADULT ONLY"},
{ name: "CONNECTICUT", desc: "Yale University Hospital" , contact: "Contact: <NAME>, NP or <NAME>, PCN", tel: "Tel: 203.200.4DNA (4362)", email: "E-mail: <EMAIL> or <EMAIL>", web: "Click for Website", adult: "ADULT AND PEDIATRIC" },
{ name: "ILLINOIS", desc: "University of Chicago" , contact: "Contact: <NAME>, MS, CGC, Genetic Counselor", tel: "Tel: 773.702.4749; Fax: 773.834.3834", email: "E-mail: <EMAIL>", web: "Click for Website", adult: "ADULT AND PEDIATRIC" },
{ name: "MASSACHUSETTS", desc: "Massachusetts General Hospital, Boston" , contact: "Contact: <NAME>, MD", tel: "Tel: 617.724.3404; Fax: 617.726.9418", email: "E-mail: <EMAIL>", web: "Click for Website", adult: "" },
{ name: "MICHIGAN", desc: "University of Michigan Medical Center, Ann Arbor" , contact: "Contact: <NAME>, MS, CGC, Genetic Counselor", tel: "Tel: 734.647.0822", email: "E-mail: <EMAIL>", web: "Click for Website", adult: "" },
{ name: "NEW YORK", desc: "Columbia University Medical Center, New York Presbyterian Hospital, New York City" , contact: "Contact: <NAME>, MS, CGC, Genetic Counselor", tel: "Tel: 212.305.0190; Fax: 212.305.0322", email: "E-mail: <EMAIL>", web: "Click for Website", adult: "ADULT AND PEDIATRIC" },
{ name: "<NAME>", desc: "University of North Carolina, Lineberger Cancer Center, Chapel Hill, NC" , contact: "Contact: <NAME>, NP", email: "E-mail: <EMAIL>", web: "Click for Website", adult: "ADULT AND PEDIATRIC" },
{ name: "OHIO", desc: "<NAME>" , contact: "Contact: <NAME>, MS, LGC, Genetic Counselor", tel: "Tel: 216.445.6798; Fax: 216.445.6935", email: "E-mail: <EMAIL>", web: "Click for Website", adult: "ADULT AND PEDIATRIC" },
{ name: "PENNSYLVANIA", desc: "Hospital of the University of Pennsylvania, Philadelphia" , contact: "Contact: <NAME>", tel: "Tel: 215.662.4740; Fax: 215.614.0298", email: "E-mail: <EMAIL>", web: "Click for Website", adult: "ADULT AND PEDIATRIC" },
{ name: "TENNESSEE", desc: "Vanderbilt Hereditary Cancer Clinic, Nashville" , contact: "Contact: <NAME>, APRN, MSc, MSN, ANP-BC, AGN-BC", tel: "Tel: 615.343.7400; Fax: 615.343.3343", email: "Email: <EMAIL>;", web: "", adult: "" },
{ name: "VIRGINIA", desc: "University of Virginia, Charlottesville" , contact: "Contact: <NAME>, RN, and <NAME>", tel: "Tel: 434.243.2757; Fax: 434.243.5634", email: "Email: <EMAIL>", web: "Click for Website", adult: "ADULT AND PEDIATRIC" },
];
this.set("sections", sections);
var sections1 = [
{ name: "ALABAMA", desc: "University of Alabama at Birmingham" , contact: "Contact: <NAME>, MS, CGC, Dept. of Genetics", tel: "Tel: 205.996.2916", email: "E-mail: <EMAIL>", web: "Click for Website", adult: ""},
{ name: "ARIZONA", desc: "<NAME>, Scottsdale" , contact: "Contact: <NAME>, MS, CGC", tel: "Tel. 480.342.4800; Fax: 480.301.6356", email: "E-mail: <EMAIL>", web: "Click for Website", adult: "" },
{ name: "CALIFORNIA", desc: "University of California, Los Angeles (UCLA)" , contact: "Contact: <NAME>", tel: "Tel: 310.206.5930", email: "E-mail: <EMAIL>", web: "", adult: "" },
{ name: "COLORADO", desc: "University of Colorado, Denver" , contact: "Contact: <NAME>, MSN", tel: "Tel: 720.848.8570", email: "E-mail: <EMAIL>", web: "", adult: "" },
{ name: "FLORIDA", desc: "University of Miami" , contact: "Contact: <NAME>, MS, CGC", tel: "Tel: 305.243.3627; Fax: 305.243.3919", email: "E-mail: <EMAIL>", web: "", adult: "", desc2:"Moffitt Cancer Center, Tampa", contact2:"Contact: <NAME>, RN, BSN. Primary Nurse for Dr. Spiess – GU Clinic", tel2:"Tel: 813.745.8119; Fax: 813.449.6726", email2:"E-mail: <EMAIL>"},
{ name: "INDIANA", desc: "Indiana University, Simon Cancer Center, Indianapolis" , contact: "Contact: <NAME>, RN, BSN, Kidney Cancer Services Clinic", tel: "Tel: 317.962.0867", email: "Email: <EMAIL>", web: "", adult: "" },
{ name: "IOWA", desc: "University of Iowa Hospitals & Clinics, Iowa City" , contact: "Contact: <NAME>, ARNP", tel: "Tel: 319.356.4686; Fax: 319.356.3347", email: "E-mail: <EMAIL>", web: "", adult: "", desc2:"Or", contact2:"Contact: <NAME>, DNP, RN", tel2:"Tel: 319.467.8147; Fax: 319.356.3347", email2:"E-mail: <EMAIL>" },
{ name: "KANSAS", desc: "University of Kansas Medical Center, Kansas City" , contact: "Contact: <NAME>, MS, CGC", tel: "Tel: 913.588.3671; Fax: 913.588.4060", email: "E-mail: <EMAIL>", web: "", adult: "", desc2:"Or", contact2:"Contact: <NAME>, APRN, FNP–BC (for neuro)", tel2:"Tel: 913.574.1049", email2:"E-mail: <EMAIL>" },
{ name: "MARYLAND", desc: "Johns Hopkins Hospital, Baltimore" , contact: "Contact: <NAME>, Senior Medical Concierge", tel:"Tel: 410.464.6555 x309", email: "Email: <EMAIL>", web: "Click for Website", adult: "" },
{ name: "MASSACHUSETTS", desc: "Lahey Clinic Medical Center, Burlington" , contact: "Contact: <NAME>. Tel: 781.744.2511; Fax: 781.564.5429", tel: "", email: "E-mail: <EMAIL>hey.org", web: "Click for Website", adult: "" },
{ name: "MINNESOTA", desc: "<NAME>, Rochester" , contact: "Contact: Dr. <NAME>, Medical Genetics", tel: "Tel: 507.284.3215; Fax: 507.284.1067", email: "", web: "Click for Website", adult: "", desc2:"University of Minnesota, Minneapolis", contact2:"Contact: <NAME>, APRN-CNS", tel2:"Tel: 612.626.9898; Fax: 612.625.4406", email2:"E-mail: <EMAIL>"},
{ name: "MISSOURI", desc: "The Alvin J. Siteman Cancer Center (SCC) at Barnes-Jewish Hospital and Washington University School of Medicine, St. Louis" , contact: "Contact: <NAME>", tel: "Tel: 314.454.8775; Fax: 314.454.5244", email: "E-mail: <EMAIL>", web: "", adult: "" },
{ name: "<NAME>", desc: "Memorial Sloan Kettering Cancer Center, New York City" , contact: "Contact: <NAME>, BSN, CAPA", tel: "Tel: 646.422.4432; Fax: 212.452.3323", email: "Email: <EMAIL>", web: "Click for Website", adult: "", desc2:"Montefiore Einstein Center for Cancer Care, Bronx", contact2:"Contact: <NAME>, NP-C", tel2:"Tel: 718.862.8840 ext 236; Fax: 718.862.8852", email2:"E-mail: <EMAIL>", desc3:"SUNY Upstate Medical University, Syracuse", contact3:"Contact: <NAME>", tel3:"Tel: 315-464-6031; Fax: 315-464-6117", email3:"E-mail: <EMAIL>" },
{ name: "OHIO", desc: "Ohio State University Wexner Medical Center" , contact: "Contact: <NAME>, NP", tel: "Tel: 614.293-4448", email: "E-mail: <EMAIL>", web: "", adult: "" },
{ name: "PENNSYLVANIA", desc: "University of Pittsburgh, Pittsburgh" , contact: "Contact: <NAME>, MS, CGC", tel: "Tel: 800.454.8156 or 412-641.1466; Fax: 412-641.1132", email: "E-mail: <EMAIL>", web: "", adult: "" },
{ name: "UTAH", desc: "Huntsman Cancer Institute, Salt Lake City" , contact: "Contact: <NAME>, MS, MPH, CGC", tel: "Tel: 801.213.5774; Fax: 801.585.5763", email: "Email: <EMAIL>", web: "Click for Website", adult: "" },
];
this.set("sections1", sections1);
var sections2 = [
{ name:"ARGENTINA", desc:"Hospital Italiano de Buenos Aires, Buenos Aires", contact:"Contact, Adults: Valeria de Miguel, MD, Endocrinology, Metabolism and Nuclear Medicine Unit.", tel:"Tel: +541149590200, ext: 4849/8442; Fax: +541149590323", email:"E-mail: <EMAIL>", contact2:"Contact, Pediatrics: <NAME>, PhD.", tel2:"Tel: +5441149635931, ext: 129; Fax: +541149635930", email2:"E-mail: <EMAIL>", desc2:"Hospital Privado Centro Médico de Córdoba. <NAME>, Servicio de Nefrología.", email3:"E-mail: <EMAIL>"},
{ name:"AUSTRALIA", desc:"Prince of Wales Hospital, Sydney. Hereditary Cancer Clinic.", contact:"", tel:"", email:"E-mail: <EMAIL>", web:"", adult:""},
{ name:"BELGIUM", desc:"University of Brussels, Brussels. Neurosurgery", contact:"Contact: Professor Dr. <NAME>", tel:"Tel. +02.477.55.14; Fax. +02.477.55.70", email:"Email: <EMAIL>", desc2:"Nephrology and Internal Medicine", contact2:"Contact: Dr. <NAME>", tel2:"Tel. +02.477.60.55", email2:"Email: <EMAIL>"},
{ name:"CANADA", desc:"Memorial University of Newfoundland, St. John’s, NF.", contact:"Contact: Dr. <NAME>, Medical Genetics.", tel:"Tel: 1-709.777.6242 Fax: 1-709.777.7317", email:"E-mail: <EMAIL>", desc2:"Toronto General Hospital, Toronto, ON.", contact2:"Contact, Adults: <NAME>, RN.", tel2:"Tel: 1.416.340.3111 x6243", email2:"E-mail: <EMAIL>", desc3:"Pediatrics: The Hospital for Sick Children, Toronto, ON", contact3:"Contact: <NAME>, MSc., Cancer Genetics Program", tel3:"Tel: 416-813-8597", email3:"E-mail: <EMAIL>"},
{ name:"CHINA", desc:"Peking University First Hospital, Beijing,", contact:"Contact: <NAME>, MD.,", tel:"Tel: +86 (10) 83575101; Fax: +86 (10) 66552211", email:"E-mail: <EMAIL>", web:"", adult:"ADULT AND PEDIATRIC"},
{ name:"FRANCE", desc:"Necker Hospital and Kremlin-Bicêtre Hospital, Paris.", contact:"Contact: <NAME>, MD, Oncogenetics.", tel:"Tel/Fax: +33 (1) 49.59.67.28", email:"E-mail: <EMAIL>", web:"Click for Website!", adult:""},
{ name:"GERMANY", desc:"Albert-Ludwigs University Medical Center Freiburg.", contact:"Contact: <NAME>, MD, Nephrology", tel:"Tel: +49.761.27034140; Fax: +49.761.34140", email:"E-mail: <EMAIL>", web:"", adult:""},
{ name:"INDIA", desc:"Amrita Institute of Medical Sciences, Elamakkara Post, Kochi, Kerala.", contact:"Contact: <NAME>, MD, Neurosurgery.", tel:"Tel: Fax: + 91.484.280.2020", email:"E-mail: <EMAIL>", web:"", adult:""},
{ name:"ISRAEL", desc:"Hadassah University Hospital, Jerusalem.", contact:"Contact: <NAME>, Endocrinology.", tel:"Tel: +972 (0)2.677.8899", email:"E-mail: <EMAIL>", web:"", adult:""},
{ name:"JAPAN", desc:"Kochi Medical School Hospital, Nankoku Kochi.", contact:"Contact: <NAME>, Genetic Counselor. Department of Clinical Genetics", tel:"Tel: 088.866.5811", email:"E-mail: <EMAIL>", web:"", adult:""},
{ name:"THE NETHERLANDS", desc:"University Hospital Utrecht.", contact:"<NAME>, PhD, Internal Medicine.", tel:"", email:"E-mail: r.giles at umcutrecht.nl", web:"", adult:""},
{ name:"POLAND", desc:"Pomeranian Academy of Medicine, Szczecin.", contact:"Contact: <NAME>, MD, Genetics.", tel:"Fax: +48 (91) 4828.450", email:"E-mail: <EMAIL>", web:"", adult:""},
{ name:"SINGAPORE", desc:"National Cancer Centre Singapore.", contact:"Contact: <NAME>, MD, PhD, Medical Oncology.", tel:"Tel: +65.6436.8000", email:"Email: <EMAIL>, <EMAIL>", web:"", adult:""},
{ name:"<NAME>", overview:"Care for VHL and other genetic conditions in the UK is organized under the local genetics centres. People should begin by contacting their local centre, which will network with the major centres as necessary.", desc:"University of Birmingham", contact:"Contact: <NAME>", tel:"Tel: +044.0121.627.2710", email:"Email: <EMAIL>",
desc2:"University of Cambridge", contact2:"Contact: Prof. <NAME>, Dept. of Medical Genetics.", tel2:"Tel: +44.01223.217.054", email2:"Email: <EMAIL>",
desc3:"St. Bartholomew’s Hospital, London", contact3:"Contact: Ms. <NAME>, Neuroendocrine Clinical Nurse Specialist.", tel3:"Tel: +44 (0) 203.465.7264", email3:"Email: <EMAIL>",
desc4:"Churchill Hospital, Oxford", contact4:"Regional Genetics Service", tel4:"Tel: +0114.271.7025"},
];
this.set("sections2", sections2);
}
public donate = function () {
utilsModule.openUrl("https://donatenow.networkforgood.org/1411829?code=orange")
}
public onOpenSurvey = function () {
utilsModule.openUrl("https://docs.google.com/forms/d/1x35igCRZFCvcaeYmY_d5M2xYW1KMUCmLvjJuSQ4ZTbc/viewform?edit_requested=true")
}
public onButtonTap = function (args) {
var websites = [
"https://stanfordhealthcare.org/medical-conditions/cancer/von-hippel-lindau-syndrome.html",
"https://medicine.yale.edu/urology/programs/genitourinary/kidney/hereditary.aspx",
"http://www.uchospitals.edu/specialties/cancer/risk/about/vhl/index.html",
"http://www.massgeneral.org/cancer/about/ccra_rcc.aspx",
"http://www.mcancer.org/endocrine-cancer/familial-neuroendocrine-syndromes/comprehensive-clinical-care-center-von-hippel-lindau-disease",
"http://columbiaspine.org/condition/von-hippel-lindau/",
"https://unclineberger.org/patientcare/programs/vonhippellindau",
"https://my.clevelandclinic.org/health/articles/von-hippel-lindau-disease",
"https://www.pennmedicine.org/for-patients-and-visitors/find-a-program-or-service/translational-medicine-and-human-genetics/von-hippel-lindau-vhl-syndrome-center",
"",
"https://www.mdanderson.org/cancer-types/von-hippel-lindau-disease.html",
"https://neurosciences.uvahealth.com/services/neurocutaneous-disorders/neurocutaneous-conditions/von-hippel-lindau-disease",
];
if(args.index != 9){
utilsModule.openUrl(websites[args.index])
}
}
public onButtonTap1 = function (args) {
var websites1 = [
"https://www.uabmedicine.org/patient-care/conditions/von-hippel-lindau",
"http://www.mayoclinic.org/departments-centers/clinical-genomics/overview/specialty-groups/von-hippel-lindau-clinic",
"",
"",
"",
"",
"",
"",
"http://www.hopkinsmedicine.org/nephrology/patient_care/vhl-care.html",
"https://www.lahey.org/Departments_and_Locations/Departments/Breast_Center/Ebsco_Content/Chemotherapy.aspx?chunkiid=22504",
"http://www.mayoclinic.org/departments-centers/clinical-genomics/overview/specialty-groups/von-hippel-lindau-clinic",
"https://www.mskcc.org/cancer-care/patient-education/frequently-asked-questions-about-von-hippel-lindau-vhl-syndrome",
"",
"",
"",
"http://healthcare.utah.edu/huntsmancancerinstitute/patient-care/clinics-and-care-teams/high-risk-cancer-research-clinics-and-studies/family-cancer-assessment-clinic/von-hippel-lindau.php",
];
utilsModule.openUrl(websites1[args.index])
}
public onButtonTap2 = function (args) {
var websites2 = [
"",
"",
"",
"",
"",
"http://www.predir.org/",
"",
"",
"",
"",
"",
"",
"",
];
if(args.index == 5){
utilsModule.openUrl(websites2[args.index])
}
}
public selectItemTemplate = function (item, index, items) {
if(index == 4 || index == 6 || index == 7 || index == 10){
return "two";
}
else if (index == 12){
return "three";
}
else{
return "one";
}
}
public selectItemTemplate1 = function (item, index, items) {
if(index == 0){
return "argentina";
}
else if(index == 2){
return "belgium";
}
else if(index == 3){
return "canada";
}
else if(index ==13){
return "uk";
}
else{
return "normal";
}
}
}
|
qsmalljr/vhl
|
vhl-test/platforms/android/app/src/main/assets/app/handbook/handbook-view-model.ts
|
<filename>vhl-test/platforms/android/app/src/main/assets/app/handbook/handbook-view-model.ts<gh_stars>0
import { Observable } from "data/observable";
import frameModule = require("tns-core-modules/ui/frame");
var utilsModule = require("tns-core-modules/utils/utils");
export class handbookViewModel extends Observable {
constructor() {
super();
var sections = [
{ name: "What is VHL?", imageSrc: "1" },
{ name: "Possible VHL Manifestations", imageSrc: "2" },
{ name: "Healthy Living for the VHL Family", imageSrc: "3" },
{ name: "Discussing VHL with Your Family", imageSrc: "4" },
{ name: "VHL Research", imageSrc: "5" },
{ name: "Glossary of Medical Terms", imageSrc: "6" },
{ name: "VHL Support Resources", imageSrc: "7" },
];
this.set("sections", sections);
}
public tapAction(args) {
//ADD NAVIGATION CODE HERE
frameModule.topmost().navigate("hbsection" + (args.index + 1) + "/hbsection" + (args.index + 1) + "-page");
}
public donate = function () {
utilsModule.openUrl("https://donatenow.networkforgood.org/1411829?code=orange")
}
}
|
qsmalljr/vhl
|
vhl-test/platforms/android/app/src/main/assets/app/tns_modules/nativescript-pdf-view/pdf-view.common.d.ts
|
<filename>vhl-test/platforms/android/app/src/main/assets/app/tns_modules/nativescript-pdf-view/pdf-view.common.d.ts
import { Property, View } from 'tns-core-modules/ui/core/view';
export declare abstract class PDFViewCommon extends View {
static loadEvent: string;
src: string;
static notifyOfEvent(eventName: string, pdfViewRef: WeakRef<PDFViewCommon>): void;
}
export declare const srcProperty: Property<PDFViewCommon, string>;
|
qsmalljr/vhl
|
vhl-test/platforms/android/app/src/main/assets/app/faq/faq-view-model.ts
|
<gh_stars>0
import { Observable } from "data/observable";
var utilsModule = require("tns-core-modules/utils/utils");
export class faqViewModel extends Observable {
constructor() {
super();
var questions = [
{ name: "What is VHL?", desc: "<NAME> (VHL) is a genetic condition involving the abnormal growth of blood vessels in up to 10 parts of the body.It is caused by a flaw in one gene-- the vhl gene.With no known pharmacological treatment, active surveillance and surgery (as needed) are the only options for VHL patients as they battle a series of tumors throughout their life." },
{ name: "How common is VHL?", desc: "VHL affects 1 in 36,000 people (~10,000 people in the U.S. and 200,000, worldwide) in every ethnic group.The prevalence of VHL is approximately the same prevalence as muscular dystrophy and one-half that of cystic fibrosis." },
{ name: "What is the active surveillance protocol for VHL patients?", desc: "Even young children with VHL need to be monitored for lesions. Most VHL tumors in the eye or ear are best treated as soon as they are found. Other tumors, such as on the kidney or CNS, should be monitored regularly; researchers have defined specific criteria for removal." },
{ name: "What is the VHL Alliance?", desc: "The VHL Alliance (VHLA) is a 501c3 non-profit organization founded in 1993. Today, VHLA is the world's leading organization supporting von Hippel- Landau Syndrome. VHLA funds research, increases awareness, and provides education and support to improve the lives of thousands of people living with VHL." },
{ name: "How can I find the leading VHL specialists?", desc: "The VHLA established the Clinical Care Center (CCC) program to enable people living with VHL to obtain the best possible care from a medical team knowledgeable about this rare disease. VHLA - endorsed CCCs provide effective coordination of care, promote timely surveillance and serve as a source of information and support.Note: an endorsement of a VHL team at a particular hospital does NOT endorse every provider at the hospital. " },
];
this.set("questions", questions);
}
public donate = function () {
utilsModule.openUrl("https://donatenow.networkforgood.org/1411829?code=orange")
}
}
|
qsmalljr/vhl
|
vhl-test/platforms/android/app/src/main/assets/app/ercard/ercard-view-model.ts
|
import { Observable } from "data/observable";
var utilsModule = require("tns-core-modules/utils/utils");
export class ercardViewModel extends Observable {
constructor() {
super();
}
public donate = function () {
utilsModule.openUrl("https://donatenow.networkforgood.org/1411829?code=orange")
}
}
|
qsmalljr/vhl
|
vhl-test/platforms/android/app/src/main/assets/app/calendarmanager/calendarmanager-view-model.ts
|
import { Observable } from 'data/observable';
import { DatePicker } from "ui/date-picker";
export class calendarmanagerViewModel extends Observable {
constructor() {
super();
}
get title(): String {
return <String>this.get("textFieldValue");
}
get year(): Number {
//doesnt work
return <Number>this.get("currentYear");
}
public navBack = function () {
//var title = this.title;
//var year = this.year;
//console.log(year);
}
public onPickerLoaded(args) {
let datePicker = <DatePicker>args.object;
//console.log(datePicker.year);
}
}
|
qsmalljr/vhl
|
vhl-test/platforms/android/app/src/main/assets/app/hbsection7/hbsection7-page.ts
|
import { EventData } from "data/observable";
import { RadSideDrawer } from "nativescript-pro-ui/sidedrawer";
import { topmost } from "ui/frame";
import { NavigatedData, Page } from "ui/page";
import { hbsection7ViewModel } from "./hbsection7-view-model";
/* ***********************************************************
* Use the "onNavigatingTo" handler to initialize the page binding context.
*************************************************************/
export function onNavigatingTo(args: NavigatedData) {
/* ***********************************************************
* The "onNavigatingTo" event handler lets you detect if the user navigated with a back button.
* Skipping the re-initialization on back navigation means the user will see the
* page in the same data state that he left it in before navigating.
*************************************************************/
if (args.isBackNavigation) {
return;
}
const page = <Page>args.object;
page.bindingContext = new hbsection7ViewModel();
}
/* ***********************************************************
* According to guidelines, if you have a drawer on your page, you should always
* have a button that opens it. Get a reference to the RadSideDrawer view and
* use the showDrawer() function to open the app drawer section.
*************************************************************/
export function onDrawerButtonTap(args: EventData) {
const sideDrawer = <RadSideDrawer>topmost().getViewById("sideDrawer");
sideDrawer.showDrawer();
}
|
qsmalljr/vhl
|
vhl-test/platforms/android/app/build/intermediates/assets/F0F1/debug/app/calendar/calendar-view-model.ts
|
import { Observable } from "data/observable";
import calendarModule = require("nativescript-pro-ui/calendar");
import observableModule = require("tns-core-modules/data/observable");
import frameModule = require("tns-core-modules/ui/frame");
import { Color } from "tns-core-modules/color";
import applicationSettingsModule = require("application-settings");
export class CalendarViewModel extends Observable {
constructor() {
super();
//CALENDAR POPULATING STUFF
let now = new Date();
let startDate: Date,
endDate: Date,
event: calendarModule.CalendarEvent;
let colors: Array<Color> = [new Color(200, 188, 26, 214), new Color(220, 255, 109, 130), new Color(255, 55, 45, 255), new Color(199, 17, 227, 10), new Color(255, 255, 54, 3)];
let events: Array<calendarModule.CalendarEvent> = new Array<calendarModule.CalendarEvent>();
event = new calendarModule.CalendarEvent("pooping", new Date(now.getFullYear(),now.getMonth(),23), new Date(now.getFullYear(), now.getMonth(), 25), false);
/*
for (let i = 1; i < 10; i++) {
startDate = new Date(now.getFullYear(), now.getMonth(), 19);
endDate = new Date(now.getFullYear(), now.getMonth(), 20);
event = new calendarModule.CalendarEvent("event " + i, startDate, endDate, false, colors[i * 10 % (colors.length - 1)]);
events.push(event);
if (i % 3 == 0) {
event = new calendarModule.CalendarEvent("second " + i, startDate, endDate, true, colors[i * 5 % (colors.length - 1)]);
events.push(event);
}
}
*/
events.push(event);
//convert events to dictionaries, stringify
//when reading in, convert back from dictionaries to event objects
var dictEvent;
applicationSettingsModule.setNumber("length", events.length);
for(let i = 0; i < events.length; i++){
dictEvent = {
title: events[i].title,
startDate: events[i].startDate.toString(),
endDate: events[i].endDate,
}
applicationSettingsModule.setString("event" + i, JSON.stringify(dictEvent));
}
var length = applicationSettingsModule.getNumber("length");
let tempEvents: Array<calendarModule.CalendarEvent> = new Array<calendarModule.CalendarEvent>();
//convert all back to events
for(var i = 0; i < length; i++){
var eventi = JSON.parse(applicationSettingsModule.getString("event" + i.toString()));
console.log(eventi.title);
console.log(<Date>eventi.startDate);
//let pooper: Date = new Date(2017, 12, 20);
//console.log(pooper);
var tempEvent: calendarModule.CalendarEvent;
//dates stored weird so create new date objects and use them in calendar events
//then push to calendar events array
tempEvent = new calendarModule.CalendarEvent(eventi.title, new Date(eventi.startDate), new Date(eventi.endDate));
tempEvents.push(tempEvent);
}
//set source to show in calendar
this.source = tempEvents;
}
public addEvent(eventData) {
//this event gets fired properly
console.log("add");
let now = new Date();
var events: Array<calendarModule.CalendarEvent> = this.source;
//console.log(events.length);
var event: calendarModule.CalendarEvent;
event = new calendarModule.CalendarEvent("pooping", new Date(now.getFullYear(),now.getMonth(),19), new Date(now.getFullYear(), now.getMonth(), 25), false);
events.push(event);
//save locally
applicationSettingsModule.setString("events", JSON.stringify(events));
this.set("calendarEvents", events);
//events = <Array<calendarModule.CalendarEvent>>JSON.parse(applicationSettingsModule.getString("events"));
//resolve(events);
/*
for(let i = 0; i < events.length; i++){
events[i] = events[i] as calendarModule.CalendarEvent;
}
console.log(typeof(events[1]) == typeof(calendarModule.CalendarEvent));
console.log(events[1].title);
*/
//var poop = new BrowseViewModel();
}
//gets the json string of events and populates the calendar on page load
public loadEvents(){
var events: Array<calendarModule.CalendarEvent> = <Array<calendarModule.CalendarEvent>>JSON.parse(applicationSettingsModule.getString("events"));
}
public deleteEvent(eventData) {
//this event gets fired properly
console.log("delete");
}
//MORE CALENDAR METHODS
set source(value: Array<calendarModule.CalendarEvent>) {
this.set("eventSource", value);
}
get source(): Array<calendarModule.CalendarEvent> {
return <Array<calendarModule.CalendarEvent>>this.get("eventSource");
}
public onDateSelected(args: calendarModule.CalendarSelectionEventData) {
var date: Date = args.date;
var calendar: calendarModule.RadCalendar = <calendarModule.RadCalendar>frameModule.topmost().getViewById("calendar");
var events: Array<calendarModule.CalendarEvent> = calendar.getEventsForDate(date);
this.set("myItems", events);
}
public toggleDropdown(eventData){
//toggle works now
this.set("showDetails", !this.get("showDetails"));
}
}
|
qsmalljr/vhl
|
vhl-test/platforms/android/app/src/main/assets/app/hbsection1/hbsection1-view-model.ts
|
<filename>vhl-test/platforms/android/app/src/main/assets/app/hbsection1/hbsection1-view-model.ts
import { Observable } from "data/observable";
export class hbsection1ViewModel extends Observable {
constructor() {
super();
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/commonBehaviors/gravityBehaviors/gravity-behavior.ts
|
import * as PIXI from "pixi.js";
import { World } from "../../world";
import { GameObject } from "../../abstract/game-object";
export class GravityBehavior {
public gameObject: GameObject;
public gravityTicker: PIXI.Ticker;
constructor(gameObject: GameObject) {
this.gameObject = gameObject;
this.velocityY = 0;
this.gravityTicker = new PIXI.Ticker();
this.gravityTicker.add(this.gravity.bind(this));
this.gravityTicker.start();
}
public gravity(): void {
if (this.velocityY < 10) {
this.velocityY += this.gameObject.gravityPower;
}
if (this.velocityY > 0 && World.isObjectOnGround(this.gameObject)) {
return;
}
this.gameObject.y += this.velocityY;
}
public dispose(): void {
this.gameObject = null;
this.gravityTicker.stop();
this.gravityTicker = null;
}
private get velocityY(): number {
return this.gameObject.velocityY;
}
private set velocityY(value: number) {
this.gameObject.velocityY = value;
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/abstract/game-object.ts
|
<reponame>yordan-kanchelov/flappy-bird-pixijs<filename>src/game/abstract/game-object.ts
import * as PIXI from "pixi.js";
export abstract class GameObject extends PIXI.Sprite {
health: number = 0;
velocityX: number = 0;
velocityY: number = 0;
gravityPower: number = 0;
/**
*
*/
constructor(spriteTexture: PIXI.Texture) {
super(spriteTexture);
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/game-controller.ts
|
import * as PIXI from "pixi.js";
import PixiEventResolver from "pixi-event-resolver";
import getHowlerSound from "../utils/getHowlerSound";
import { GameSettings } from "./game-settings";
import { CollisionChecker } from "../utils/collision-checker";
import { ObstaclesView } from "./obstacles/obstacles-view";
import { GameView } from "./game-view";
import { BirdController } from "./bird/bird-controller";
import { ObstaclesController } from "./obstacles/obstacles-controller";
import { World } from "./world";
import { GameModel } from "./game-model";
export class GameController {
private _view: GameView;
private _model: GameModel;
private _obstaclesController: ObstaclesController;
private _obstaclesView: ObstaclesView;
private _birdController: BirdController;
private _gameScoreText: PIXI.Text;
private _collisionCheckTicker: PIXI.Ticker;
private _scorePointSound: Howl;
private _hitSound: Howl;
constructor(model: GameModel, view: GameView) {
World.getInstance().stage = view.stage;
World.setBackground(PIXI.Texture.from("background.png"));
this._view = view;
this._model = model;
this._scorePointSound = getHowlerSound("sfx_point.wav");
this._hitSound = getHowlerSound("sfx_hit.wav");
this.initObstacles();
this.initPlayerBird();
this.initGameScoreText();
this.setupEvents();
this._collisionCheckTicker = new PIXI.Ticker();
this._collisionCheckTicker.add(this.onCollisionCheckTick.bind(this));
this._collisionCheckTicker.start();
this._obstaclesController.startMoving();
}
private initPlayerBird(): any {
this._birdController = new BirdController();
}
private initObstacles(): any {
this._obstaclesView = new ObstaclesView();
this._obstaclesController = new ObstaclesController(this._obstaclesView);
}
// TODO:
// move to view
private initGameScoreText(): any {
this._gameScoreText = new PIXI.Text(this._model.gameScore.toString(), {
fontSize: 20,
fill: 0xffffff,
fontWeight: "bold",
});
this._view.stage.addChild(this._gameScoreText);
this.updateGameScore();
}
private onKeyDown(key: KeyboardEvent) {
if (key.keyCode == 32) {
this.mainAction();
}
}
private mainAction(): void {
if (this._model.gameOver) {
this.restart();
} else {
this._birdController.fly();
}
}
private onCollisionCheckTick(): void {
if (this._model.gameOver) {
this._collisionCheckTicker.stop();
}
//pipe collision
if (this._birdController.bird.health !== 0) {
if (CollisionChecker.pipeCollision(this._birdController.bird, this._obstaclesController.NextPipeObstacle)) {
this.onBirdHit();
}
}
//groundHit
if (World.isObjectOnGround(this._birdController.bird)) {
this._model.gameOver = true;
this.onBirdHit();
}
}
private restart(): void {
this._model.resetModel();
this.updateGameScore();
this._birdController.resetBird();
this._obstaclesController.resetObstacles();
this._obstaclesController.startMoving();
this._collisionCheckTicker.start();
}
private onBirdHit(): void {
if (this._birdController.bird.health != 0) {
this._hitSound.play();
this._birdController.birdHealth = 0;
this._obstaclesController.stopMoving();
}
}
private onPipePassed(): any {
this._model.incrementScore(1);
this._scorePointSound.play();
this.updateGameScore();
}
private updateGameScore() {
this._gameScoreText.text = this._model.gameScore.toString();
// center text
const gameWidth = GameSettings.getInstance().gameWidth;
this._gameScoreText.position.set(gameWidth / 2 - this._gameScoreText.width / 2, 20);
}
private setupEvents(): any {
// collision
this._obstaclesController.on(ObstaclesController.PIPE_PASSED, () => {
this.onPipePassed();
});
// fly events
document.addEventListener("keydown", (e: KeyboardEvent) => {
this.onKeyDown(e);
});
this._view.stage.addListener(
PixiEventResolver.resolve("mousedown") as PIXI.interaction.InteractionEventTypes,
() => this.mainAction()
);
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/bird/bird-controller.ts
|
import { GameSettings } from "../game-settings";
import { Bird } from "./bird";
import { World } from "../world";
export class BirdController {
private _gameSettings: GameSettings;
private _bird: Bird;
constructor() {
this._gameSettings = GameSettings.getInstance();
this._bird = new Bird();
World.addObjectToWorld(this.bird);
this.resetBird();
}
get bird(): Bird {
return this._bird;
}
set birdHealth(value: number) {
if (value === 0) {
this.onBirdHit();
}
this.bird.health = value;
}
public fly(): void {
this.bird.fly();
}
public resetBird(): void {
this.bird.x = this._gameSettings.birdStartingXPosition;
this.bird.y = this._gameSettings.birdStartingYPosition;
this.bird.rotation = 0;
this.bird.velocityY = this._gameSettings.birdStartingVelocity;
this.birdHealth = 100;
this.bird.startMovingWings();
}
private onBirdHit(): void {
if (this.bird.velocityY < 0) {
this.bird.velocityY = 0;
}
this.bird.stopMovingWings();
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/bird/behaviors/bird-rotation-behavior.ts
|
<gh_stars>1-10
import * as PIXI from "pixi.js";
import { GameObject } from "../../abstract/game-object";
import { World } from "../../world";
export class BirdRotationBehavior {
public gameObject: GameObject | null;
public rotationTicker: PIXI.Ticker | null;
constructor(gameObject: GameObject) {
this.gameObject = gameObject;
this.rotationTicker = new PIXI.Ticker();
this.rotationTicker.add(() => {
this.rotate();
});
this.rotationTicker.start();
}
rotate(): void {
if (World.isObjectOnGround(this.gameObject)) {
return;
}
if (this.gameObject.health !== 0) {
if (this.gameObject.velocityY > 0 && this.gameObject.rotation < 0.5) {
this.gameObject.rotation += this.gameObject.velocityY / 40;
} else if (this.gameObject.velocityY < 0 && this.gameObject.rotation > -0.3) {
this.gameObject.rotation -= 0.05;
}
} else {
this.gameObject.rotation += 0.1;
}
}
dispose(): void {
this.gameObject = null;
this.rotationTicker.stop();
this.rotationTicker = null;
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/utils/collision-checker.ts
|
<reponame>yordan-kanchelov/flappy-bird-pixijs<gh_stars>1-10
import { PipeObstacle } from "../game/obstacles/pipes-obstacle";
import { Bird } from "../game/bird/bird";
export class CollisionChecker {
// TODO:
// check for circle collision maybe it would be better with it
public static pipeCollision(bird: Bird, pipeObstacle: PipeObstacle): boolean {
const birdBottomPoint: number = bird.y + bird.texture.height;
const xCollision: boolean =
bird.x < pipeObstacle.x + pipeObstacle.upperPipe.width && bird.x + bird.width / 2 > pipeObstacle.x;
const yCollision: boolean =
(bird.y - bird.height / 2 < pipeObstacle.upperPipe.y + pipeObstacle.upperPipe.height &&
bird.height / 2 + bird.y > pipeObstacle.upperPipe.y) ||
(bird.y - bird.height / 2 < pipeObstacle.bottomPipe.y + pipeObstacle.bottomPipe.height &&
bird.height / 2 + bird.y > pipeObstacle.bottomPipe.y) ||
birdBottomPoint < 0; // when bird height is out of screen
if (yCollision && xCollision) {
return true;
}
return false;
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/game-model.ts
|
<gh_stars>1-10
export class GameModel {
public gameOver: boolean;
private _gameScore: number;
/**
*
*/
constructor() {
this.gameOver = false;
this._gameScore = 0;
}
public get gameScore(): number {
return this._gameScore;
}
incrementScore(incValue: number) {
this._gameScore += incValue;
}
decrementScore(decValue: number) {
this._gameScore = this.gameScore <= decValue ? 0 : this.gameScore - decValue;
}
resetModel() {
this.gameOver = false;
this._gameScore = 0;
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/world.ts
|
import * as PIXI from "pixi.js";
import { Ground } from "./ground/ground";
import { GameObject } from "./abstract/game-object";
export class World {
private static instance: World = new World();
stage: PIXI.Container;
ground: Ground;
gameObjects: GameObject[];
private background: PIXI.Sprite;
constructor() {
if (World.instance) {
throw new Error("Error: Instantiation failed: Use World.getInstance() instead of new.");
}
World.instance = this;
this.gameObjects = [];
}
public static getInstance(): World {
return World.instance;
}
public static setBackground(backgroundTexture: PIXI.Texture): any {
if (!this.WorldInstance.background) {
this.WorldInstance.background = new PIXI.Sprite(backgroundTexture);
this.WorldInstance.stage.addChildAt(this.WorldInstance.background, 0);
} else {
this.WorldInstance.background.texture = backgroundTexture;
}
}
public static isObjectOnGround(gameObject: GameObject) {
if (gameObject.y >= World.getInstance().ground.y) {
return true;
}
return false;
}
public static addObjectToWorld(gameObject: GameObject) {
this.WorldInstance.gameObjects.push(gameObject);
this.WorldInstance.stage.addChild(gameObject);
}
private static get WorldInstance() {
return World.getInstance();
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/obstacles/obstacles-controller.ts
|
import * as PIXI from "pixi.js";
import { PipeObstacle } from "./pipes-obstacle";
import { ObstaclesView } from "./obstacles-view";
import { GameSettings } from "../game-settings";
import { Ground } from "../ground/ground";
import { World } from "../world";
export class ObstaclesController extends PIXI.utils.EventEmitter {
public static readonly PIPE_PASSED = "pipePassed"; // move to notification class
private readonly PIPES_COUNT: number = 3;
private _view: ObstaclesView;
private _gameSettings: GameSettings = GameSettings.getInstance();
private _nextPipeObstacleIndex: number;
private _moveObstaclesTicker: PIXI.Ticker;
constructor(view: ObstaclesView) {
super();
this._view = view;
this._view.on(ObstaclesView.PIPE_PASSED, this.onPipePassed, this);
this._nextPipeObstacleIndex = 0;
this._moveObstaclesTicker = new PIXI.Ticker();
this._moveObstaclesTicker.add(() => this.moveObstacles());
this.addObstacles();
}
get NextPipeObstacle(): PipeObstacle {
return this._view.pipeObstacles[this._nextPipeObstacleIndex];
}
public startMoving(): void {
this._moveObstaclesTicker.start();
}
public stopMoving(): void {
this._moveObstaclesTicker.stop();
}
public resetObstacles(): void {
this.resetPipesPosition();
}
//TODO
// add move behavior
private moveObstacles() {
this.movePipes();
this.moveGround();
}
private movePipes(): void {
this._view.movePipes();
}
private moveGround(): void {
this._view.moveGround(-this._gameSettings.groundMoveSpeed);
}
private onPipePassed(): any {
this._nextPipeObstacleIndex =
this._nextPipeObstacleIndex < this.PIPES_COUNT - 1 ? this._nextPipeObstacleIndex + 1 : 0;
this._view.nextPipeObstacleIndex = this._nextPipeObstacleIndex;
this.emit(ObstaclesController.PIPE_PASSED);
}
private addObstacles(): void {
this.addPipeObstacles();
this.addGroundObstacle();
}
// TODO
// move ground as parallax background in the root view
private addGroundObstacle() {
const ground = (World.getInstance().ground = new Ground());
ground.y = this._gameSettings.gameHeight - ground.height;
World.addObjectToWorld(ground);
this._view.groundObstacle = ground;
}
private addPipeObstacles() {
this._view.pipeObstacles = [];
for (let i = 0; i < this.PIPES_COUNT; i++) {
const pipeObstacle: PipeObstacle = new PipeObstacle();
pipeObstacle.x =
this._gameSettings.gameWidth + pipeObstacle.width * i + i * this._gameSettings.obstaclesDistance;
World.addObjectToWorld(pipeObstacle.upperPipe); // add them below ground
World.addObjectToWorld(pipeObstacle.bottomPipe); // add them below ground
this._view.pipeObstacles.push(pipeObstacle);
}
}
private resetPipesPosition(): void {
// TODO:
// nextPipeObsticle show be only in the controller or model
// remove it from the view
this._nextPipeObstacleIndex = 0;
this._view.nextPipeObstacleIndex = 0;
this._view.resetPipesPosition();
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/obstacles/pipes-obstacle.ts
|
import { GameSettings } from "../game-settings";
import { Pipe } from "./pipe";
import { Ground } from "../ground/ground";
export class PipeObstacle {
private _upperPipe: Pipe;
private _bottomPipe: Pipe;
constructor() {
this._upperPipe = new Pipe(true);
this._bottomPipe = new Pipe(false);
this._bottomPipe.y = GameSettings.getInstance().gameHeight - new Ground().height; // think for a better way
this.updateObstacle();
}
public set x(xValue: number) {
this._bottomPipe.x = xValue;
this._upperPipe.x = xValue;
}
public get x(): number {
return this._bottomPipe.x;
}
public get width(): number {
// both pipes are with the same width so return one of them
return this._upperPipe.width;
}
get upperPipe(): Pipe {
return this._upperPipe;
}
get bottomPipe(): Pipe {
return this._bottomPipe;
}
get pipes() {
return [this.upperPipe, this.bottomPipe];
}
public updateObstacle(): void {
const upperOffset: number = Math.floor(Math.random() * 100 + 1);
this._upperPipe.y = -upperOffset;
this._bottomPipe.y = this.upperPipe.y + this.upperPipe.height + GameSettings.getInstance().pipeObstaclesGap;
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/game-settings.ts
|
export class GameSettings {
//game resolution
public gameWidth: number = 144;
public gameHeight: number = 256;
//bird settings
public birdStartingXPosition: number = this.gameWidth / 3;
public birdStartingYPosition: number = this.gameHeight / 5;
public birdStartingVelocity: number = -2;
//obstacles settings
public pipeObstaclesGap: number = 45;
public obstaclesDistance: number = 45;
public obstaclesSpeed: number = 1;
// customization
public groundMoveSpeed: number = 2;
private static instance: GameSettings = new GameSettings();
constructor() {
if (GameSettings.instance) {
throw new Error("Error: Instantiation failed: Use GameSettings.getInstance() instead of new.");
}
GameSettings.instance = this;
}
public static getInstance(): GameSettings {
return GameSettings.instance;
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/utils/getHowlerSound.ts
|
import { Howl } from "howler";
export default function getHowlSound(soundName: string, props?: IHowlProperties): Howl {
let soundSource = `./sounds/${soundName}`;
let howlProps: IHowlProperties = { src: soundSource, ...props };
return new Howl(howlProps);
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/ground/ground.ts
|
<filename>src/game/ground/ground.ts
import * as PIXI from "pixi.js";
import { GameObject } from "../abstract/game-object";
export class Ground extends GameObject {
constructor() {
super(PIXI.Texture.from("ground.png"));
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/obstacles/pipe.ts
|
<gh_stars>1-10
import * as PIXI from "pixi.js";
import { GameObject } from "../abstract/game-object";
export class Pipe extends PIXI.Sprite implements GameObject {
gravityPower: number;
health: number;
velocityX: number;
velocityY: number;
constructor(upperPipe: boolean = true) {
super(PIXI.Texture.from(upperPipe ? "pipeUp.png" : "pipeDown.png"));
}
get body(): PIXI.Sprite {
return this;
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/index.ts
|
import * as PIXI from "pixi.js";
import * as screenfull from "screenfull";
import { GameController } from "./game/game-controller";
import { GameSettings } from "./game/game-settings";
import { GameView } from "./game/game-view";
import { GameModel } from "./game/game-model";
export class Main {
private gameSettings: GameSettings = GameSettings.getInstance();
private game: PIXI.Application;
constructor() {
window.onload = () => {
this.createRenderer();
this.startLoadingAssets();
};
}
private startLoadingAssets(): void {
const loader = PIXI.Loader.shared;
loader.add("gameSprite", "./spritesData.json");
loader.on("complete", () => {
this.onAssetsLoaded();
});
loader.load();
}
private onAssetsLoaded(): void {
const gameModel = new GameModel();
const gameView = new GameView(this.game.stage);
const gameController = new GameController(gameModel, gameView);
(window as any).flappyBird = { PIXI: PIXI, Main: this, GameController: gameController, GameView: gameView };
}
private createRenderer(): void {
const gameContainer = document.getElementById("gameContainer");
this.game = new PIXI.Application({
backgroundColor: 0xff0000,
height: window.innerHeight,
width: window.innerWidth,
});
gameContainer.appendChild(this.game.view);
this.game.stage.interactive = true;
this.game.stage.scale.x = window.innerWidth / this.gameSettings.gameWidth;
this.game.stage.scale.y = window.innerHeight / this.gameSettings.gameHeight;
this.game.stage.interactive = true;
this.game.stage.addListener("tap", () => {
if (screenfull && screenfull.enabled) {
screenfull.request(this.game.view);
}
});
window.addEventListener("resize", () => {
this.game.renderer.resize(window.innerWidth, window.innerHeight);
this.game.stage.scale.x = window.innerWidth / this.gameSettings.gameWidth;
this.game.stage.scale.y = window.innerHeight / this.gameSettings.gameHeight;
});
window.addEventListener("orientationchange", () => {
this.game.renderer.resize(window.innerWidth, window.innerHeight);
this.game.stage.scale.x = window.innerWidth / this.gameSettings.gameWidth;
this.game.stage.scale.y = window.innerHeight / this.gameSettings.gameHeight;
});
}
}
(function() {
const game: Main = new Main();
})();
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/abstract/behaviors/gravity-behavior.ts
|
import * as PIXI from "pixi.js";
import { GameObject } from "../game-object";
export interface GravityBehavior {
gameObject: GameObject;
gravityTicker: PIXI.Ticker;
gravity(): void;
dispose(): void;
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/game-view.ts
|
import * as PIXI from "pixi.js";
// import { PixiConsole } from "pixi-console";
import PixiFps from "pixi-fps";
export class GameView extends PIXI.Container {
private _stage: PIXI.Container;
constructor(stage: PIXI.Container) {
super();
this._stage = stage;
stage.addChild(this);
}
get stage(): PIXI.Container {
return this._stage;
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/bird/behaviors/bird-fly-flappy-behavior.ts
|
import getHowlSound from "../../../utils/getHowlerSound";
import { FlyBehavior } from "../../abstract/behaviors/fly-behavior";
import { GameObject } from "../../abstract/game-object";
export class BirdFlyFlappyBehavior implements FlyBehavior {
private static readonly FLY_VELOCITY_Y: number = 2.43;
public gameObject: GameObject;
private flySound: Howl;
private whoopingFlySound: Howl;
constructor(gameObject: GameObject) {
this.gameObject = gameObject;
this.flySound = getHowlSound("sfx_wing.wav");
this.whoopingFlySound = getHowlSound("sfx_swooshing.wav");
}
public fly(): void {
if (this.gameObject.health === 0) {
return;
}
if (this.gameObject.velocityY >= 4) {
this.whoopingFlySound.play();
} else {
this.flySound.play();
}
this.gameObject.velocityY = -BirdFlyFlappyBehavior.FLY_VELOCITY_Y;
}
dispose(): void {
this.gameObject = null;
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/commonBehaviors/gravityBehaviors/no-gravity-behavior.ts
|
import * as PIXI from "pixi.js";
import { GameObject } from "../../abstract/game-object";
import { GravityBehavior } from "../../abstract/behaviors/gravity-behavior";
export class NoGravityBehavior implements GravityBehavior {
public gameObject: GameObject;
public gravityPower: number = 0.1;
public gravityTicker: PIXI.Ticker;
constructor(gameObject: GameObject) {}
public gravity(): void {
// DO NOTHING
}
public dispose(): void {}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/bird/bird.ts
|
import * as PIXI from "pixi.js";
import { GravityBehavior as IGravityBehavior } from "../abstract/behaviors/gravity-behavior";
import { GravityBehavior } from "../commonBehaviors/gravityBehaviors/gravity-behavior";
import { FlyBehavior } from "../abstract/behaviors/fly-behavior";
import { BirdFlyFlappyBehavior } from "./behaviors/bird-fly-flappy-behavior";
import { BirdRotationBehavior } from "./behaviors/bird-rotation-behavior";
import { GameObject } from "../abstract/game-object";
export class Bird extends GameObject {
private _gravityBehavior: IGravityBehavior;
private _flyBehavior: FlyBehavior;
private _rotationBehavior: BirdRotationBehavior;
private _birdTextures: PIXI.Texture[];
private _birdPhase: number;
private _then: number;
private _interval: number;
private _delta: number;
private birdFlapping: boolean;
constructor() {
super(PIXI.Texture.EMPTY);
const fps = 60;
this._then = Date.now();
this._interval = 3000 / fps;
this._delta;
this._birdPhase = 0;
this._birdTextures = [
PIXI.Texture.from("birdDown.png"),
PIXI.Texture.from("birdMiddle.png"),
PIXI.Texture.from("birdUp.png"),
];
this.texture = this._birdTextures[0];
this.anchor.x = this.anchor.y = 0.5;
this.gravityPower = 0.1;
this._gravityBehavior = new GravityBehavior(this);
this._flyBehavior = new BirdFlyFlappyBehavior(this);
this._rotationBehavior = new BirdRotationBehavior(this);
}
fly() {
this._flyBehavior.fly();
}
startMovingWings() {
this.birdFlapping = true;
// TODO:
// use ticker
requestAnimationFrame(() => {
if (this.birdFlapping) {
this.startMovingWings();
}
});
const now = Date.now();
this._delta = now - this._then;
if (this._delta > this._interval) {
this._then = now - (this._delta % this._interval);
if (this._birdPhase > 2) {
this._birdPhase = 0;
}
this.texture = this._birdTextures[this._birdPhase];
this._birdPhase += 1;
}
}
stopMovingWings() {
this.birdFlapping = false;
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/obstacles/obstacles-view.ts
|
<reponame>yordan-kanchelov/flappy-bird-pixijs
import * as PIXI from "pixi.js";
import { Ground } from "../ground/ground";
import { PipeObstacle } from "../obstacles/pipes-obstacle";
import { GameSettings } from "../game-settings";
export class ObstaclesView extends PIXI.utils.EventEmitter {
public static readonly PIPE_PASSED = "pipePassed";
groundObstacle: Ground;
pipeObstacles: PipeObstacle[];
nextPipeObstacleIndex: number = 0;
constructor() {
super();
}
movePipes() {
if (
this.pipeObstacles[this.nextPipeObstacleIndex].x + this.pipeObstacles[this.nextPipeObstacleIndex].width <
this._gameSettings.birdStartingXPosition - PIXI.Texture.from("birdMiddle.png").width / 2
) {
this.emit(ObstaclesView.PIPE_PASSED);
}
for (let i = 0; i < this.pipeObstacles.length; i += 1) {
if (this.pipeObstacles[i].x < -this.pipeObstacles[i].upperPipe.width) {
this.pipeObstacles[i].updateObstacle();
this.pipeObstacles[i].x = this._gameSettings.gameWidth + this._gameSettings.obstaclesDistance;
}
this.pipeObstacles[i].x -= this._gameSettings.obstaclesSpeed;
}
}
moveGround(moveStep: number) {
this.groundObstacle.x += moveStep;
if (-this.groundObstacle.x === this.groundObstacle.texture.width - this._gameSettings.gameWidth) {
this.groundObstacle.x = 0;
}
}
resetPipesPosition() {
for (let i = 0; i < this.pipeObstacles.length; i++) {
this.pipeObstacles[i].updateObstacle();
this.pipeObstacles[i].x =
this._gameSettings.gameWidth +
this.pipeObstacles[i].width * i +
i * this._gameSettings.obstaclesDistance;
}
}
private get _gameSettings(): GameSettings {
return GameSettings.getInstance();
}
}
|
yordan-kanchelov/flappy-bird-pixijs
|
src/game/abstract/behaviors/fly-behavior.ts
|
<filename>src/game/abstract/behaviors/fly-behavior.ts
import { GameObject } from "../game-object";
export interface FlyBehavior {
gameObject: GameObject;
fly(): void;
dispose(): void;
}
|
rousslabs/xfinity-data-usage
|
src/server.ts
|
import Http from 'http';
import URL from 'url';
import { homeassistantAttributesData } from './mqtt';
import { Xfinity, xfinityUsage } from './xfinity';
export const createServer = (xfinity: Xfinity): void => {
Http.createServer((req, res) => {
const url = URL.parse(req.url || '');
const path = url.pathname;
const homeassistant = path === '/homeassistant';
console.log(`HTTP request: ${path}`);
if (path !== '/' && !homeassistant) {
res.writeHead(404);
res.end();
return;
}
let data: xfinityUsage | homeassistantAttributesData | undefined = xfinity.getData();
if (!data) {
res.writeHead(503);
res.end();
return;
}
if (homeassistant) {
const [current] = data.usageMonths.slice(-1);
data = {
total_usage: current.totalUsage,
allowable_usage: current.allowableUsage,
home_usage: current.homeUsage,
wifi_usage: current.wifiUsage,
courtesy_used: data.courtesyUsed,
courtesy_remaining: data.courtesyRemaining,
courtesy_allowed: data.courtesyAllowed,
in_paid_overage: data.inPaidOverage,
remaining_usage: current.allowableUsage - current.totalUsage,
};
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(data));
res.end();
}).listen(7878);
console.log('http server started');
};
|
rousslabs/xfinity-data-usage
|
src/app.ts
|
import Request from 'request';
import { Config } from './config';
import { mqtt as MQTT } from './mqtt';
import { createServer } from './server';
import { Xfinity, DATA_UPDATED } from './xfinity';
let config: Config;
try {
config = new Config();
} catch (e) {
console.log(e.message);
process.exit(1);
}
const { xfinity: xfinityConfig, mqtt: mqttConfig } = config.getConfig();
const xfinity = new Xfinity(xfinityConfig);
xfinity.start();
if (config.useHttp) {
createServer(xfinity);
}
if (config.useMqtt && mqttConfig) {
const mqtt = new MQTT(mqttConfig);
xfinity.addListener(DATA_UPDATED, mqtt.update.bind(mqtt));
}
if (config.usePost) {
xfinity.addListener(DATA_UPDATED, (data) => {
console.log(`Posting to ${config.postUrl}`);
Request.post(config.postUrl, { json: data }, (error) => {
if (error) {
console.log(`Couldn't post to ${config.postUrl}. Error: ${error.code}`);
}
});
});
}
|
rousslabs/xfinity-data-usage
|
src/xfinity.ts
|
import { EventEmitter } from 'events';
import puppeteer from 'puppeteer-core';
import randomUseragent from 'random-useragent';
export const DATA_UPDATED = 'dataUpdated';
const JSON_URL = 'https://customer.xfinity.com/apis/services/internet/usage';
const LOGIN_URL = 'https://customer.xfinity.com';
const SECURITY_CHECK_TITLE = 'Security Check';
export interface xfinityConfig {
username: string;
password: string;
interval: number;
pageTimeout: number;
}
export interface xfinityUsage {
courtesyUsed: number;
courtesyRemaining: number;
courtesyAllowed: number;
inPaidOverage: boolean;
displayUsage: boolean;
usageMonths: Array<xfinityUsageMonth>;
error?: string;
logged_in_within_limit?: boolean;
}
interface xfinityUsageMonth {
policyName: string;
startDate: string;
endDate: string;
homeUsage: number;
wifiUsage: number;
totalUsage: number;
allowableUsage: number;
unitOfMeasure: string;
displayUsage: boolean;
devices: Array<{ id: string; usage: number }>;
additionalBlocksUsed: number;
additionalCostPerBlock: number;
additionalUnitsPerBlock: number;
additionalIncluded: number;
additionalUsed: number;
additionalPercentUsed: number;
additionalRemaining: number;
billableOverage: number;
overageCharges: number;
overageUsed: number;
currentCreditAmount: number;
maxCreditAmount: number;
policy: string;
}
export class Xfinity extends EventEmitter {
#browser?: puppeteer.Browser;
#page?: puppeteer.Page;
#data: xfinityUsage | undefined;
#password: string;
#username: string;
#interval: number;
#intervalMs: number;
#pageTimeout: number;
constructor({ username, password, interval, pageTimeout }: xfinityConfig) {
super();
this.#username = username;
this.#password = password;
this.#interval = interval;
this.#intervalMs = interval * 60000;
this.#pageTimeout = pageTimeout * 1000;
}
start(): void {
this.fetch();
setInterval(this.fetch.bind(this), this.#intervalMs);
}
getData(): xfinityUsage | undefined {
return this.#data;
}
private async fetch() {
const nextAt = new Date(Date.now() + this.#intervalMs).toLocaleTimeString();
console.log('Fetching Data');
try {
this.#data = await this.retrieveDataUsage();
console.log('Data updated');
this.emit(DATA_UPDATED, this.#data);
} catch (e) {
console.error(`Browser Error: ${e}`);
} finally {
await this.#browser?.close();
this.#page = undefined;
}
console.log(`Next fetch in ${this.#interval} minutes @ ${nextAt}`);
}
private async retrieveDataUsage(): Promise<xfinityUsage> {
let data: xfinityUsage;
let retries = 3;
do {
if (retries === 0) {
throw new Error('Unable to login');
}
if (retries !== 3) {
console.info('Not logged in');
}
await this.authenticate();
retries--;
data = await this.getJson();
} while (data.error === 'unauthenticated' || data.logged_in_within_limit === false);
return data;
}
private async getJson(): Promise<xfinityUsage> {
console.info(`Loading Usage ${JSON_URL}`);
const page = await this.getPage();
await page.goto(JSON_URL, { waitUntil: 'networkidle0' });
const text = await page.$eval('pre', (e) => e.innerHTML);
let jsonData;
try {
jsonData = JSON.parse(text.toString());
} catch (e) {
console.log('Bad JSON', text);
}
return jsonData;
}
private async authenticate() {
console.info(`Loading (${LOGIN_URL})`);
const page = await this.getPage();
await page.goto(LOGIN_URL, { waitUntil: 'networkidle2' });
await page.waitForSelector('#user');
await page.type('#user', this.#username);
await page.type('#passwd', this.#password);
await page.click('#sign_in');
await page.waitForNavigation({ waitUntil: 'networkidle2' });
const pageTitle = await page.title();
console.log('Page Title: ', pageTitle);
if (pageTitle === SECURITY_CHECK_TITLE) {
await this.bypassSecurityCheck();
}
}
private async bypassSecurityCheck() {
console.log('Clicking "Ask me later" for security check');
const page = await this.getPage();
await page.click('.cancel');
await page.waitForNavigation({ waitUntil: 'networkidle2' });
}
private async getBrowser() {
if (this.#browser?.isConnected()) return this.#browser;
this.#browser = await puppeteer.launch({
executablePath: '/usr/bin/chromium',
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'],
});
return this.#browser;
}
private async getPage() {
if (this.#page?.isClosed() !== false) {
const browser = await this.getBrowser();
const page = await browser.newPage();
await page.setUserAgent(this.getUseragent());
page.setDefaultNavigationTimeout(this.#pageTimeout);
await page.setViewport({ width: 1920, height: 1080 });
this.#page = page;
}
return this.#page;
}
private getUseragent(): string {
const USERAGENT =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36';
const useragent = randomUseragent.getRandom(function (ua) {
return ua.browserName === 'Chrome' && parseFloat(ua.browserVersion) >= 50;
});
return useragent ?? USERAGENT;
}
}
|
0J3/tiny-invariant
|
src/tiny-invariant.ts
|
<reponame>0J3/tiny-invariant
// @flow
const prefix: string = 'Invariant failed';
// Throw an error if the condition fails
export default function invariant(
condition: any,
message?: string,
): asserts condition {
if (condition) {
return;
}
// Condition not passed
// We error
throw new Error(`${prefix}: ${message || ''}`);
}
|
KiharaTakahiro/share-media
|
web/src/components/parts/styles/title.tsx
|
<reponame>KiharaTakahiro/share-media
import React from "react";
import Typography from "@material-ui/core/Typography";
type Props = {
title: string
}
const PartsTitle: React.FC<Props> = ({title}) => (
<Typography variant="h5" component="h2">
{title}
</Typography>
);
export default PartsTitle;
|
KiharaTakahiro/share-media
|
web/src/pages/register_user.tsx
|
<filename>web/src/pages/register_user.tsx<gh_stars>0
import React from 'react'
import RegisterUserTemplate from '../components/templates/register_user_template';
import ApiCaller from '../common/api_caller'
import Router from 'next/router'
const RegisterUser = () => {
// ユーザ取得処理
const register_user = (data: Object) => {
console.log(data)
ApiCaller.post("users/create", data)
.then(response => {
Router.push('/complete_register_user')
})
.catch(error => {
// TODO: エラーメッセージを表示するようにしたい
console.log(error.response.data)
})
}
return (
<RegisterUserTemplate register_user={register_user}/>
)
}
export default RegisterUser;
|
KiharaTakahiro/share-media
|
web/src/components/templates/top_template.tsx
|
import React from "react";
import PrimarySubmitButton from "../parts/buttons/primary_submit_button"
import RequireText from "../parts/text_fields/normal_text"
type Props = {}
const TopTemplate: React.FC<Props> = () => (
<div>
<div>TOPページをのいろいろ</div>
<PrimarySubmitButton button_name="プライマリ"/>
<RequireText label="ユーザ名" />
</div>
);
export default TopTemplate;
|
KiharaTakahiro/share-media
|
web/src/components/templates/login_user_template.tsx
|
<reponame>KiharaTakahiro/share-media
import React from "react";
import PrimarySubmitButton from "../parts/buttons/primary_submit_button"
import UserNameText from "../parts/text_fields/user_name_text"
import PasswordText from "../parts/text_fields/password_text"
import PartsTitle from "../parts/styles/title"
import Grid from '@material-ui/core/Grid'
import Paper from '@material-ui/core/Paper'
import { useForm } from 'react-hook-form'
import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'
type Props = {
login: any // ログイン処理
}
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
'& .MuiTextField-root': {
margin: theme.spacing(2),
width: '40ch',
},
'& .MuiButton-root': {
margin: theme.spacing(2),
width: '52ch',
height: '7ch'
},
},
}),
)
const LoginUserTemplate: React.FC<Props> = ({ login }) => {
const classes = useStyles()
const { handleSubmit, register, errors } = useForm()
return (
<>
<Grid container direction="column" justify="center" alignItems="center">
<PartsTitle title="ログイン"/>
<Paper elevation={3}>
<form className={classes.root} onSubmit={handleSubmit(login)}>
<Grid container direction="column" justify="center" alignItems="center">
<UserNameText required register={register} errors={errors}/>
<PasswordText required register={register} errors={errors}/>
<PrimarySubmitButton button_name="ログイン"/>
</Grid>
</form>
</Paper>
</Grid>
</>
)
}
export default LoginUserTemplate;
|
KiharaTakahiro/share-media
|
web/src/components/parts/buttons/primary_submit_button.tsx
|
<gh_stars>0
import Button from '@material-ui/core/Button';
import React from "react";
type Props = {
button_name: string
}
const PrimarySubmitButton: React.FC<Props> = ({button_name}) => {
return (
<Button variant="contained" color="primary" type="submit" >
{button_name}
</Button>
)
}
export default PrimarySubmitButton;
|
KiharaTakahiro/share-media
|
web/src/components/parts/buttons/primary_click_button.tsx
|
<reponame>KiharaTakahiro/share-media
import Button from '@material-ui/core/Button';
import React from "react";
type Props = {
button_name: string
onClick: any
}
const PrimaryClickButton: React.FC<Props> = ({button_name, onClick}) => {
return (
<Button variant="contained" color="primary" onClick={onClick} >
{button_name}
</Button>
)
}
export default PrimaryClickButton;
|
KiharaTakahiro/share-media
|
web/src/common/auth.ts
|
<reponame>KiharaTakahiro/share-media
import { PAGE_END_POINT } from '../common/const'
import { parseCookies, destroyCookie, setCookie} from 'nookies';
import { NextPageContext } from 'next';
import Router from 'next/router'
/**
* トークンのインターフェース
*/
interface Token {
access_token: string,
refresh_token: string
}
/**
* トークンの情報を取得する
* @param ctx
*/
export const get_access_token = (ctx?: NextPageContext): Token | any => {
if(typeof parseCookies(ctx).access_token === 'undefined') {
return undefined
}
return parseCookies(ctx).access_token;
}
export const set_token = (data: Token, ctx?: NextPageContext) =>{
setCookie(ctx, "access_token", data.access_token , {
maxAge: 24 * 60 * 60, // 1日で切れる
path: '/'
})
setCookie(ctx, "refresh_token", data.refresh_token , {
maxAge: 90 * 24 * 60 * 60, // 90日で切れる
path: '/'
})
}
/**
* 認証不要ページの判定処理
* @param url
*/
export const exclude_login_route = (url: string) => {
return url === PAGE_END_POINT.REGISTER_USER || url === PAGE_END_POINT.LOGIN_USER
}
/**
* ログアウト処理
*/
export const logout = (ctx?: NextPageContext) => {
destroyCookie(ctx, "access_token")
destroyCookie(ctx, "refresh_token")
Router.push(PAGE_END_POINT.LOGIN_USER)
}
|
KiharaTakahiro/share-media
|
web/src/common/const.ts
|
/**
* 正規表現用の定数クラス
*/
export namespace RegConst {
/**
* 半角英数の正規表現
*/
export const HANKAKU_EISU = /^[0-9a-zA-Z]*$/
/**
* 全角ひらがなの正規表現
*/
export const ZENKAKU_HIRAKANA = /^[ぁ-んー]*$/
/**
* 全角カナの正規表現
*/
export const ZENKAKU_KANA = /^[ァ-ンヴー]*$/
/**
* 半角英数記号のみ
*/
export const HANKAKU_EISU_KIGOU = /^[a-zA-Z0-9!-/:-@¥[-`{-~]*$/
/**
* emailアドレスの正規表現
*/
export const EMAIL = /^[a-zA-Z0-9_+-]+(.[a-zA-Z0-9_+-]+)*@([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]*\.)+[a-zA-Z]{2,}$/
}
export namespace PAGE_END_POINT {
/**
* ログインページのエンドポイント
*/
export const LOGIN_USER = "/login_user"
/**
* ユーザ登録ページのエンドポイント
*/
export const REGISTER_USER = "/register_user"
}
|
KiharaTakahiro/share-media
|
web/src/pages/complete_register_user.tsx
|
import React from 'react'
const CompleteRegisterUser = () => (
<div>ユーザ登録完了しました</div>
);
export default CompleteRegisterUser;
|
KiharaTakahiro/share-media
|
web/src/components/templates/menu_template.tsx
|
<filename>web/src/components/templates/menu_template.tsx<gh_stars>0
import React from "react";
import PrimaryClickButton from '../parts/buttons/primary_click_button'
type Props = {
logout: any
}
const MenuTemplate: React.FC<Props> = ({logout}) => {
return (
<>
<div>ログイン後のメニュー</div>
<PrimaryClickButton button_name="ログアウト" onClick={logout} />
</>
)
}
export default MenuTemplate;
|
KiharaTakahiro/share-media
|
web/src/pages/menu.tsx
|
<filename>web/src/pages/menu.tsx
import React, {useEffect} from 'react'
import MenuTemplate from '../components/templates/menu_template';
import { logout } from '../common/auth'
import { NextPageContext } from 'next'
import ApiCaller from '../common/api_caller'
const Menu = (ctx: NextPageContext) => {
const page_logout = () => {
logout(ctx)
}
const get_user = () => {
ApiCaller.get("/users/me")
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
}
useEffect(() => {
get_user()
})
return (
<MenuTemplate logout={page_logout}/>
)
}
export default Menu;
|
KiharaTakahiro/share-media
|
web/src/components/parts/text_fields/email_text.tsx
|
<gh_stars>0
/**
* ユーザのEmail入力用のテキストフィールド
*/
import TextField from '@material-ui/core/TextField'
import React from "react"
import { RegConst } from "../../../common/const"
type Props = {
/**
* register
*/
register: any
/**
* errors属性
*/
errors: any
/**
* 必須(true)/必須ではない(false)
*/
required?: boolean
/**
* 初期値
*/
default_value?: string
/**
* id属性
*/
id?: string
}
interface ValidationRule {
required?: string
maxLength: {
value: number,
message: string
}
pattern: {
value: RegExp,
message: string
}
}
const EMailText: React.FC<Props> = ({required, default_value, id, register, errors}) => {
/**
* 最大文字数
*/
const MAX_LENGTH = 30
/**
* バリデーションルール
* @param required
*/
const validation_rule = (required: boolean) => {
var component_rule: ValidationRule = {
maxLength: {
value: MAX_LENGTH,
message: `emailは${MAX_LENGTH}文字以内で入力してください`
},
pattern: {
value: RegConst.EMAIL,
message: "emailアドレスの形式で入力してください"
}
}
if (required) {
component_rule['required'] = "emailは必須です"
}
return component_rule
}
/**
* 表示領域
*/
return (
<TextField
required={required}
defaultValue={default_value}
id={id}
inputRef={register(validation_rule(required))}
name="email"
label="email"
variant="outlined"
error={Boolean(errors.email)}
helperText={errors.email && errors.email.message}/>
)
};
export default EMailText;
|
KiharaTakahiro/share-media
|
web/src/components/parts/text_fields/password_text.tsx
|
<reponame>KiharaTakahiro/share-media
/**
* ユーザのパスワード入力用のテキストフィールド
*/
import TextField from '@material-ui/core/TextField'
import React from "react"
import { RegConst } from "../../../common/const"
type Props = {
/**
* 必須(true)/必須ではない(false)
*/
required?: boolean
/**
* 初期値
*/
default_value?: string
/**
* id属性
*/
id?: string
/**
* register
*/
register?: any
/**
* errors属性
*/
errors?: any
}
interface ValidationRule {
required?: string
maxLength: {
value: number,
message: string
}
minLength:{
value: number,
message: string
}
pattern: {
value: RegExp,
message: string
}
}
const PasswordText: React.FC<Props> = ({required, default_value, id, register, errors}) => {
/**
* 最大文字数
*/
const MAX_LENGTH = 20
/**
* 最小文字数
*/
const MIN_LENGHT = 8
/**
* バリデーションルール
* @param required
*/
const validation_rule = (required: boolean) => {
var component_rule: ValidationRule = {
maxLength: {
value: MAX_LENGTH,
message: `パスワードは${MAX_LENGTH}文字以内で入力してください`
},
minLength: {
value: MIN_LENGHT,
message: `パスワードは${MIN_LENGHT}文字以上で入力してください`
},
pattern: {
value: RegConst.HANKAKU_EISU_KIGOU,
message: "パスワードは半角英数字か記号で入力してください"
}
}
if (required) {
component_rule['required'] = "パスワードは必須です"
}
return component_rule
}
/**
* 表示領域
*/
return (
<TextField
required={required}
defaultValue={default_value}
id={id}
inputRef={register(validation_rule(required))}
type="password"
name="password"
label="パスワード"
variant="outlined"
error={Boolean(errors.password)}
helperText={ errors.password && errors.password.message}/>
)
};
export default PasswordText;
|
KiharaTakahiro/share-media
|
web/src/components/parts/text_fields/age_text.tsx
|
<filename>web/src/components/parts/text_fields/age_text.tsx
/**
* ユーザの年齢入力用のテキストフィールド
*/
import TextField from '@material-ui/core/TextField'
import React from "react"
type Props = {
/**
* register
*/
register: any
/**
* errors属性
*/
errors: any
/**
* 必須(true)/必須ではない(false)
*/
required?: boolean
/**
* 初期値
*/
default_value?: string
/**
* id属性
*/
id?: string
}
interface ValidationRule {
required?: string
max: {
value: number,
message: string
}
min: {
value: number,
message: string
}
}
const AgeText: React.FC<Props> = ({required, default_value, id, register, errors}) => {
/**
* 最大の年齢
*/
const MAX_AGE = 200
/**
* 最小の年齢
*/
const MIN_AGE = 15
/**
* バリデーションルール
* @param required
*/
const validation_rule = (required: boolean) => {
var component_rule: ValidationRule = {
max: {
value: MAX_AGE,
message: `年齢は${MAX_AGE}才以内で入力してください`
},
min: {
value: MIN_AGE,
message: `年齢は${MIN_AGE}才以上で入力してください`
}
}
if (required) {
component_rule['required'] = "年齢は必須です"
}
return component_rule
}
/**
* 表示領域
*/
return (
<TextField
required={required}
defaultValue={default_value}
id={id}
inputRef={register(validation_rule(required))}
name="age"
label="年齢"
variant="outlined"
type="number"
error={Boolean(errors.age)}
helperText={errors.age && errors.age.message}/>
)
};
export default AgeText;
|
KiharaTakahiro/share-media
|
web/src/common/api_caller.ts
|
<reponame>KiharaTakahiro/share-media
import axios from "axios"
import { get_access_token, logout } from '../common/auth'
/**
* バックエンドとの通信を行うための設定
*/
const instance = axios.create({
baseURL: "http://localhost:8000/",
timeout: 2000,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
/**
* リクエストのインターセプタ
* config: requestが送信される前に実行される処理
* error: then/catchの処理の「前に」実行されるエラーハンドリング
*/
instance.interceptors.request.use(
config => {
// tokenが存在する場合は再度
const access_token = get_access_token()
if (typeof access_token !== 'undefined') {
config.headers = { Authorization: `Bearer ${access_token}` }
}
return config
},
error => {
return Promise.reject(error)
}
)
/**
* レスポンスのインターセプタ
* response: レスポンスを取得後の処理
* error: エラー時の処理
*/
instance.interceptors.response.use(
response => {
return response;
},
error => {
if(error.state == 401){
logout()
}
return Promise.reject(error)
}
)
export default instance
|
KiharaTakahiro/share-media
|
web/src/components/parts/text_fields/user_name_text.tsx
|
<filename>web/src/components/parts/text_fields/user_name_text.tsx
/**
* ユーザのユーザ名入力用のテキストフィールド
*/
import TextField from '@material-ui/core/TextField'
import React from "react"
import { RegConst } from "../../../common/const"
type Props = {
/**
* 必須(true)/必須ではない(false)
*/
required?: boolean
/**
* 初期値
*/
default_value?: string
/**
* id属性
*/
id?: string
/**
* register
*/
register?: any
/**
* errors属性
*/
errors?: any
}
interface ValidationRule {
required?: string
maxLength: {
value: number,
message: string
}
pattern:{
value: RegExp
message: string
}
}
const UserNameText: React.FC<Props> = ({required, default_value, id, register, errors}) => {
const validation_rule = (required: boolean) => {
var component_rule: ValidationRule = {
maxLength: {
value: 10,
message: "ユーザ名は10文字以内で入力してください"
},
pattern: {
value: RegConst.HANKAKU_EISU,
message: "ユーザ名は半角英数字で入力してください"
}
}
if (required) {
component_rule['required'] = "ユーザ名は必須です"
}
return component_rule
}
return (
<TextField
required={required}
defaultValue={default_value}
id={id}
inputRef={register(validation_rule(required))}
name="username"
label="ユーザ名"
variant="outlined"
error={Boolean(errors.username)}
helperText={errors.username && errors.username.message}/>
)
};
export default UserNameText;
|
KiharaTakahiro/share-media
|
web/src/components/parts/text_fields/normal_text.tsx
|
<filename>web/src/components/parts/text_fields/normal_text.tsx
import TextField from '@material-ui/core/TextField';
import React from "react";
type Props = {
label?: string
default_value?: string
id?: string
required?: boolean
}
const NormalText: React.FC<Props> = ({label, default_value, id, required}) => {
return (
<TextField required={required} id={id} label={label} defaultValue={default_value} variant="outlined"/>
)
};
export default NormalText;
|
KiharaTakahiro/share-media
|
web/src/pages/index.tsx
|
<reponame>KiharaTakahiro/share-media
import React from 'react'
import TopTemplate from '../components/templates/top_template'
const Index = () => {
return (
<TopTemplate/>
)
}
export default Index;
|
KiharaTakahiro/share-media
|
web/src/pages/_app.tsx
|
<gh_stars>0
import { NextPageContext } from 'next'
import { AppProps } from 'next/app'
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import { exclude_login_route } from '../common/auth'
import { PAGE_END_POINT } from '../common/const'
import { get_access_token } from '../common/auth'
const MyApp = ({ Component, pageProps }: AppProps, ctx: NextPageContext) => {
const router = useRouter()
useEffect(() => {
router.beforePopState(({ url }) => {
if (!exclude_login_route(url) && typeof get_access_token(ctx) === 'undefined') {
window.location.href = PAGE_END_POINT.LOGIN_USER
return false
}
return true
})
}, [])
return typeof pageProps === 'undefined' ? null : <Component {...pageProps} />
}
MyApp.getInitialProps = async (appContext: any) => {
if (!exclude_login_route(appContext.ctx.pathname) && typeof get_access_token(appContext.ctx) === 'undefined') {
if (typeof window === 'undefined') {
appContext.ctx.res.statusCode = 302
appContext.ctx.res.setHeader('Location', PAGE_END_POINT.LOGIN_USER)
return {}
}
}
return {
pageProps: {
...(appContext.Component.getInitialProps
? await appContext.Component.getInitialProps(appContext.ctx)
: {}),
pathname: appContext.ctx.pathname,
},
}
}
export default MyApp
|
KiharaTakahiro/share-media
|
web/src/pages/login_user.tsx
|
<gh_stars>0
import React from 'react'
import LoginUserTemplate from '../components/templates/login_user_template';
import ApiCaller from '../common/api_caller'
import Router from 'next/router'
import { set_token } from '../common/auth'
import { NextPageContext } from 'next'
const LoginUser = (ctx: NextPageContext) => {
// TODO: ページに移す予定
const login = (data: Object) => {
console.log(data)
ApiCaller.post("/users/login", data)
.then(response => {
set_token(response.data, ctx)
Router.push('/menu')
})
.catch(error => {
console.log(error)
})
}
return (
<LoginUserTemplate login={login}/>
)
}
export default LoginUser;
|
DenisVASI9/grpc-reprod
|
src/mservice/mservice.service.ts
|
<reponame>DenisVASI9/grpc-reprod
import { Injectable } from '@nestjs/common';
import { Message, Name } from './mservice';
@Injectable()
export class MserviceService {
async sayHello(params: Name): Promise<Message> {
return {
message: `Привет, ${params.name}`,
};
}
}
|
DenisVASI9/grpc-reprod
|
src/mservice/mservice.controller.ts
|
import { Controller } from '@nestjs/common';
import {
Message,
MServiceController,
MServiceControllerMethods,
Name,
} from './mservice';
import { MserviceService } from './mservice.service';
import { RpcException } from '@nestjs/microservices';
import * as grpc from 'grpc';
@Controller()
@MServiceControllerMethods()
export class MserviceController implements MServiceController {
constructor(private readonly mServiceService: MserviceService) {}
sayHelloFromRpc(request: Name): Promise<Message> {
throw new RpcException({
code: grpc.status.NOT_FOUND,
message: 'test throw',
});
return this.mServiceService.sayHello(request);
}
}
|
DenisVASI9/grpc-reprod
|
src/main.ts
|
<reponame>DenisVASI9/grpc-reprod
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {
GrpcOptions,
MicroserviceOptions,
Transport,
} from '@nestjs/microservices';
import { resolve } from 'path';
export const MserviceClientOptions: GrpcOptions = {
transport: Transport.GRPC,
options: {
url: 'localhost:50052',
package: 'mservice',
protoPath: resolve(__dirname, '../../src/mservice/mservice.proto'),
},
};
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.connectMicroservice<MicroserviceOptions>(MserviceClientOptions);
await app.startAllMicroservicesAsync();
await app.listen(5000);
}
bootstrap();
|
DenisVASI9/grpc-reprod
|
src/mservice/mservice.module.ts
|
import { Module } from '@nestjs/common';
import { MserviceController } from './mservice.controller';
import { MserviceService } from './mservice.service';
@Module({
imports: [],
controllers: [MserviceController],
providers: [MserviceService],
})
export class MserviceModule {}
|
DenisVASI9/grpc-reprod
|
src/gateway/gateway.service.ts
|
import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { ClientGrpc } from '@nestjs/microservices';
import {
M_SERVICE_NAME,
MSERVICE_PACKAGE_NAME,
MServiceClient,
} from '../mservice/mservice';
@Injectable()
export class GatewayService implements OnModuleInit {
constructor(
@Inject(MSERVICE_PACKAGE_NAME) private readonly client: ClientGrpc,
) {}
mserviceClient: MServiceClient;
onModuleInit() {
this.mserviceClient =
this.client.getService<MServiceClient>(M_SERVICE_NAME);
}
sayHello() {
return this.mserviceClient.sayHelloFromRpc({
name: 'Denis',
});
}
}
|
DenisVASI9/grpc-reprod
|
protogen.ts
|
<reponame>DenisVASI9/grpc-reprod
import { exec } from 'child_process';
import * as path from 'path';
const plugin = path.resolve(__dirname, `node_modules/.bin/protoc-gen-ts_proto`);
const commands = [
`cd src/mservice/ && protoc --plugin=${plugin} --ts_proto_opt=nestJs=true --ts_proto_opt=snakeToCamel=false --ts_proto_out=. ./mservice.proto`,
];
commands.forEach((command) => {
exec(command, (error, stdout, stderr) => {
if (stdout) {
console.log(stdout);
}
if (error) {
console.error(error.message);
return;
}
if (stderr) {
console.error(stderr);
return;
}
});
});
|
DenisVASI9/grpc-reprod
|
src/mservice/mservice.ts
|
/* eslint-disable */
import { GrpcMethod, GrpcStreamMethod } from '@nestjs/microservices';
import { util, configure } from 'protobufjs/minimal';
import * as Long from 'long';
import { Observable } from 'rxjs';
export const protobufPackage = 'mservice';
export interface Name {
name: string;
}
export interface Message {
message: string;
}
export const MSERVICE_PACKAGE_NAME = 'mservice';
export interface MServiceClient {
sayHelloFromRpc(request: Name): Observable<Message>;
}
export interface MServiceController {
sayHelloFromRpc(
request: Name,
): Promise<Message> | Observable<Message> | Message;
}
export function MServiceControllerMethods() {
return function (constructor: Function) {
const grpcMethods: string[] = ['sayHelloFromRpc'];
for (const method of grpcMethods) {
const descriptor: any = Reflect.getOwnPropertyDescriptor(
constructor.prototype,
method,
);
GrpcMethod('MService', method)(
constructor.prototype[method],
method,
descriptor,
);
}
const grpcStreamMethods: string[] = [];
for (const method of grpcStreamMethods) {
const descriptor: any = Reflect.getOwnPropertyDescriptor(
constructor.prototype,
method,
);
GrpcStreamMethod('MService', method)(
constructor.prototype[method],
method,
descriptor,
);
}
};
}
export const M_SERVICE_NAME = 'MService';
// If you get a compile-error about 'Constructor<Long> and ... have no overlap',
// add '--ts_proto_opt=esModuleInterop=true' as a flag when calling 'protoc'.
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}
|
DenisVASI9/grpc-reprod
|
src/gateway/gateway.controller.ts
|
<reponame>DenisVASI9/grpc-reprod
import { Controller, Get } from '@nestjs/common';
import { GatewayService } from './gateway.service';
@Controller('api/gateway')
export class GatewayController {
constructor(private readonly gatewayService: GatewayService) {}
@Get('hello')
async hello() {
return this.gatewayService.sayHello();
}
}
|
DenisVASI9/grpc-reprod
|
src/gateway/gateway.module.ts
|
import { Module } from '@nestjs/common';
import { GatewayController } from './gateway.controller';
import { GatewayService } from './gateway.service';
import { ClientGrpcProxy, ClientsModule } from '@nestjs/microservices';
import { resolve } from 'path';
class ErrorHandlingProxy extends ClientGrpcProxy {
protected serializeResponse(response: any): any {
console.log('RESPONSEEEEE');
return super.serializeResponse(response);
}
protected serializeError(err: any): any {
console.log('ERRORRRRRR');
return super.serializeError(err);
}
}
@Module({
imports: [
ClientsModule.register([
{
name: 'mservice',
customClass: ErrorHandlingProxy,
options: {
url: 'localhost:50052',
package: 'mservice',
protoPath: resolve(__dirname, '../../mservice/mservice.proto'),
},
},
]),
],
controllers: [GatewayController],
providers: [GatewayService],
})
export class GatewayModule {}
|
PepperAddict/zeitgeist
|
frontend/component/Columns.tsx
|
import React, { useState, useEffect } from 'react';
import Column from './Column';
import '../styles/columns.styl'
import { setMode } from '../redux/states.js';
import { useSelector, useDispatch, RootStateOrAny } from 'react-redux';
export default function Columns() {
const mode = useSelector((state: RootStateOrAny) => state.mode.value);
const dispatch = useDispatch()
const [col, setCol] = useState(mode)
useEffect(() => {
if (col) {
dispatch(setMode(col))
}
}, [col])
return (
<div className="roomColumnsContainer">
<div className="tabs-container">
<div className="tab col-START" onClick={() => setCol('START')}>START</div>
<div className="tab col-STOP" onClick={() => setCol('STOP')}>STOP</div>
<div className="tab col-CONTINUE" onClick={() => setCol('CONTINUE')}>CONTINUE</div>
</div>
<Column column={col} />
</div>
)
}
|
PepperAddict/zeitgeist
|
frontend/component/App.tsx
|
import React from 'react';
import ReactDOM from 'react-dom';
import '../styles/app.styl'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import BG from './BG'
//redux portion
import store from '../redux/store'
import { Provider } from 'react-redux'
//apollo/graphql portion
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
//this portion enables subscriptions
import { WebSocketLink } from '@apollo/client/link/ws';
const link = new WebSocketLink({
uri: `ws://localhost:8080/subscriptions`,
options: {
reconnect: true
}
})
const client = new ApolloClient({
link,
uri: 'http://localhost:8080/graphql',
cache: new InMemoryCache()
})
// import components
import Welcome from './Welcome'
import Room from './Room'
const App = () => {
return (
<Provider store={store}>
<ApolloProvider client={client}>
<BG />
<Router>
<Route exact path="/">
<Welcome />
</Route>
<Route path="/room">
<Room />
</Route>
</Router>
</ApolloProvider>
</Provider>
)
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
|
PepperAddict/zeitgeist
|
frontend/component/BG.tsx
|
import React from 'react';
import Bubbles from './three'
import { useSelector, useDispatch, RootStateOrAny } from 'react-redux';
export default function Background() {
const mode = useSelector((state: RootStateOrAny) => state.mode.value)
return (
<Bubbles />
)
}
|
PepperAddict/zeitgeist
|
frontend/component/Room.tsx
|
<filename>frontend/component/Room.tsx
import React from 'react';
import '../styles/room.styl';
import Columns from './Columns';
import {Redirect} from 'react-router-dom'
import { REMOVE_All } from '../helpers/graphql';
import { useMutation } from '@apollo/client';
import logo from '../../public/images/logo.png';
import { setName, setMode } from '../redux/states.js';
import { useSelector, useDispatch, RootStateOrAny } from 'react-redux';
export default function Room() {
const [removeAll] = useMutation(REMOVE_All)
const user = useSelector((state: RootStateOrAny) => state.user.value);
const dispatch = useDispatch()
if (!user) {
return <Redirect to="/" />
}
const clearAll = () => {
dispatch(setName(''))
dispatch(setMode('START'))
removeAll();
}
return <div className="main-container">
<img src={logo} alt="logo" className="logo-room"/>
<Columns />
<span className="clear" onClick={() => clearAll()}>clear</span>
</div>
}
|
PepperAddict/zeitgeist
|
frontend/component/three.tsx
|
import { Canvas, extend, useFrame, useThree } from '@react-three/fiber';
import React, { useMemo, useRef, useState, Suspense } from 'react';
import * as THREE from 'three';
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass';
import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass';
import { Instances, Instance, Environment, ContactShadows } from '@react-three/drei'
import { EffectComposer, SSAO } from '@react-three/postprocessing'
export default function Bubbles() {
extend({ EffectComposer, RenderPass, UnrealBloomPass })
function Sphere({ geometry, x, y, z, s, color }) {
const ref = useRef()
useFrame((state) => {
ref.current.position.x = x - state.mouse.x * 2
ref.current.position.y = y - state.mouse.y * 2
ref.current.position.z = z - Math.sin((state.clock.getElapsedTime() * s))
})
return (
<mesh ref={ref} position={[x, y, z]} scale={[s, s, s]} geometry={geometry}>
<meshStandardMaterial color={color} roughness={0} />
</mesh>
)
}
function RandomSpheres({ color, amount, startSize }) {
const [geometry] = useState(() => new THREE.SphereGeometry(startSize, 25, 25), [])
const data = useMemo(() => {
return new Array(amount).fill().map((_, i) => ({
x: Math.random() * 150 - 50,
y: Math.random() * 150 - 50,
z: Math.random() * 150 - 50,
s: Math.random() + 2,
}))
}, [])
return data.map((props, i) => <Sphere key={i} {...props} geometry={geometry} color={color} />)
}
function Main({ children }) {
const scene = useRef()
const { gl } = useThree()
const width = window.innerWidth;
const height = window.innerHeight;
const camera = new THREE.PerspectiveCamera(90, width / height, 0.1, 1000);
//const camera = new THREE.OrthographicCamera(width/-2, width /2, height /2, height / -2, 1, 1000)
useFrame(() => {
gl.autoClear = false
gl.clearDepth()
gl.render(scene.current, camera)
}, 2)
return <scene ref={scene}>{children}</scene>
}
return (
<Canvas linear camera={{ position: [0, 0, 120] }}>
<Main>
<fog attach="fog" args={["white", 0, 40]} />
<ambientLight intensity={0.4} />
<directionalLight
castShadow
position={[2.5, 8, 5]}
intensity={2.5}
shadow-mapSize-width={1024}
shadow-mapSize-height={1024}
shadow-camera-far={150}
shadow-camera-left={-110}
shadow-camera-right={110}
shadow-camera-top={110}
shadow-camera-bottom={-110}
/>
<pointLight position={[-10, 0, -20]} color="rgba(255, 144, 225)" intensity={0.5} />
<pointLight position={[0, -10, 0]} intensity={1.5} />
<Suspense fallback={null}>
<Environment preset="city" />
</Suspense>
<ContactShadows position={[0, -30, 0]} opacity={0.5} width={130} height={130} blur={2} far={40} />
<RandomSpheres color="gray" amount={100} startSize={1} />
<RandomSpheres color="rgba(255, 144, 225)" amount={50} startSize={1} />
<RandomSpheres color="rgba(20, 202, 255)" amount={100} startSize={0.5} />
</Main>
</Canvas>
)
}
|
PepperAddict/zeitgeist
|
frontend/component/UploadImage.tsx
|
import React, { useState, useRef, useEffect } from 'react';
import { useMutation } from '@apollo/client';
import { POST_MESSAGE } from '../helpers/graphql.js';
var formData = new FormData()
export default function UploadImage({ name }) {
const [file, setFile] = useState(null)
const [sendMessage] = useMutation(POST_MESSAGE);
const imageInput = useRef();
const uploadFile = (e) => {
e.preventDefault();
const acceptedImages = ["image/jpeg", "image/png", "image/gif"]
if ( file && acceptedImages.includes(file.type)) {
formData.append('myFile', file)
fetch('http://localhost:8080/upload', {
method: "POST",
body: formData
}).then((res) => res.text()).then((response) => {
sendMessage({
variables: {
theUser: name,
theMessage: response,
theFile: 'true'
}
})
//reset everything
setFile(null);
if (imageInput) (imageInput as any).current.value = ""
formData = new FormData();
}).catch((err) => console.log(err))
} else {
console.log('not allowed')
}
}
return (
<form onSubmit={uploadFile}>
<input type="file" id="myFile" name="filename" ref={imageInput} onChange={(e) => setFile(e.target.files[0])} />
<button type="submit">upload</button>
</form>
)
}
|
PepperAddict/zeitgeist
|
frontend/component/three2.tsx
|
<filename>frontend/component/three2.tsx<gh_stars>0
import * as THREE from 'three'
import { render } from 'react-dom'
import React, { useRef, useState, useMemo, useEffect } from 'react'
import { Canvas, extend, useThree, useFrame } from '@react-three/fiber'
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer'
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass'
import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass'
extend({ EffectComposer, RenderPass, UnrealBloomPass })
function Sphere({ geometry, x, y, z, s, color }) {
const ref = useRef()
useFrame((state) => {
ref.current.position.x = x - state.mouse.x * 2
ref.current.position.y = y - state.mouse.y * 2
ref.current.position.z = z + Math.sin((state.clock.getElapsedTime() * s) / 2)
})
return (
<mesh ref={ref} position={[x, y, z]} scale={[s, s, s]} geometry={geometry} color={color} >
<meshStandardMaterial color={color} roughness={1} />
</mesh>
)
}
function RandomSpheres({color, amount, startSize}) {
const [geometry] = useState(() => new THREE.SphereGeometry(startSize, 32, 32), [])
const data = useMemo(() => {
return new Array(amount).fill().map((_, i) => ({
x: Math.random() * 100 - 50,
y: Math.random() * 100 - 50,
z: Math.random() * 100 - 50,
s: Math.random() + 10,
}))
}, [])
return data.map((props, i) => <Sphere key={i} {...props} geometry={geometry} color={color} />)
}
function Bloom({ children }) {
const { gl, camera, size } = useThree()
const [scene, setScene] = useState()
const composer = useRef()
useEffect(() => void scene && composer.current.setSize(size.width, size.height), [size])
useFrame(() => scene && composer.current.render(), 1)
return (
<>
<scene ref={setScene}>{children}</scene>
<effectComposer ref={composer} args={[gl]}>
<renderPass attachArray="passes" scene={scene} camera={camera} />
<unrealBloomPass attachArray="passes" args={[undefined, 1.5, 1, 0]} />
</effectComposer>
</>
)
}
function Main({ children }) {
const scene = useRef()
const { gl } = useThree()
const width = window.innerWidth;
const height = window.innerHeight;
const camera = new THREE.PerspectiveCamera(90, width / height, 0.1, 1000);
useFrame(() => {
gl.autoClear = false
gl.clearDepth()
gl.render(scene.current, camera)
}, 2)
return <scene ref={scene}>{children}</scene>
}
export default function Dots() {
return(
<Canvas linear camera={{ position: [0, 0, 120] }}>
<Main>
<pointLight />
<ambientLight />
<RandomSpheres color="rgba(20, 202, 255)" amount={100} startSize={0.5} />
</Main>
<Bloom>
<ambientLight />
<RandomSpheres color="rgba(20, 202, 255)" amount={100} startSize={0.5} />
</Bloom>
</Canvas>
)
}
|
PepperAddict/zeitgeist
|
frontend/component/Particles.tsx
|
import * as THREE from 'three'
import { useMemo, useState, useRef } from 'react'
import { createPortal, useFrame } from '@react-three/fiber'
import { useFBO } from '@react-three/drei'
import './shaders/simulationMaterial.js'
import './shaders/doPointsMaterial.js'
export function Particles({ speed, fov, aperture, focus, curl, size = 512, ...props }) {
const simRef = useRef()
const renderRef = useRef()
// Set up FBO
const [scene] = useState(() => new THREE.Scene())
const [camera] = useState(() => new THREE.OrthographicCamera(-1, 1, 1, -1, 1 / Math.pow(2, 53), 1))
const [positions] = useState(() => new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0]))
const [uvs] = useState(() => new Float32Array([0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0]))
const target = useFBO(size, size, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBFormat, type: THREE.FloatType })
// Normalize points
const particles = useMemo(() => {
const length = size * size
const particles = new Float32Array(length * 3)
for (let i = 0; i < length; i++) {
let i3 = i * 3
particles[i3 + 0] = (i % size) / size
particles[i3 + 1] = i / size / size
}
return particles
}, [size])
// Update FBO and pointcloud every frame
useFrame((state) => {
state.gl.setRenderTarget(target)
state.gl.clear()
state.gl.render(scene, camera)
state.gl.setRenderTarget(null)
renderRef.current.uniforms.positions.value = target.texture
renderRef.current.uniforms.uTime.value = state.clock.elapsedTime
renderRef.current.uniforms.uFocus.value = THREE.MathUtils.lerp(renderRef.current.uniforms.uFocus.value, focus, 0.1)
renderRef.current.uniforms.uFov.value = THREE.MathUtils.lerp(renderRef.current.uniforms.uFov.value, fov, 0.1)
renderRef.current.uniforms.uBlur.value = THREE.MathUtils.lerp(renderRef.current.uniforms.uBlur.value, (5.6 - aperture) * 9, 0.1)
simRef.current.uniforms.uTime.value = state.clock.elapsedTime * speed
simRef.current.uniforms.uCurlFreq.value = THREE.MathUtils.lerp(simRef.current.uniforms.uCurlFreq.value, curl, 0.1)
})
return (
<>
{/* Simulation goes into a FBO/Off-buffer */}
{createPortal(
<mesh>
<simulationMaterial ref={simRef} />
<bufferGeometry>
<bufferAttribute attachObject={['attributes', 'position']} count={positions.length / 3} array={positions} itemSize={3} />
<bufferAttribute attachObject={['attributes', 'uv']} count={uvs.length / 2} array={uvs} itemSize={2} />
</bufferGeometry>
</mesh>,
scene
)}
{/* The result of which is forwarded into a pointcloud via data-texture */}
<points {...props}>
<dofPointsMaterial ref={renderRef} />
<bufferGeometry>
<bufferAttribute attachObject={['attributes', 'position']} count={particles.length / 3} array={particles} itemSize={3} />
</bufferGeometry>
</points>
</>
)
}
|
PepperAddict/zeitgeist
|
frontend/component/Column.tsx
|
import { useMutation, useSubscription } from '@apollo/client';
import React, { useState, useRef, useEffect } from 'react';
import { POST_MESSAGE, WATCH_MESSAGE, REMOVE_MESSAGE } from '../helpers/graphql';
import { RootStateOrAny, useSelector } from 'react-redux';
import '../styles/columns.styl';
const sdk = require('microsoft-cognitiveservices-speech-sdk');
const speechConfig = sdk.SpeechConfig.fromSubscription(process.env.SPEECH_KEY, "eastus")
let audioConfig = sdk.AudioConfig.fromDefaultMicrophoneInput()
let recognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig)
//This is for deleting a message if it belongs to the user
function DeleteMessage({ id }) {
const [removeMessage] = useMutation(REMOVE_MESSAGE)
const initiateRemoval = () => {
removeMessage({ variables: { id } })
}
return <span onClick={() => initiateRemoval()}>✖</span>
}
function Message(props) {
const { message, user, name, _id } = props;
const [hide, setHide] = useState(true);
return <p className="chat" key={_id}> {message}{(user === name) && <DeleteMessage id={_id} />} </p>
}
function Messages(props) {
return (<div className="chat-container">
{props.messages.sort((a, b) => b._id - a._id).map(({ _id, name, message, column }) => {
if (column.toLowerCase() === props.theColumn.toLowerCase()) {
return <Message {...props} name={name} _id={_id} message={message} key={_id} />
}
})}
</div>
)
}
export default function Column({ column }) {
const user = useSelector((state: RootStateOrAny) => state.user.value);
let [message, setMessage] = useState('')
const inputText = useRef();
const [sendMessage] = useMutation(POST_MESSAGE);
const { loading, error, data } = useSubscription(WATCH_MESSAGE);
const [listening, setListening] = useState(false);
const [audio, setAudio] = useState('' as any);
const submitForm = () => {
event.preventDefault();
if (message.length > 1) {
console.log(user, message, column)
sendMessage({
variables: {
theUser: user,
theMessage: message,
theColumn: column
}
})
}
setMessage(' ')
}
const stopListening = () => {
audio.getTracks().forEach(
(track) => {
track.stop();
});
submitForm();
window.location.reload();
setListening(false);
}
const initiate = () => {
setListening(true);
if (navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({ video: false, audio: true }).then(stream => {
recognizer.startContinuousRecognitionAsync();
setAudio(stream)
recognizer.recognized = (s, e) => {
if (e.result.text) {
setMessage(message += e.result.text)
if (e.result.text.toLowerCase().includes('send comment')) {
submitForm();
message = ''
setMessage('')
}
if (e.result.text.toLowerCase().includes('stop listening')) {
submitForm();
window.location.reload();
}
}
};
})
}
}
return (
<div className={"column-container col-" + column}>
<form onSubmit={(e) => submitForm()}>
<label>
<textarea value={message} ref={inputText} onChange={(e) => setMessage(e.target.value)} placeholder="Enter a comment" />
<div className="listeningContainer">
{!listening ? <span onClick={initiate}>🎤 Listen</span> :
<span className="active" onClick={stopListening}>To submit, say: <span className="sayThis">Send comment</span>. <br /> Click or say: <span className="sayThis">Stop Listening</span> to end</span>}
</div>
</label>
<button type="submit">Add</button>
</form>
{data && <Messages messages={data.newMessages} user={user} theColumn={column} />}
</div>
)
}
|
PepperAddict/zeitgeist
|
frontend/component/Welcome.tsx
|
import React, {useState, useRef} from 'react';
import { Redirect } from 'react-router-dom';
import { useSelector, useDispatch, RootStateOrAny } from 'react-redux';
import { setName } from '../redux/states.js';
import '../styles/app.styl'
import logo from '../../public/images/logo.png';
export default function Welcome () {
const [name, inputName] = useState(null);
const dispatch = useDispatch()
const user = useSelector((state: RootStateOrAny) => state.user.value)
const enterUsername = async(e) => {
e.preventDefault();
await dispatch(setName(name))
}
if (user) {
return <Redirect to="/room/" />
}
return (
<div className="home-container">
<div className="boxContainer">
<img src={logo} alt="logo" className="logo"/>
<div className="box1"><span>REFLECT</span></div>
<div className="box2"><span>IMPROVE</span></div>
<form onSubmit={enterUsername}>
<input placeholder="Enter a nickname" pattern="[A-Za-z]{3,10}" title="Letters only 3-10 characters" onChange={(e) => inputName(e.target.value)} />
<button type="submit">Enter</button>
</form>
</div>
</div>
)
}
|
nythonore/mlabs-blog
|
src/resources/views/BlogListView.tsx
|
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { Container, Row, Col } from 'react-bootstrap';
import { listBlog } from '../../domain/blog/actions';
import Blog from '../components/Blog';
import Search from '../components/Search';
import useTypedSelector from '../../core/hooks/useTypedSelector';
const BlogListView = () => {
const dispatch = useDispatch();
const { loading, data } = useTypedSelector(state => state.blog);
useEffect(() => {
dispatch(listBlog());
}, [dispatch]);
return (
<div className='blog py-5'>
<Container fluid>
<Row>
<Col md={12}>
<Row className='align-items-center'>
<Col>
<h2 className='font-sz-24 font-wg-600 text-white title'>
Featured Blog
</h2>
</Col>
<Col md={6} lg={3}>
<Search />
</Col>
</Row>
</Col>
</Row>
<Row className='mt-5'>
{loading
? null
: data.map((data, key) => (
<Col md={6} className='mb-4'>
<Blog key={key} data={data} />
</Col>
))}
</Row>
</Container>
</div>
);
};
export default BlogListView;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.