repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
caos/zitadel-examples
b2b-nextjs/pages/api/grantedprojects.tsx
<reponame>caos/zitadel-examples<filename>b2b-nextjs/pages/api/grantedprojects.tsx import { NextApiRequest, NextApiResponse } from 'next'; import { BearerToken, hasRole, requestAccessToken } from '../../lib/jwt'; import { handleFetchErrors } from '../../lib/middleware'; function getGrantedProjectsOfUser( userId: string, orgId: string, authorizationHeader: string ): Promise<any> { return hasRole("reader", orgId, authorizationHeader) .then((isAllowed) => { if (isAllowed) { return requestAccessToken().then((token: BearerToken) => { const request = `https://api.zitadel.ch/management/v1/projectgrants/_search`; return fetch(request, { headers: { authorization: `Bearer ${token.access_token}`, "x-zitadel-org": process.env.ORG_ID, "content-type": "application/json", }, method: "POST", body: JSON.stringify({ query: { limit: 100, asc: true, }, queries: [ { grantedOrgIdQuery: { grantedOrgId: orgId, }, }, ], }), }) .then(handleFetchErrors) .then((resp) => { return resp.json(); }); }); } else { throw new Error("not allowed"); } }) .catch((error) => { throw new Error("not allowed"); }); } const handler = async (req: NextApiRequest, res: NextApiResponse) => { // await runMiddleware(req, res, cors); if (req.method === "GET") { const userId = req.headers.userid as string; const orgId = req.headers.orgid as string; const authorizationHeader = req.headers.authorization as string; return getGrantedProjectsOfUser(userId, orgId, authorizationHeader) .then((resp) => { res.status(200).json(resp); }) .catch((error) => { console.error("got an error", error); res.status(500).json(error); }); } }; export default handler;
caos/zitadel-examples
b2b-nextjs/lib/org.ts
import create from 'zustand'; import { ZitadelOrg } from '../components/OrgContext'; const orgStore = create((set) => ({ org: null, setOrg: (orgToSet: ZitadelOrg) => set(() => ({ org: orgToSet, })), })); export default orgStore;
caos/zitadel-examples
b2b-nextjs/components/RoleCheck.tsx
<filename>b2b-nextjs/components/RoleCheck.tsx import { useSession } from "next-auth/react"; import { useContext } from "react"; import orgStore from "../lib/org"; export default function RolesCheck(props: any) { const { data: session } = useSession(); const org = orgStore((state) => (state as any).org); const hasRoles = !!( org && org.id && session && session.user && session.user.roles && (props.requiredRole ? session.user.roles[props.requiredRole] && session.user.roles[props.requiredRole][org.id] : Object.keys(session.user.roles).findIndex((role) => { return session.user.roles[role][org.id]; }) > -1) ); return session && session.accessToken && hasRoles ? props.children : props.fallback || ( <div className="max-w-7xl mx-auto px-6 py-10"> <div className="flex flex-col items-center"> <p className="mb-4 text-red-500"> You don&apos;t have any roles for this organization </p> </div> </div> ); }
caos/zitadel-examples
b2b-nextjs/lib/middleware.ts
import { NextApiRequest, NextApiResponse } from 'next'; export function runMiddleware( req: NextApiRequest, res: NextApiResponse, fn: any ) { return new Promise((resolve, reject) => { fn(req, res, (result: any) => { if (result instanceof Error) { return reject(result); } return resolve(result); }); }); } export const handleFetchErrors = (response: any) => { if (!response.ok) { console.error("handleFetchErrors: not ok"); console.error(response); throw new Error(response?.statusText ?? "Unknown Error"); } else { return response; } };
caos/zitadel-examples
b2b-nextjs/components/OrgContext.tsx
<gh_stars>1-10 import { Listbox, Transition } from '@headlessui/react'; import { CheckIcon, SelectorIcon } from '@heroicons/react/outline'; import { getSession } from 'next-auth/react'; import { Fragment, useEffect, useState } from 'react'; import orgStore from '../lib/org'; export type ZitadelOrg = { id: string; name: string; }; const orgMap = (res: any): ZitadelOrg[] => { return res.result; }; export default function OrgContext() { const fetcher = async (url: string, cb: any) => { const session = (await getSession()) as any; return fetch(`${url}`, { method: "POST", headers: { authorization: `Bearer ${session.accessToken}`, }, }) .then((res) => res.json()) .then(cb); }; const setOrg = orgStore((state) => (state as any).setOrg); const org = orgStore((state) => (state as any).org); const [orgs, setOrgs] = useState<ZitadelOrg[]>([]); useEffect(() => { const org = orgStore.getState().org; fetcher( "https://api.zitadel.ch/auth/v1/global/projectorgs/_search", orgMap ).then((orgs) => { if (!org && orgs && orgs.length) { setOrgs(orgs); setOrg(orgs[0]); } }); }, []); return ( <div className="w-60 ml-20"> <Listbox value={org} onChange={setOrg}> <div className="relative mt-1"> <Listbox.Button className="relative w-full py-2 pl-3 pr-10 text-left bg-zitadelblue-600 rounded-lg shadow-md cursor-default focus:outline-none focus-visible:ring-2 focus-visible:ring-opacity-75 focus-visible:ring-white focus-visible:ring-offset-orange-300 focus-visible:ring-offset-2 focus-visible:border-indigo-500 sm:text-sm"> <span className="block truncate"> {org?.name ?? "No org selected"} </span> <span className="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none"> <SelectorIcon className="w-5 h-5 text-gray-400" aria-hidden="true" /> </span> </Listbox.Button> <Transition as={Fragment} leave="transition ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0" > <Listbox.Options className="absolute w-full py-1 mt-1 overflow-auto text-base bg-zitadelblue-600 rounded-md shadow-lg max-h-60 ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm"> {orgs && orgs.map((person, personIdx) => ( <Listbox.Option key={personIdx} className={({ active }) => `${ active ? "text-amber-900 bg-amber-100" : "text-gray-200" } cursor-default select-none relative py-2 pl-10 pr-4` } value={person} > {({ selected, active }) => ( <> <span className={`${ selected ? "font-medium" : "font-normal" } block truncate`} > {person.name} </span> {selected ? ( <span className={`${ active ? "text-amber-600" : "text-amber-600" } absolute inset-y-0 left-0 flex items-center pl-3`} > <CheckIcon className="w-5 h-5" aria-hidden="true" /> </span> ) : null} </> )} </Listbox.Option> ))} </Listbox.Options> </Transition> </div> </Listbox> </div> ); }
caos/zitadel-examples
b2b-nextjs/components/GrantRadio.tsx
import { RadioGroup } from "@headlessui/react"; import { EyeIcon } from "@heroicons/react/outline"; import { useSession } from "next-auth/react"; import { useState } from "react"; import orgStore from "../lib/org"; import { Role, ROLES } from "../lib/roles"; export default function GrantRadio({ selected, setSelected }: any) { const { data: session } = useSession(); const org = orgStore((state) => (state as any).org); function isAllowed(requestedRoles: string[]): boolean { const isAllowed = !!( org && org.id && session && session.user && session.user.roles && requestedRoles && requestedRoles.findIndex((role) => { return session.user.roles[role] && session.user.roles[role][org.id]; }) > -1 ); return isAllowed; } return ( <div className="w-full py-4"> <div className="mx-auto max-w-7xl px-6"> <RadioGroup className="" value={selected} onChange={setSelected}> <RadioGroup.Label className="sr-only">Server size</RadioGroup.Label> <div className="grid grid-cols-2 space-x-4"> {ROLES.map((role: Role) => ( <RadioGroup.Option key={role.name} value={role} disabled={!isAllowed(role.roles)} className={({ active, checked, disabled }) => `${ active ? "ring-2 ring-offset-2 ring-offset-white ring-white ring-opacity-30" : "" } ${ checked ? "bg-zitadelblue-700 bg-opacity-75 text-white" : "bg-zitadelblue-400" } ${ disabled ? "bg-gray-600 opacity-50 text-gray-500 cursor-not-allowed" : "" } relative rounded-lg shadow-md px-5 py-4 cursor-pointer flex focus:outline-none` } > {({ active, checked }) => ( <> <div className="flex items-center justify-between w-full"> <div className="flex items-center"> <div className="text-sm"> <RadioGroup.Label as="p" className={`font-medium ${ checked ? "text-white" : "text-white" }`} > {role.name} </RadioGroup.Label> <RadioGroup.Description as="span" className={`inline ${ checked ? "text-sky-100" : "text-gray-500" }`} > <span>{role.desc}</span>{" "} </RadioGroup.Description> </div> </div> {checked && ( <div className="flex-shrink-0 text-white"> <EyeIcon className="text-zitadelaccent-500 w-6 h-6" /> </div> )} </div> </> )} </RadioGroup.Option> ))} </div> </RadioGroup> </div> </div> ); }
caos/zitadel-examples
angular/src/app/components/user/user.component.ts
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { AuthenticationService } from 'src/app/services/authentication.service'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.scss'] }) export class UserComponent implements OnInit { public user$: Observable<any>; constructor(private auth: AuthenticationService) { this.user$ = this.auth.getOIDCUser(); } ngOnInit(): void { } triggerSignout(): void { this.auth.signout(); } }
caos/zitadel-examples
b2b-nextjs/lib/localized-date.ts
<gh_stars>1-10 import { format } from 'date-fns'; import { de, enUS, it } from 'date-fns/locale'; export default function localizedDate(timestamp: string | number, localeCode: string, hoursOnly: boolean = false) { // const date: Date = dateFromTimestamp(ts); if (typeof timestamp === 'string') { const ts = timestamp; let date: Date = new Date(ts); switch (localeCode) { case 'de': return format(date, hoursOnly ? 'HH:mm' : 'dd. MMM yyyy, HH:mm', { locale: de }); case 'it': return format(date, hoursOnly ? 'HH:mm' : 'dd. MMM yyyy, HH:mm', { locale: it }); case 'en': return format(date, hoursOnly ? 'HH:mm' : 'yyyy MMM dd, HH:mm', { locale: enUS }); default: return format(date, hoursOnly ? 'HH:mm' : 'dd. MMM yyyy', { locale: de }); } } else if (typeof (timestamp) === 'number') { const ts = timestamp * 1000; let date: Date = new Date(); date.setTime(ts); switch (localeCode) { case 'de': return format(date, hoursOnly ? 'HH:mm' : 'dd. MMM yyyy, HH:mm', { locale: de }); case 'it': return format(date, hoursOnly ? 'HH:mm' : 'dd. MMM yyyy, HH:mm', { locale: it }); case 'en': return format(date, hoursOnly ? 'HH:mm' : 'yyyy MMM dd, HH:mm', { locale: enUS }); default: return format(date, hoursOnly ? 'HH:mm' : 'dd. MMM yyyy', { locale: de }); } } else { return timestamp; } }
caos/zitadel-examples
angular/src/app/app-routing.module.ts
<gh_stars>1-10 import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './components/home/home.component'; import { SignedOutComponent } from './components/signed-out/signed-out.component'; import { UserComponent } from './components/user/user.component'; import { AuthGuard } from './guards/auth.guard'; const routes: Routes = [ { path: '', component: HomeComponent, }, { path: 'user', component: UserComponent, canActivate: [AuthGuard], }, { path: 'auth/callback', redirectTo: 'user' }, { path: 'signedout', component: SignedOutComponent }, { path: '**', redirectTo: '/' }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
caos/zitadel-examples
b2b-nextjs/components/UserGrantTable.tsx
<reponame>caos/zitadel-examples<filename>b2b-nextjs/components/UserGrantTable.tsx import { getSession } from 'next-auth/react'; import useSWR from 'swr'; import orgStore from '../lib/org'; export default function UserGrantTable() { const fetcher = async (url: string) => { const session = (await getSession()) as any; const org = orgStore.getState().org; return fetch(`${url}`, { method: "GET", headers: { "content-Type": "application/json", authorization: `Bearer ${session.accessToken}`, orgid: org.id, }, }) .then((res) => res.json()) .then((resp) => resp.result) .catch((error) => { console.error(error); }); }; const { data: usergrants, error: orgError } = useSWR( "/api/usergrants", (url) => fetcher(url) ); return ( <div className="max-w-7xl mx-auto px-6 pt-10"> <h2 className="text-3xl mb-2">User Grants</h2> <p className="text-sm text-gray-300 mb-4"> These are the unfiltered user grants of your organization </p> <div className="-mx-4 sm:-mx-8 px-4 sm:px-8 py-4 overflow-x-auto"> <div className="inline-block min-w-full shadow-md rounded-lg overflow-hidden"> <table className="min-w-full leading-normal"> <thead> <tr> <th className="px-5 py-3 border-b-2 border-gray-400 text-left text-xs font-semibold text-gray-200 uppercase tracking-wider"> User </th> <th className="px-5 py-3 border-b-2 border-gray-400 text-left text-xs font-semibold text-gray-200 uppercase tracking-wider"> Organization </th> <th className="px-5 py-3 border-b-2 border-gray-400 text-left text-xs font-semibold text-gray-200 uppercase tracking-wider"> Project </th> <th className="px-5 py-3 border-b-2 border-gray-400 text-left text-xs font-semibold text-gray-200 uppercase tracking-wider"> Roles </th> </tr> </thead> <tbody> {usergrants && usergrants.map((grant, i) => { return ( <tr key={`${grant.id}${i}`} className="group cursor-pointer hover:bg-zitadelblue-400" > <td className="px-5 py-5 border-b border-gray-600 text-sm group"> <div className="flex flex-col"> <p className="text-white whitespace-no-wrap"> {grant.displayName} </p> <p className="block text-sm text-gray-400 whitespace-no-wrap"> {grant.email} </p> </div> </td> <td className="px-5 py-5 border-b border-gray-600 text-sm group"> <p className="text-white whitespace-no-wrap"> {grant.orgName} </p> </td> <td className="px-5 py-5 border-b border-gray-600 text-sm group"> <p className="text-white whitespace-no-wrap"> {grant.projectName} </p> </td> <td className="px-5 py-5 border-b border-gray-600 text-sm group"> <p className="text-white whitespace-no-wrap"> {grant.roleKeys ? grant.roleKeys.join(", ") : ""} </p> </td> </tr> ); })} </tbody> </table> </div> </div> </div> ); }
caos/zitadel-examples
b2b-nextjs/components/UserGrant.tsx
<reponame>caos/zitadel-examples import { useSession } from 'next-auth/react'; import orgStore from '../lib/org'; export default function UserGrant() { const org = orgStore((state) => (state as any).org); const { data: session } = useSession(); let roles = []; if (session && session.user && org?.id && session.user.roles) { roles = Object.keys(session.user.roles).map((role) => { return session.user.roles[role][org.id] ? role : null; }); } return ( session && ( <div className="py-4"> You ({session.user.preferred_username}) have{" "} <strong className={`${ roles && roles.length ? "text-green-500" : "text-red-500" }`} > {roles && roles.length ? roles.join(",") : "no"} </strong>{" "} roles for this application and the organization set above. </div> ) ); }
caos/zitadel-examples
b2b-nextjs/components/Footer.tsx
<reponame>caos/zitadel-examples import { useRouter } from 'next/router'; import FooterLink from './FooterLink'; const Footer = () => { const router = useRouter(); const effectClasses = "filter grayscale transform hover:brightness-75 dark:hover:brightness-125"; return ( <> <footer className="bg-footer-light dark:bg-zitadelblue-900 text-grey font-medium text-sm pt-8 w-full"> <div className="container mx-auto flex-col px-6 max-w-7xl"> <div className="flex flex-row flex-wrap -mx-3"> <div className="flex-1 px-3 py-6 min-w-half md:min-w-0 box-border"> <p className="text-xs text-gray-400 uppercase mb-4 font-semibold"> ZITADEL </p> <FooterLink external href="https://zitadel.ch"> Home </FooterLink> <FooterLink external href="https://zitadel.ch/opensource"> Opensource </FooterLink> </div> <div className="flex-1 px-3 py-6 min-w-half md:min-w-0 box-border"> <p className="text-xs text-gray-400 uppercase mb-4 font-semibold"> Examples </p> <FooterLink href="https://docs.zitadel.ch/docs/quickstarts/introduction" external > Quickstarts </FooterLink> <FooterLink href="https://github.com/caos/zitadel-examples" external > Example Repo </FooterLink> </div> </div> <div className="flex-1 p-4 md:px-0 flex flex-col items-center md:flex-row md:justify-between border-t border-gray-500 border-opacity-30 text-xs"> <div className="flex-1"> <p className="text-gray-600 dark:text-gray-300 text-center md:text-left mb-2"> <a className="hover:text-pink-600" href="https://caos.ch"> <NAME> </a> , Teufener Str. 19, 9000 St. Gallen </p> <span className="text-gray-500 md:mr-6">© 2021</span> </div> <div className="grid grid-cols-3 gap-2 my-2"> <a className="hover:text-gray-500 dark:text-gray-400 dark:hover:text-white" target="_blank" rel="noreferrer" href="https://github.com/caos" > <i className="text-3xl lab la-github"></i> </a> <a className="hover:text-gray-500 dark:text-gray-400 dark:hover:text-white" target="_blank" rel="noreferrer" href="https://twitter.com/caos_ch" > <i className="text-3xl lab la-twitter"></i> </a> <a className="hover:text-gray-500 dark:text-gray-400 dark:hover:text-white" target="_blank" rel="noreferrer" href="https://www.linkedin.com/company/caos-ag/" > <i className="text-3xl lab la-linkedin"></i> </a> </div> </div> </div> </footer> </> ); }; export default Footer;
caos/zitadel-examples
b2b-nextjs/components/GrantedProjects.tsx
import { getSession } from 'next-auth/react'; import { useEffect, useState } from 'react'; import useSWR from 'swr'; import orgStore from '../lib/org'; import ProjectItem from './ProjectItem'; export default function GrantedProjects() { const fetcher = async (url: string) => { const session = (await getSession()) as any; const org = orgStore.getState().org; return fetch(`${url}`, { method: "GET", headers: { "content-Type": "application/json", authorization: `Bearer ${session.accessToken}`, orgid: org.id, }, }) .then((res) => res.json()) .then((resp) => resp.result) .catch((error) => { console.error(error); }); }; const { data: projects, error: orgError } = useSWR( "/api/grantedprojects", (url) => fetcher(url) ); return projects && projects.length ? ( <div className="py-10 container md:mx-auto max-w-7xl"> <div className="px-6 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4"> {projects.map((project) => ( <div key={` ${project.projectId}${project.grantId}`} > <ProjectItem project={project} /> </div> ))} </div> </div> ) : ( <div className="py-4 container md:mx-auto max-w-7xl px-6"> <p className="text-red-500">No granted projects found!</p> </div> ); }
caos/zitadel-examples
b2b-nextjs/components/ProfileImage.tsx
import { Menu, Transition } from '@headlessui/react'; import { LogoutIcon, PencilIcon } from '@heroicons/react/outline'; import { getSession, signIn, signOut } from 'next-auth/react'; import { Fragment, useEffect, useState } from 'react'; export default function ProfileImage({ user }: { user?: any | null }) { const sessionMap = (res: any): any[] => { return res.result; }; const fetcher = async (url: string, cb: any) => { const session = (await getSession()) as any; return fetch(`${url}`, { method: "POST", headers: { authorization: `Bearer ${session.accessToken}`, }, }) .then((res) => res.json()) .then(cb); }; const [sessions, setSessions] = useState<any[]>([]); useEffect(() => { fetcher( "https://api.zitadel.ch/auth/v1/users/me/sessions/_search", sessionMap ).then((sessions) => { if (sessions && sessions.length) { setSessions(sessions); } }); }, []); function signInWithHint(session: any): void { signIn( "zitadel", { callbackUrl: "/", }, { login_hint: session.loginName, } ); } return ( <Menu as="div" className="relative inline-block text-left"> <div> <Menu.Button className="flex items-center bg-zitadelblue-400 justify-center ml-4 transition-all h-8 w-8 rounded-full shadow-lg ring-2 ring-white ring-opacity-50 hover:ring-opacity-100"> {user && user.image ? ( <img className="h-8 w-8 rounded-full" src={user.image} alt="user avatar" /> ) : ( <span className="text-sm"> {user ? user.name.substring(0, 1) : "A"} </span> )} </Menu.Button> </div> <Transition as={Fragment} enter="transition ease-out duration-100" enterFrom="transform opacity-0 scale-95" enterTo="transform opacity-100 scale-100" leave="transition ease-in duration-75" leaveFrom="transform opacity-100 scale-100" leaveTo="transform opacity-0 scale-95" > <Menu.Items className="absolute w-80 right-0 mt-5 origin-top-right bg-zitadelblue-400 divide-y divide-gray-500 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"> <div className="px-1 py-1 "> <div className="flex flex-col items-center py-4"> <p>{user?.name}</p> <p className="text-gray-300 text-sm">{user?.email}</p> </div> <Menu.Item> {({ active }) => ( <a href="https://console.zitadel.ch/users/me" target="_blank" rel="noreferrer" className={`${ active ? "bg-zitadelblue-300 text-white" : "text-gray-300" } group flex rounded-md justify-center items-center w-full px-2 py-2 text-sm`} > {active ? ( <PencilIcon className="w-5 h-5 mr-2" aria-hidden="true" /> ) : ( <PencilIcon className="w-5 h-5 mr-2" aria-hidden="true" /> )} Edit Profile </a> )} </Menu.Item> </div> <div className="px-1 py-1 max-h-96 overflow-y-auto"> {sessions.map((session, i) => ( <Menu.Item key={`${session.userName}${i}`}> {({ active }) => ( <button onClick={() => signInWithHint(session)} className={`${ active ? "bg-zitadelblue-300 text-white" : "text-gray-300" } group flex rounded-md items-center w-full px-2 py-2 text-sm`} > <div className="w-8 h-8 mr-2 flex items-center justify-center rounded-full bg-black bg-opacity-20"> <span className="text-sm"> {session ? session.displayName.substring(0, 1) : "A"} </span> </div> <div className="flex flex-col justify-start"> <span className="text-left">{session.displayName}</span> <span className="text-left text-sm"> {session.userName} </span> <span className={`text-left text-sm ${ session.authState === "SESSION_STATE_ACTIVE" ? "text-green-500" : "text-red-500" }`} > {session.authState === "SESSION_STATE_ACTIVE" ? "active" : "inactive"} </span> </div> </button> )} </Menu.Item> ))} </div> <div className="px-1 py-1"> <Menu.Item> {({ active }) => ( <button onClick={() => signOut()} className={`${ active ? "bg-zitadelaccent-800 text-white" : "text-gray-300" } group flex rounded-md justify-center items-center w-full px-2 py-2 text-sm`} > {active ? ( <LogoutIcon className="w-5 h-5 mr-2 text-violet-400" aria-hidden="true" /> ) : ( <LogoutIcon className="w-5 h-5 mr-2 text-violet-400" aria-hidden="true" /> )} Logout </button> )} </Menu.Item> </div> </Menu.Items> </Transition> </Menu> ); }
caos/zitadel-examples
b2b-nextjs/lib/roles.ts
<reponame>caos/zitadel-examples export const ROLES: Role[] = [ { name: "Granted Projects", desc: "You need to have reader role to view granted projects", roles: ["reader", "admin"], }, { name: "Authorizations", desc: "You need to have admin role to view user grants", roles: ["admin"], }, ]; export interface Role { name: string; desc: string; roles: string[]; // one of the given roles enables the selection if available on the user }
caos/zitadel-examples
b2b-nextjs/lib/jwt.ts
<reponame>caos/zitadel-examples import { handleFetchErrors } from './middleware'; var jwt = require("jsonwebtoken"); type ZitadelSecret = { type: string; userId: string; keyId: string; key: string; }; export type BearerToken = { access_token: string; expires_in: number; token_type: "Bearer"; }; export function requestAccessToken(): Promise<BearerToken> { const secret: ZitadelSecret = JSON.parse( process.env.SERVICE_ACCOUNT_SECRET as any ); const jwtPayload = { iss: secret.userId, sub: secret.userId, aud: "https://issuer.zitadel.ch", alg: "RS256", kid: secret.keyId, iat: Math.floor(Date.now() / 1000) - 5, // offset the time see caos/zitadel #2704 exp: Math.floor(Date.now() / 1000) + 30 * 60, }; try { var token = jwt.sign(jwtPayload, secret.key, { algorithm: "RS256", header: { kid: secret.keyId }, }); } catch (error) { console.error("error on signin token", error); return Promise.reject(error); } const url = "https://api.zitadel.ch/oauth/v2/token?"; return fetch( url + new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", scope: "openid profile email urn:zitadel:iam:org:project:id:69234237810729019:aud", assertion: token, }), { headers: { "content-type": "application/x-www-form-urlencoded", }, method: "POST", } ) .then((resp) => resp.json()) .catch((error) => { console.error("get token error", error); return Promise.reject(error); }); } export function hasRole( role: string, orgId: string, authHeader: string ): Promise<boolean> { const userInfoEndpoint = "https://api.zitadel.ch/oauth/v2/userinfo"; return fetch(userInfoEndpoint, { headers: { authorization: authHeader, "content-type": "application/json", }, method: "GET", }) .then(handleFetchErrors) .then((resp) => resp.json()) .then((resp) => { const scope = "urn:zitadel:iam:org:project:roles"; const roles = resp[scope]; return roles && roles[role] && roles[role][orgId]; }) .catch(() => { return false; }); }
caos/zitadel-examples
b2b-nextjs/components/Nav.tsx
<filename>b2b-nextjs/components/Nav.tsx import { signIn, useSession } from 'next-auth/react'; import Link from 'next/link'; import { Router, withRouter } from 'next/router'; import React, { Fragment, useEffect, useState } from 'react'; import AuthCheck from './AuthCheck'; import OrgContext from './OrgContext'; import ProfileImage from './ProfileImage'; type Props = { router: any; }; type State = { mobileOpen: boolean; }; class Nav extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { mobileOpen: false, }; Router.events.on("routeChangeComplete", (url) => { this.setState({ mobileOpen: false, }); }); Router.events.on("hashChangeComplete", (url) => { this.setState({ mobileOpen: false, }); }); } triggerMenu() { this.setState({ mobileOpen: !this.state.mobileOpen, }); } componentWillUnmount() { Router.events.off("routeChangeComplete", () => {}); Router.events.off("hashChangeComplete", () => {}); } render() { return ( <nav className="font-normal z-50 transition-all duration-300 ease-in-out fixed top-0 inset-x-0 h-14 bg-lnav dark:bg-dnav shadow-lnav backdrop-nav dark:shadow-dnav"> <div className="h-full max-w-7xl mx-auto flex items-center px-6"> <div className="min-w-40 relative"> <Link href="/"> <a className="h-10 block"> <img height={40} width={147.5} className="navimgd" src="/zitadel-logo-light.svg" alt="ZITADEL logo dark" /> </a> </Link> <span className="text-xl font-bold absolute -bottom-1 -right-6 text-zitadelaccent-500"> B2B </span> </div> <AuthCheck fallback={<div></div>}> <OrgContext /> </AuthCheck> <span className="flex-grow"></span> <ul className="hidden md:flex items-center flex-grow justify-end"> <li className="text-gray-500 dark:text-gray-300 hover:text-black dark:hover:text-white"> <Link href="/"> <a className="flex items-center h-14 relative px-4 text-sm"> Home </a> </Link> </li> <li className="text-gray-500 dark:text-gray-300 hover:text-black dark:hover:text-white"> <a href="https://console.zitadel.ch" target="_blank" rel="noreferrer" className="flex items-center h-14 relative px-4 text-sm" > <span>Console</span> <i className="text-xl h-5 -mt-2 ml-2 las la-external-link-alt"></i> </a> </li> <NavButtons></NavButtons> </ul> <ul className="pt-flex md:hidden"> <li className="text-gray-500 dark:text-gray-200"> <button onClick={() => this.triggerMenu()} className="flex items-center box-border px-4 outline-none focus:outline-none" > <i className="text-lg las la-bars"></i> </button> <div className={`${ this.state.mobileOpen ? "absolute inset-0 top-14 h-screen w-full dark:bg-zitadelblue-700 dark:bg-opacity-80" : "hidden" }`} onClick={() => this.triggerMenu()} ></div> <div className={`${ this.state.mobileOpen ? "absolute top-14 left-0 right-0 bottom-0 flex-col" : "hidden " } `} > <MobileList></MobileList> </div> </li> </ul> </div> </nav> ); } } function NavButtons() { const { data: session, status } = useSession(); function login() { signIn("zitadel" as any, { callbackUrl: "/", }); } if (session) { return <ProfileImage user={session.user} />; } else { return ( <div className="flex items-center justify-center py-2"> <button onClick={login} className="whitespace-nowrap py-2 px-4 mx-2 shadow rounded-md text-sm hidden md:block hover:bg-gray-100 dark:bg-zitadelblue-400 dark:hover:bg-zitadelblue-300 dark:hover:bg-opacity-80 font-normal" > Login </button> </div> ); } } function MobileList() { return ( <div className="overflow-y-scroll max-h-screenmnav m-2 py-2 bg-white dark:bg-zitadelblue-400 shadow-xl dark:text-white rounded-xl relative"> <Link href="/"> <a className="px-4 py-4 flex items-center hover:text-purple-700 dark:hover:text-zitadelaccent-400 justify-center"> Home </a> </Link> <Link href="/aboutus"> <a className="px-4 py-4 flex items-center hover:text-purple-700 dark:hover:text-zitadelaccent-400 justify-center"> About Us </a> </Link> <Link href="/contact"> <a className="px-4 py-4 flex items-center hover:text-purple-700 dark:hover:text-zitadelaccent-400 justify-center"> Contact </a> </Link> <Link href="/jobs"> <a className="px-4 py-4 flex items-center hover:text-purple-700 dark:hover:text-zitadelaccent-400 justify-center"> Jobs </a> </Link> </div> ); } export default withRouter(Nav);
livelybone/owner-window
src/index.ts
export function getOwnerWindow(el: HTMLElement): Window { const doc = el.ownerDocument const id = 'script-for-inject-owner-window' let script = doc.getElementById(id) as HTMLScriptElement | null // @ts-ignore if (!el.ownerWindow && script) { script.id = '' script = null } if (!script) { script = doc.createElement('script') script.type = 'text/javascript' script.id = 'script-for-inject-owner-window' script.innerHTML = 'HTMLElement.prototype.ownerWindow = window;' doc.head.appendChild(script) } // @ts-ignore return el.ownerWindow }
livelybone/owner-window
index.d.ts
<gh_stars>0 declare function getOwnerWindow(el: HTMLElement): Window export { getOwnerWindow }
Photon79/Angular-Full-Stack-Test
client/app/shared/models/index.ts
<reponame>Photon79/Angular-Full-Stack-Test export { Word } from './word.model';
Photon79/Angular-Full-Stack-Test
client/app/pages/testing/testing.component.ts
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { without } from 'lodash/array'; import { Word } from '../../shared/models'; import { DictionaryService, StorageService } from '../../services'; @Component({ selector: 'app-testing', templateUrl: './testing.component.html', styleUrls: ['./testing.component.css'] }) export class TestingComponent { question = 1; public showResult = false; public questions: Array<Word> = []; answer: string = null; current: Word = new Word(); constructor( private dictionary: DictionaryService, private storage: StorageService ) { this.questions = this.storage.load('questions') || []; if (!this.questions.length) { this.getData(); } else { this.showResult = this.storage.load('complete') || false; this.question = this.storage.load('question'); this.current = this.questions[this.question - 1]; } } getData() { this.question = 1; this.dictionary.getWords(true).subscribe(data => { this.questions = data.items.map(word => { const shuffled = without(this.shuffle(data.items), word); word.answers = this.shuffle([ word.translation, ...shuffled.slice(0, 5).map(item => item.translation) ]); return word; }); if (this.questions.length) { this.storage.save({ questions: this.questions, question: this.question }); this.current = this.questions[this.question - 1]; } }); } next() { if (!this.answer) { return; } const answers = this.storage.load('answers') || []; if (this.question <= this.questions.length) { answers.push({ question: this.question, result: this.answer }); this.storage.save({ answers }); this.answer = null; this.question++; if (this.question <= this.questions.length) { this.current = this.questions[this.question - 1]; this.storage.save({ question: this.question }); } } if (this.question > this.questions.length) { this.showResult = true; this.storage.save({ complete: true }); } } getResults() { const answers = this.storage.load('answers'); let correct = 0; answers.forEach(item => { console.log(this.questions[item.question - 1].translation, item.result); if (this.questions[item.question - 1].translation === item.result) { correct++; } }); return { rate: Math.floor(100 / this.questions.length * correct), count: correct }; } clear() { this.storage.clear(); this.getData(); this.showResult = false; } private shuffle(arr) { const shuffled = arr.slice() .map((a) => ({sort: Math.random(), value: a})) .sort((a, b) => a.sort - b.sort) .map((a) => a.value); return shuffled; } }
Photon79/Angular-Full-Stack-Test
server/controllers/base.ts
<reponame>Photon79/Angular-Full-Stack-Test import { Request, Response } from 'express'; export abstract class BaseCtrl { abstract model: any; // Get all getAll = async (req: Request, res: Response) => { try { const docs = await this.model.find({}); return res.status(200).json(docs); } catch (err) { return res.status(500).json({ message: err.message }); } } // Count all count = async (req: Request, res: Response) => { try { const count = await this.model.count({}); return res.status(200).json(count); } catch (err) { return res.status(500).json({ message: err.message }); } } // Insert create = async (req: Request, res: Response) => { try { const obj = new this.model(req.body); const item = await obj.save(); return res.status(200).json(item); } catch (err) { if (err.code === 11000) { return res.status(400).json({ message: err.message }); } return res.status(500).json({ message: err.message }); } } // Get by id read = async (req: Request, res: Response) => { try { const item = await this.model.findOne({ _id: req.params.id }); return res.status(200).json(item); } catch (err) { return res.status(500).json({ message: err.message }); } } // Update by id update = async (req: Request, res: Response) => { try { await this.model.findOneAndUpdate({ _id: req.params.id }, req.body); return res.sendStatus(200); } catch (err) { return res.status(500).json({ message: err.message }); } } // Delete by id delete = async (req: Request, res: Response) => { try { await this.model.findOneAndRemove({ _id: req.params.id }); return res.sendStatus(200); } catch (err) { return res.status(500).json({ message: err.message }); } } }
Photon79/Angular-Full-Stack-Test
server/declarations/promise-bluebird.d.ts
<filename>server/declarations/promise-bluebird.d.ts /// <reference types="mongoose" /> import * as Bluebird from 'bluebird'; declare module 'mongoose' { type Promise<T> = Bluebird<T>; }
Photon79/Angular-Full-Stack-Test
server/models/index.ts
<reponame>Photon79/Angular-Full-Stack-Test<filename>server/models/index.ts export { Word } from './word';
Photon79/Angular-Full-Stack-Test
server/controllers/word.ts
<reponame>Photon79/Angular-Full-Stack-Test import { promisify } from 'bluebird'; import { Request, Response } from 'express'; import { Word } from '../models'; import { BaseCtrl } from './base'; export class WordCtrl extends BaseCtrl { model = Word; getAll = async (req: Request, res: Response) => { try { const { skip, limit, random } = req.query; let total, result; if (random) { result = await this.model.findRandom().limit(20); total = result.length; } else { total = await this.model.count({}); result = await this.model.find({}).limit(limit).skip(skip); } res.json({ total, items: result }); } catch (err) { return res.status(500).json({ message: err.message }); } } }
Photon79/Angular-Full-Stack-Test
client/app/pages/testing/testing.component.spec.ts
<reponame>Photon79/Angular-Full-Stack-Test<filename>client/app/pages/testing/testing.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { ComponentFixtureAutoDetect } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { TestingComponent } from './testing.component'; import { DictionaryService, StorageService } from '../../services'; describe('TestingComponent', () => { let component: TestingComponent; let fixture: ComponentFixture<TestingComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule, FormsModule, ReactiveFormsModule, HttpClientTestingModule ], declarations: [ TestingComponent ], providers: [ { provide: ComponentFixtureAutoDetect, useValue: true }, DictionaryService, StorageService ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TestingComponent); console.log('fixture', fixture); component = fixture.componentInstance; console.log('component', component); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should display the string "Тестирование" in h3', () => { const el = fixture.debugElement.query(By.css('h3')).nativeElement; expect(el.textContent).toContain('Тестирование'); }); it('should display the string "Результаты тестирования" in h3', () => { component.showResult = true; const el = fixture.debugElement.query(By.css('h3')).nativeElement; if (component.questions.length) { expect(el.textContent).toContain('Результаты тестирования'); } else { expect(el.textContent).toContain('Тестирование'); } }); });
Photon79/Angular-Full-Stack-Test
client/app/app.module.ts
<filename>client/app/app.module.ts import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { NgxPaginationModule } from 'ngx-pagination'; import { BsModalModule } from 'ng2-bs3-modal'; import { ModalModule } from 'ngx-modialog'; import { BootstrapModalModule } from 'ngx-modialog/plugins/bootstrap'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClient, HttpClientModule } from '@angular/common/http'; // Modules import { RoutingModule } from './routing.module'; // Pages import { AboutComponent } from './pages/about/about.component'; import { NotFoundComponent } from './pages/not-found/not-found.component'; import { DictionaryComponent } from './pages/dictionary/dictionary.component'; import { TestingComponent } from './pages/testing/testing.component'; // Services import { DictionaryService } from './services'; import { StorageService } from './services/storage.service'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent, AboutComponent, NotFoundComponent, DictionaryComponent, TestingComponent ], imports: [ RoutingModule, NgxPaginationModule, BsModalModule, ModalModule.forRoot(), BootstrapModalModule, BrowserModule, FormsModule, ReactiveFormsModule, HttpClientModule ], providers: [ DictionaryService, StorageService ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ], bootstrap: [ AppComponent ] }) export class AppModule { }
Photon79/Angular-Full-Stack-Test
client/app/shared/models/word.model.ts
export class Word { _id?: string; original?: string; translation?: string; answers?: Array<string>; }
Photon79/Angular-Full-Stack-Test
server/models/word.ts
import { Document, Model, model, Schema } from 'mongoose'; import * as random from 'mongoose-random'; const wordSchema: Schema = new Schema({ original: String, translation: String }); wordSchema.plugin(random, { path: 'r' }); interface IWord extends Document { original: string; translation: string; } interface WordModel extends Model<IWord> { findRandom(); } const Word: WordModel = model<IWord>('Word', wordSchema) as WordModel; export { Word };
Photon79/Angular-Full-Stack-Test
client/app/pages/dictionary/dictionary.component.spec.ts
<filename>client/app/pages/dictionary/dictionary.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NgxPaginationModule } from 'ngx-pagination'; import { BsModalModule } from 'ng2-bs3-modal'; import { ModalModule } from 'ngx-modialog'; import { BootstrapModalModule } from 'ngx-modialog/plugins/bootstrap'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { DictionaryComponent } from './dictionary.component'; import { DictionaryService } from '../../services'; describe('DictionaryComponent', () => { let component: DictionaryComponent; let fixture: ComponentFixture<DictionaryComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ NgxPaginationModule, BsModalModule, ModalModule.forRoot(), BootstrapModalModule, FormsModule, ReactiveFormsModule, RouterTestingModule, HttpClientTestingModule ], declarations: [ DictionaryComponent ], providers: [ DictionaryService ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DictionaryComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should display the string "Словарь" in h3', () => { const el = fixture.debugElement.query(By.css('h3')).nativeElement; expect(el.textContent).toContain('Словарь'); }); });
Photon79/Angular-Full-Stack-Test
client/app/pages/dictionary/dictionary.component.ts
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { BsModalComponent } from 'ng2-bs3-modal'; import { Overlay } from 'ngx-modialog'; import { Modal } from 'ngx-modialog/plugins/bootstrap'; import { DictionaryService } from '../../services'; import { Word } from '../../shared/models'; @Component({ selector: 'app-dictionary', templateUrl: './dictionary.component.html', styleUrls: ['./dictionary.component.css'], encapsulation: ViewEncapsulation.None, }) export class DictionaryComponent implements OnInit { @ViewChild('modal') modal: BsModalComponent; editMode = false; items: Array<Word> = []; selectedWord: Word = new Word(); total: number; page = 1; pageSize = 20; constructor( private route: ActivatedRoute, private router: Router, private dictionary: DictionaryService, private modalService: Modal ) {} ngOnInit() { this.getWords(); } pageChanged(page) { this.page = page; this.getWords(); } add() { this.selectedWord = new Word(); this.editMode = false; this.modal.open(); } edit(item) { this.selectedWord = item; this.editMode = true; this.modal.open(); } delete(word) { const modalRef = this.modalService .confirm() .title('Удаление слова') .body(`Вы уверены, что хотите удалить слово <strong>${word.original}</strong>`) .open(); modalRef.result .then(result => { if (result) { this.dictionary .deleteWord(word) .subscribe(() => { this.getWords(); }); } }) .catch(err => false); } closed() { const func: any = this.editMode ? this.dictionary.editWord.bind(this.dictionary) : this.dictionary.addWord.bind(this.dictionary); func(this.selectedWord).subscribe(() => { this.getWords(); }); } dismissed(type) { if (this.editMode) { this.getWords(); } else { this.selectedWord = new Word(); } } getWords() { this.dictionary .getWords(false, this.page, this.pageSize) .subscribe(data => { this.items = data.items; this.total = data.total; }); } }
Photon79/Angular-Full-Stack-Test
client/app/services/index.ts
<filename>client/app/services/index.ts export { DictionaryService } from './dictionary.service'; export { StorageService } from './storage.service';
Photon79/Angular-Full-Stack-Test
server/controllers/index.ts
export { BaseCtrl } from './base'; export { WordCtrl } from './word';
Photon79/Angular-Full-Stack-Test
server/routes.ts
import * as express from 'express'; import { WordCtrl } from './controllers'; import { Word } from './models'; export default function setRoutes(app) { const router = express.Router(); const wordCtrl = new WordCtrl(); router .route('/words') .get(wordCtrl.getAll) .post(wordCtrl.create); router .route('/words/:id') .put(wordCtrl.update) .delete(wordCtrl.delete); app.use('/api', router); }
Photon79/Angular-Full-Stack-Test
client/app/services/dictionary.service.ts
<filename>client/app/services/dictionary.service.ts import { Injectable, Inject } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { Word } from '../shared/models'; @Injectable() export class DictionaryService { constructor(private http: HttpClient) {} getWords(random: boolean = false, page: number = 1, perPage: number = 10): Observable<{items: Word[], total: number}> { const skip = perPage * (page - 1); const params = new HttpParams() .set('skip', skip.toString()) .set('limit', perPage.toString()) .set('random', random.toString()); return this.http.get<{items: Word[], total: number}>('/api/words', { params }); } addWord(word: Word): Observable<Word> { return this.http.post<Word>('/api/words', word); } editWord(word: Word): Observable<string> { return this.http.put(`/api/words/${word._id}`, word, { responseType: 'text' }); } deleteWord(word: Word): Observable<string> { return this.http.delete(`/api/words/${word._id}`, { responseType: 'text' }); } }
Photon79/Angular-Full-Stack-Test
client/app/services/storage.service.ts
<filename>client/app/services/storage.service.ts import { Injectable } from '@angular/core'; @Injectable() export class StorageService { constructor() { } save(data: any): void { Object.keys(data).forEach(key => localStorage.setItem(`test1-${key}`, JSON.stringify(data[key]))); } load(key: string): any { return JSON.parse(localStorage.getItem(`test1-${key}`)); } delete(key: string): void { localStorage.removeItem(`test1-${key}`); } clear(): void { localStorage.clear(); } }
lkesteloot/z80-asm
src/zasm/Main.ts
<gh_stars>0 import * as fs from "fs"; import chalk from "chalk"; import {toHex} from "z80-base"; import {Asm} from "../assembler/Asm"; const srcPathname = "sio_basic.asm"; const lstPathname = "sio_basic.lst"; const binPathname = "sio_basic.bin"; function loadFile(filename: string): string[] { return fs.readFileSync(filename, "utf-8").split(/\r?\n/); } function main() { const lstFd = fs.openSync(lstPathname, "w"); const binFd = fs.openSync(binPathname, "w"); const asm = new Asm(loadFile); const sourceFile = asm.assembleFile(srcPathname); if (sourceFile === undefined) { console.log("Cannot read file " + srcPathname); return; } const assembledLines = sourceFile.assembledLines; let errorCount = 0; for (const results of assembledLines) { if (results.binary.length !== 0) { // Show four bytes at a time. let displayAddress = results.address; for (let i = 0; i < results.binary.length; i += 4) { let result = toHex(displayAddress, 4) + ":"; for (let j = 0; j < 4 && i + j < results.binary.length; j++) { result += " " + toHex(results.binary[i + j], 2); displayAddress++; } if (i === 0) { result = result.padEnd(24, " ") + results.line; } fs.writeSync(lstFd, result + "\n"); } fs.writeSync(binFd, new Uint8Array(results.binary)); } else { fs.writeSync(lstFd, " ".repeat(24) + results.line + "\n"); } if (results.error !== undefined) { fs.writeSync(lstFd, "error: " + results.error + "\n"); } if (results.error !== undefined) { console.log(chalk.gray(results.line)); console.log(chalk.red("error: " + results.error)); console.log(); errorCount += 1; } } if (errorCount !== 0) { console.log(errorCount + " errors"); } fs.closeSync(lstFd); fs.closeSync(binFd); } main();
lkesteloot/z80-asm
src/main/electron-main.ts
import {app, BrowserWindow, dialog, ipcMain, IpcMainEvent, Menu, TouchBar} from 'electron'; const { TouchBarButton } = TouchBar; function createWindow(): BrowserWindow { // Create the browser window. const win = new BrowserWindow({ width: 1200, height: 800, webPreferences: { preload: `${__dirname}/electron-preload.js`, nodeIntegration: true } }); // and load the index.html of the app. win.loadFile('index.html'); // Open the DevTools. /// win.webContents.openDevTools() return win; } // Default value for future Electron versions. Setting this avoids a warning. app.allowRendererProcessReuse = true; // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { const win = createWindow(); setupMenus(); setupTouchBar(win); setupMessageListeners(); }); // Quit when all windows are closed. app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }); app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }); function openFile(win: BrowserWindow | null, pathname: string) { if (!win) { win = BrowserWindow.getFocusedWindow(); } if (!win) { return; } win.webContents.send("set-pathname", pathname); app.addRecentDocument(pathname); } app.on('open-file', (event, pathname) => { event.preventDefault(); openFile(null, pathname); }); const isMac = process.platform === 'darwin'; const template = [ ...(isMac ? [{ label: app.name, submenu: [ { role: 'about' }, { type: 'separator' }, { role: 'services' }, { type: 'separator' }, { role: 'hide' }, { role: 'hideothers' }, { role: 'unhide' }, { type: 'separator' }, { role: 'quit' } ] }] : []), { label: 'File', submenu: [ { label: "New", click: (event: any, focusedWindow: BrowserWindow, focusedWebContents: any) => { focusedWindow.webContents.send("set-pathname", ""); }, accelerator: "CmdOrCtrl+N", registerAccelerator: true, }, { label: 'Open', click: (event: any, focusedWindow: BrowserWindow, focusedWebContents: any) => { dialog.showOpenDialog(focusedWindow, { defaultPath: "/Users/lk/mine/ZED-80/src/zed-80", filters: [ { name: 'Assembly', extensions: ['asm', 'inc', 's'] }, { name: 'All Files', extensions: ['*'] } ], properties: [ 'openFile', // Can open individual files. ] }).then(result => { if (result.filePaths.length > 0) { openFile(focusedWindow, result.filePaths[0]); } }).catch(err => { console.log(err) }); }, accelerator: "CmdOrCtrl+O", registerAccelerator: true, }, // Doesn't seem to work: // { role: 'recentDocuments' }, { label: "Save", click: (event: any, focusedWindow: BrowserWindow, focusedWebContents: any) => { focusedWindow.webContents.send("save"); }, accelerator: "CmdOrCtrl+S", }, isMac ? { role: 'close' } : { role: 'quit' } ] }, { label: 'Edit', submenu: [ { role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, ...(isMac ? [ { role: 'pasteAndMatchStyle' }, { role: 'delete' }, { role: 'selectAll' }, { type: 'separator' }, { label: 'Speech', submenu: [ { role: 'startspeaking' }, { role: 'stopspeaking' } ] } ] : [ { role: 'delete' }, { type: 'separator' }, { role: 'selectAll' } ]) ] }, { label: 'View', submenu: [ { role: 'reload' }, { role: 'forcereload' }, { role: 'toggledevtools' }, { type: 'separator' }, { role: 'resetzoom' }, { role: 'zoomin' }, { role: 'zoomout' }, { type: 'separator' }, { role: 'togglefullscreen' } ] }, { label: "Navigate", submenu: [ { label: "Declaration or Usages", accelerator: "CmdOrCtrl+B", registerAccelerator: true, click: (event: any, focusedWindow: BrowserWindow, focusedWebContents: any) => { focusedWindow.webContents.send("declaration-or-usages"); }, }, { label: "Next Declaration or Usage", accelerator: "Shift+CmdOrCtrl+B", registerAccelerator: true, click: (event: any, focusedWindow: BrowserWindow, focusedWebContents: any) => { focusedWindow.webContents.send("next-usage"); }, }, { type: 'separator' }, { label: "Next Error", accelerator: "F2", registerAccelerator: true, click: (event: any, focusedWindow: BrowserWindow, focusedWebContents: any) => { focusedWindow.webContents.send("next-error"); }, }, ], }, { label: "Code", submenu: [ { label: "Fold All", accelerator: "Shift+CmdOrCtrl+-", registerAccelerator: true, click: (event: any, focusedWindow: BrowserWindow, focusedWebContents: any) => { focusedWindow.webContents.send("fold-all"); }, }, { label: "Unfold All", accelerator: "Shift+CmdOrCtrl+Plus", registerAccelerator: true, click: (event: any, focusedWindow: BrowserWindow, focusedWebContents: any) => { focusedWindow.webContents.send("unfold-all"); }, }, ], }, { label: 'Window', submenu: [ { role: 'minimize' }, { role: 'zoom' }, ...(isMac ? [ { type: 'separator' }, { role: 'front' }, { type: 'separator' }, { role: 'window' } ] : [ { role: 'close' } ]) ] }, { role: 'help', submenu: [ { label: 'Learn More', click: async () => { const { shell } = require('electron'); await shell.openExternal('https://electronjs.org'); } } ] } ]; function setupMenus() { const menu = Menu.buildFromTemplate(template as any); Menu.setApplicationMenu(menu) } function setupTouchBar(win: BrowserWindow) { const nextErrorButton = new TouchBarButton({ label: 'Next Error', click: () => { win.webContents.send("next-error"); }, }); const touchBar = new TouchBar({ items: [ nextErrorButton, ], }); win.setTouchBar(touchBar); } function setupMessageListeners() { ipcMain.on("ask-for-filename", () => { const win = BrowserWindow.getFocusedWindow(); if (!win) { return; } dialog.showSaveDialog(win, { defaultPath: "/Users/lk/mine/ZED-80/src/zed-80", filters: [ { name: 'Assembly', extensions: ['asm', 'inc', 's'] }, { name: 'All Files', extensions: ['*'] } ], properties: [ "createDirectory", // Allow creation of directory. "showOverwriteConfirmation" ] }).then(result => { win.webContents.send("asked-for-filename", result.filePath); }).catch(err => { console.log(err); win.webContents.send("asked-for-filename", undefined); }); }); ipcMain.on("set-window-title", (event: IpcMainEvent, title: string) => { const win = BrowserWindow.getFocusedWindow(); if (!win) { return; } win.setTitle(title); }); }
lkesteloot/z80-asm
src/ide/Ide.ts
import CodeMirror from "codemirror"; import {Asm, AssembledLine, FileInfo, SymbolInfo, SymbolReference} from "../assembler/Asm"; import mnemonicData from "../assembler/Opcodes"; import {toHexByte, toHexWord} from "z80-base"; import tippy from 'tippy.js'; import 'tippy.js/dist/tippy.css'; import "codemirror/lib/codemirror.css"; import "codemirror/theme/mbo.css"; import "codemirror/addon/dialog/dialog.css"; import "codemirror/addon/hint/show-hint.css"; import "codemirror/addon/fold/foldgutter.css"; import "./main.css"; // Load these for their side-effects (they register themselves). import "codemirror/addon/dialog/dialog"; import "codemirror/addon/search/search"; import "codemirror/addon/search/jump-to-line"; import "codemirror/addon/edit/closebrackets"; import "codemirror/addon/hint/show-hint"; import "codemirror/addon/scroll/annotatescrollbar"; import "codemirror/addon/selection/active-line"; import "codemirror/addon/selection/mark-selection"; import "codemirror/addon/fold/foldcode"; import "codemirror/addon/fold/foldgutter"; import "codemirror/mode/z80/z80"; import * as fs from "fs"; import Store from "electron-store"; import {ClrInstruction, OpcodeTemplate, Variant} from "../assembler/OpcodesTypes"; // Max number of sub-lines per line. These are lines where we display the // opcodes for a single source line. const MAX_SUBLINES = 100; // Max number of opcode bytes we display per subline. Sync this with the CSS // that lays out the gutter. const BYTES_PER_SUBLINE = 3; const CURRENT_PATHNAME_KEY = "current-pathname"; // Convenience for the result of a range finder function (for folding). type RangeFinderResult = {from: CodeMirror.Position, to: CodeMirror.Position} | undefined; // Result of looking up what symbol we're on. class SymbolHit { public readonly symbol: SymbolInfo; public readonly isDefinition: boolean; public readonly referenceNumber: number; constructor(symbol: SymbolInfo, isDefinition: boolean, reference: number) { this.symbol = symbol; this.isDefinition = isDefinition; this.referenceNumber = reference; } } // In-memory cache of the disk file. class SourceFile { public readonly pathname: string; public readonly lines: string[]; public modified = false; constructor(pathname: string, lines: string[]) { this.pathname = pathname; this.lines = lines; } public setLines(lines: string[]): void { console.log("Pushing " + lines.length + " lines to " + this.pathname); // See if they've changed. let changed = this.lines.length !== lines.length; if (!changed) { const length = lines.length; for (let i = 0; i < length; i++) { if (this.lines[i] !== lines[i]) { changed = true; break; } } } if (changed) { console.log("Was modified"); this.lines.splice(0, this.lines.length, ...lines); this.modified = true; } } } // Read a file raw text, or undefined if the file can't be opened. function readFile(pathname: string): string | undefined { try { return fs.readFileSync(pathname, "utf-8"); } catch (e) { console.log("readFile(" + pathname + "): " + e); return undefined; } } // Read a file as an array of lines, or undefined if the file can't be opened. function readFileLines(pathname: string): string[] | undefined { let text = readFile(pathname); if (text === undefined) { return undefined; } // Remove trailing newline, since we treat newlines as separators, not terminators. // This means that a partial line at the end of a file is treated like a full line. // TODO handle CR/NL too. if (text.endsWith("\n")) { text = text.substr(0, text.length - 1); } return text.split(/\r?\n/); } /** * Whether "prefix" is a prefix of "opcode". I.e., the opcode array starts with prefix. */ function isPrefix(prefix: OpcodeTemplate[], opcode: OpcodeTemplate[]): boolean { if (prefix.length > opcode.length) { return false; } for (let i = 0; i < prefix.length; i++) { if (prefix[i] !== opcode[i]) { return false; } } return true; } class Ide { private store: Store; private readonly cm: CodeMirror.Editor; // The index of this array is the line number in the file (zero-based). private assembledLines: AssembledLine[] = []; private pathname: string = ""; private ipcRenderer: any; private scrollbarAnnotator: any; private sourceFiles = new Map<string,SourceFile>(); private readonly symbolMarks: CodeMirror.TextMarker[] = []; private readonly lineWidgets: CodeMirror.LineWidget[] = []; private fileInfo: FileInfo | undefined; constructor(parent: HTMLElement) { this.store = new Store({ name: "z80-ide", }); const config = { value: "", lineNumbers: true, tabSize: 8, theme: 'mbo', gutters: ["CodeMirror-linenumbers", "gutter-assembled", "CodeMirror-foldgutter"], autoCloseBrackets: true, mode: "text/x-z80", // Doesn't work, I call focus() explicitly later. autoFocus: true, extraKeys: (CodeMirror as any).normalizeKeyMap({ // "Ctrl-Space": "autocomplete" "Cmd-B": () => this.jumpToDefinition(false), "Shift-Cmd-B": () => this.jumpToDefinition(true), }), hintOptions: { hint: () => this.hint(), }, styleActiveLine: true, styleSelectedText: true, cursorScrollMargin: 200, foldGutter: true, foldOptions: { rangeFinder: (cm: CodeMirror.Editor, start: CodeMirror.Position) => this.rangeFinder(start), widget: (from: CodeMirror.Position, to: CodeMirror.Position) => { const count = to.line - from.line; return `\u21A4 ${count} \u21A6`; }, }, }; this.cm = CodeMirror(parent, config); // Create CSS classes for our line heights. We do this dynamically since // we don't know the line height at compile time. const cssRules = []; for (let lineCount = 1; lineCount < MAX_SUBLINES; lineCount++) { cssRules.push(".line-height-" + lineCount + " { height: " + lineCount * this.cm.defaultTextHeight() + "px; }"); } const style = document.createElement("style"); style.appendChild(document.createTextNode(cssRules.join("\n"))); document.head.appendChild(style); this.cm.on("change", (instance, changeObj) => { // It's important to call this in "change", and not in "changes" or // after a timeout, because we want to be part of this operation. // This way a large re-assemble takes 40ms instead of 300ms. // We should be entirely within a file (otherwise we would have gotten // canceled in the "beforeChange" event). Find which file we're in // and update it all. if (changeObj.origin !== "setValue") { console.log(changeObj); const removed = changeObj.removed ?? []; const linesAdded = changeObj.text.length - removed.length; this.editorToCache(changeObj.from.line, linesAdded); this.assembleAll(); } }); this.cm.on("beforeChange", (instance, changeObj) => { if (changeObj.origin === "setValue") { // Always allow setValue(). return; } console.log("beforeChange \"" + changeObj.origin + "\""); const beginLine = changeObj.from.line; const endLine = changeObj.to.ch === 0 ? changeObj.to.line : changeObj.to.line + 1; if (this.fileInfo !== undefined) { const spansFileInfo = (fileInfo: FileInfo): boolean => { if ((beginLine < fileInfo.beginLineNumber && endLine > fileInfo.beginLineNumber) || (beginLine < fileInfo.endLineNumber && endLine > fileInfo.endLineNumber)) { return true; } for (const fi of fileInfo.childFiles) { if (spansFileInfo(fi)) { return true; } } return false; }; const spanFile = spansFileInfo(this.fileInfo); if (spanFile) { console.log("Canceling update"); changeObj.cancel(); } } }); this.cm.on("cursorActivity", (instance) => { this.updateHighlight(); }); this.cm.on("blur", () => this.saveSilently()); // The type definition doesn't include this extension. this.scrollbarAnnotator = (this.cm as any).annotateScrollbar("scrollbar-error"); // Configure IPC with the main process of Electron. this.ipcRenderer = (window as any).ipcRenderer; this.ipcRenderer.on("set-pathname", (event: any, pathname: string) => this.setPathnameAndLoad(pathname)); this.ipcRenderer.on("next-error", () => this.nextError()); this.ipcRenderer.on("declaration-or-usages", () => this.jumpToDefinition(false)); this.ipcRenderer.on("next-usage", () => this.jumpToDefinition(true)); this.ipcRenderer.on("save", () => this.saveOrAskPathname()); this.ipcRenderer.on("asked-for-filename", (event: any, pathname: string | undefined) => this.userSpecifiedPathname(pathname)); this.ipcRenderer.on("fold-all", () => this.cm.execCommand("foldAll")); this.ipcRenderer.on("unfold-all", () => this.cm.execCommand("unfoldAll")); this.cm.focus(); // Read file from last time. const pathname = this.store.get(CURRENT_PATHNAME_KEY); if (pathname !== undefined) { this.pathname = pathname; this.ipcRenderer.send("set-window-title", pathname); this.assembleAll(); this.cm.execCommand("foldAll") } } // Set pathname when we want to load that existing file from disk. private setPathnameAndLoad(pathname: string): void { this.setPathname(pathname); this.assembleAll(); this.cm.execCommand("foldAll") this.cm.clearHistory(); } // Set the pathname of a previously-new document. private setPathname(pathname: string) { this.pathname = pathname; this.ipcRenderer.send("set-window-title", pathname === "" ? "New File" : pathname); if (pathname !== "") { this.store.set(CURRENT_PATHNAME_KEY, pathname); } } // Save if possible, else do nothing. This is for implicit saving like when the editor // loses focus. private saveSilently(): void { if (this.pathname !== "") { this.saveFile(); } } // User-initiated save. private saveOrAskPathname(): void { if (this.pathname === "") { this.ipcRenderer.send("ask-for-filename"); // Continues in "asked-for-filename". } else { this.saveFile(); } } private userSpecifiedPathname(pathname: string | undefined): void { if (pathname === undefined) { // Ignore. } else { this.setPathname(pathname); this.saveFile(); } } // Save the file to disk. private saveFile(): void { /* fs.writeFile(this.pathname, this.cm.getValue(), () => { // TODO mark file clean. }); */ } // Given a starting line, see if it starts a section that could be folded. private rangeFinder(start: CodeMirror.Position): RangeFinderResult { const checkFileInfo = (fi: FileInfo | undefined, depth: number): RangeFinderResult => { if (fi !== undefined) { // Prefer children, do those first. for (const child of fi.childFiles) { const range = checkFileInfo(child, depth + 1); if (range !== undefined) { return range; } } // Assume that whatever is being folded, it's the result of an #include statement // on the previous line. Don't need to fold entire top-level file. if (fi.beginLineNumber - 1 === start.line && depth > 0) { const firstLineNumber = start.line; const firstLine = this.cm.getLine(firstLineNumber); const lastLineNumber = fi.endLineNumber - 1; const lastLine = this.cm.getLine(lastLineNumber); if (firstLine !== undefined && lastLine !== undefined) { return { from: CodeMirror.Pos(firstLineNumber, firstLine.length), to: CodeMirror.Pos(lastLineNumber, lastLine.length), }; } } } return undefined; }; return checkFileInfo(this.fileInfo, 0); } private nextError(): void { if (this.assembledLines.length === 0) { return; } const currentLineNumber = this.cm.getCursor().line; let nextErrorLineNumber = currentLineNumber; do { nextErrorLineNumber = (nextErrorLineNumber + 1) % this.assembledLines.length; } while (nextErrorLineNumber !== currentLineNumber && this.assembledLines[nextErrorLineNumber].error === undefined); if (nextErrorLineNumber !== currentLineNumber) { // TODO error might not be in this file: this.setCursor(nextErrorLineNumber, 0); } } private setCursorToReference(ref: SymbolReference): void { this.setCursor(ref.lineNumber, ref.column); } // Set the editor's cursor if it's for this file. private setCursor(lineNumber: number, column: number): void { this.cm.setCursor(lineNumber, column); } // Find symbol usage at a location, or undefined if we're not on a symbol. private findSymbolAt(lineNumber: number, column: number): SymbolHit | undefined { const assembledLine = this.assembledLines[lineNumber]; for (const symbol of assembledLine.symbols) { // See if we're at a definition. for (let i = 0; i < symbol.definitions.length; i++) { if (symbol.matches(symbol.definitions[i], lineNumber, column)) { return new SymbolHit(symbol, true, i); } } // See if we're at a use. for (let i = 0; i < symbol.references.length; i++) { if (symbol.matches(symbol.references[i], lineNumber, column)) { return new SymbolHit(symbol, false, i); } } } return undefined; } // Jump from a use to its definition and vice versa. // // @param nextUse whether to cycle uses/definitions (true) or switch between use and definition (false). private jumpToDefinition(nextUse: boolean) { const pos = this.cm.getCursor(); const symbolHit = this.findSymbolAt(pos.line, pos.ch); if (symbolHit !== undefined) { const symbol = symbolHit.symbol; if (symbolHit.isDefinition) { if (nextUse) { const reference = symbol.definitions[(symbolHit.referenceNumber + 1) % symbol.definitions.length]; this.setCursorToReference(reference); } else if (symbol.references.length > 0) { this.setCursorToReference(symbol.references[0]); } else { // TODO: Display error. } } else { if (nextUse) { const reference = symbol.references[(symbolHit.referenceNumber + 1) % symbol.references.length]; this.setCursorToReference(reference); } else if (symbol.definitions.length > 0) { this.setCursorToReference(symbol.definitions[0]); } else { // TODO: Display error. } } } } // Delete all line widgets. private clearLineWidgets(): void { let lineWidget; while ((lineWidget = this.lineWidgets.pop()) !== undefined) { lineWidget.clear(); } } private clearSymbolMarks(): void { let mark; while ((mark = this.symbolMarks.pop()) !== undefined) { mark.clear(); } } private updateHighlight() { this.clearSymbolMarks(); const pos = this.cm.getCursor(); const symbolHit = this.findSymbolAt(pos.line, pos.ch); if (symbolHit !== undefined) { const symbol = symbolHit.symbol; // Highlight definitions. for (const reference of symbol.definitions) { const mark = this.cm.markText({line: reference.lineNumber, ch: reference.column}, {line: reference.lineNumber, ch: reference.column + symbol.name.length}, { className: "current-symbol", }); this.symbolMarks.push(mark); } // Highlight references. for (const reference of symbol.references) { const mark = this.cm.markText({line: reference.lineNumber, ch: reference.column}, {line: reference.lineNumber, ch: reference.column + symbol.name.length}, { className: "current-symbol", }); this.symbolMarks.push(mark); } } } // Push the lines in the editor back to the file cache. private editorToCache(beginLineNumber: number, linesAdded: number): void { if (this.fileInfo === undefined) { // Haven't assembled yet. return; } // The line we're on. const assembledLine = this.assembledLines[beginLineNumber]; // Find the file we're in. const fileInfo = assembledLine.fileInfo; const sourceFile = this.sourceFiles.get(fileInfo.pathname); if (sourceFile === undefined) { throw new Error("Can't find source file for " + fileInfo.pathname); } let lineNumbers = Array.from(fileInfo.lineNumbers); if (linesAdded > 0) { const index = lineNumbers.indexOf(beginLineNumber); if (index === -1) { throw new Error("Can't find line number " + beginLineNumber + " in array of lines"); } for (let i = 0; i < linesAdded; i++) { lineNumbers.splice(index + 1 + i, 0, beginLineNumber + i + 1); } console.log(lineNumbers); for (let i = index + linesAdded + 1; i < lineNumbers.length; i++) { lineNumbers[i] += linesAdded; } console.log(lineNumbers); } else if (linesAdded < 0) { const linesRemoved = -linesAdded; console.log(lineNumbers); const index = lineNumbers.indexOf(beginLineNumber); if (index === -1) { throw new Error("Can't find line number " + beginLineNumber + " in array of lines"); } lineNumbers.splice(index + 1, linesRemoved); console.log(lineNumbers); for (let i = index + 1; i < lineNumbers.length; i++) { lineNumbers[i] -= linesRemoved; } console.log(lineNumbers); } const newLines: string[] = []; for (const lineNumber of lineNumbers) { // Skip synthetic lines. const lineInfo = this.cm.lineInfo(lineNumber); const isSynthetic = lineInfo.textClass === undefined ? false : lineInfo.textClass.split(" ").indexOf("synthetic-line") >= 0; if (!isSynthetic) { const text = this.cm.getLine(lineNumber); newLines.push(text); } } sourceFile.setLines(newLines); } // Get the lines from the file cache, reading from disk if necessary. private getFileLines(pathname: string): string[] | undefined { // Check the cache. let sourceFile = this.sourceFiles.get(pathname); if (sourceFile === undefined) { const lines = pathname === "" ? [""] : readFileLines(pathname); if (lines === undefined) { // Don't cache the failure, just try again next time. return undefined; } sourceFile = new SourceFile(pathname, lines); this.sourceFiles.set(pathname, sourceFile); } return sourceFile.lines; } private assembleAll() { this.clearLineWidgets(); const before = Date.now(); const asm = new Asm((pathname) => this.getFileLines(pathname)); const sourceFile = asm.assembleFile(this.pathname); if (sourceFile === undefined) { // TODO deal with file not existing. return; } this.assembledLines = sourceFile.assembledLines; this.fileInfo = sourceFile.fileInfo; // Compute new text for editor. const lines: string[] = []; for (const assembledLine of this.assembledLines) { lines.push(assembledLine.line); } let newValue = lines.join("\n"); if (newValue !== this.cm.getValue()) { const cursor = this.cm.getCursor(); this.cm.setValue(newValue); this.cm.setCursor(cursor); } const before1 = Date.now(); // Update text markers. for (let lineNumber = 0; lineNumber < this.assembledLines.length; lineNumber++) { const assembledLine = this.assembledLines[lineNumber]; const depth = assembledLine.fileInfo.depth; if (depth > 0) { this.cm.addLineClass(lineNumber, "background", "include-" + depth); } } console.log("Updating include line markers: " + (Date.now() - before1)); // Update UI. const before2 = Date.now(); const annotationMarks: any[] = []; for (let lineNumber = 0; lineNumber < this.assembledLines.length; lineNumber++) { const assembledLine = this.assembledLines[lineNumber]; // Update gutter. let addressElement: HTMLElement | null; if (assembledLine.binary.length > 0) { addressElement = document.createElement("div"); // Break opcodes over multiple lines if necessary. let numLines = 0; for (let offset = 0; offset < assembledLine.binary.length && numLines < MAX_SUBLINES; offset += BYTES_PER_SUBLINE, numLines++) { const addressString = toHexWord(assembledLine.address + offset) + " " + assembledLine.binary.slice(offset, offset + BYTES_PER_SUBLINE).map(toHexByte).join(" "); const addressTextElement = document.createTextNode(addressString); if (offset > 0) { addressElement.appendChild(document.createElement("br")); } addressElement.appendChild(addressTextElement); } addressElement.classList.add("gutter-style"); // For the line height using CSS. this.cm.removeLineClass(lineNumber, "wrap", undefined); if (numLines !== 1) { this.cm.addLineClass(lineNumber, "wrap", "line-height-" + numLines); } if (assembledLine.variant !== undefined) { let popup = assembledLine.variant.clr !== null ? this.getPopupForClr(assembledLine.variant.clr) : this.getPopupForPseudoInstruction(assembledLine.variant); if (popup !== undefined) { addressElement.addEventListener("mouseenter", () => { if (addressElement !== null && (addressElement as any)._tippy === undefined) { const instance = tippy(addressElement, { content: popup, allowHTML: true, }); instance.show(); } }); } } } else { addressElement = null; } this.cm.setGutterMarker(lineNumber, "gutter-assembled", addressElement); // Update errors. if (assembledLine.error === undefined) { this.cm.removeLineClass(lineNumber, "background", "error-line"); } else { this.cm.addLineClass(lineNumber, "background", "error-line"); // Highlight error in scrollbar. annotationMarks.push({ from: { line: lineNumber, ch: 0 }, to: { line: lineNumber + 1, ch: 0 }, }); // Write error below line. const node = document.createElement("span"); node.appendChild(document.createTextNode(assembledLine.error)); this.lineWidgets.push(this.cm.addLineWidget(lineNumber, node, { className: "error-line", })); } // Handle synthetic lines. if (assembledLine.lineNumber === undefined) { this.cm.addLineClass(lineNumber, "text", "synthetic-line"); // I don't know if we need to remember these marks and delete them ourselves, or // if the setValue() call will do it. this.cm.markText({line: lineNumber, ch: 0}, {line: lineNumber + 1, ch: 0}, { inclusiveLeft: false, inclusiveRight: false, // These are not in the type definition. Not sure if we need them. // selectLeft: false, // selectRight: true, atomic: true, collapsed: false, clearOnEnter: false, css: "color: #666", }); } } console.log("Updating gutters and line widgets: " + (Date.now() - before2)); const before3 = Date.now(); this.scrollbarAnnotator.update(annotationMarks); console.log("Updating scrollbar annotations: " + (Date.now() - before3)); console.log("Total assembly time: " + (Date.now() - before)); } private hint(): any { // TODO remove. const cursor = this.cm.getCursor(); const line = this.cm.getLine(cursor.line); const start = cursor.ch; const end = cursor.ch; return { list: ["aaaaa", "bbbbb", "ccccc"], from: CodeMirror.Pos(cursor.line, start - 3), to: CodeMirror.Pos(cursor.line, start), }; } /** * Generate a popup for an instruction that has clr info. */ private getPopupForClr(clr: ClrInstruction): string { let popup = "<b>" + clr.instruction.toUpperCase() + "</b><br><br>"; if (clr.description) { popup += clr.description + "<br><br>"; } popup += clr.byte_count + " bytes, "; if (clr.with_jump_clock_count === clr.without_jump_clock_count) { popup += clr.with_jump_clock_count + " clocks.<br><br>"; } else { popup += clr.with_jump_clock_count + "/" + clr.without_jump_clock_count + " clocks.<br><br>"; } if (clr.flags === "------") { popup += "Flags are unaffected.</br>"; } else { const flagLabels = ['C', 'N', 'P/V', 'H', 'Z', 'S']; for (let i = 0; i < 6; i++) { popup += "<b>" + flagLabels[i] + ":</b> "; switch (clr.flags.charAt(i)) { case '-': popup += 'unaffected'; break; case '+': popup += 'affected as defined'; break; case 'P': popup += 'detects parity'; break; case 'V': popup += 'detects overflow'; break; case '1': popup += 'set'; break; case '0': popup += 'reset'; break; case '*': popup += 'exceptional'; break; default: popup += 'unknown'; break; } popup += "<br>"; } } if (clr.undocumented) { popup += "<br>Undocumented instructions.<br>"; } return popup; } /** * Generate popup for a pseudo instruction (composite of multiple instructions), * or undefined if we can't find which instructions it's made of. */ private getPopupForPseudoInstruction(variant: Variant): string | undefined { if (variant.opcode.length === 0) { return undefined; } let popup = "<b>Pseudo Instruction</b><br><br>"; // If this happens a lot we should make a reverse map. let start = 0; while (start < variant.opcode.length) { const subVariant = this.getVariantForOpcode(variant.opcode.slice(start)); if (subVariant === undefined) { return undefined; } if (subVariant.clr === null) { popup += "Unknown instruction<br>"; } else { popup += subVariant.clr.instruction.toUpperCase() + "<br>"; } start += subVariant.opcode.length; } return popup; } /** * Find the variant for whatever instruction is at the head of the sequence of opcodes, * or undefined if it can't be found. Never returns pseudo-instructions. */ private getVariantForOpcode(opcode: OpcodeTemplate[]): Variant | undefined { for (const mnemonic of Object.keys(mnemonicData.mnemonics)) { for (const variant of mnemonicData.mnemonics[mnemonic].variants) { if (variant.clr !== null && isPrefix(variant.opcode, opcode)) { return variant; } } } return undefined; } } function main() { const element = document.getElementById("editor") as HTMLElement; new Ide(element); } main();
lkesteloot/z80-asm
src/assembler/Asm.spec.ts
import { expect } from "chai"; import "mocha"; import {Asm, SourceFile} from "./Asm"; interface TestLine { line: string; opcodes?: number[]; error?: boolean; } function runTest(testLines: TestLine[]): Asm { const asm = new Asm((pathname) => testLines.map(testLine => testLine.line)); const sourceFile = asm.assembleFile("unused.asm"); if (sourceFile === undefined) { throw new Error("File not found"); } const assembledLines = sourceFile.assembledLines; expect(assembledLines.length).to.be.equal(testLines.length); for (let i = 0; i < testLines.length; i++) { expect(assembledLines[i].binary).to.deep.equal(testLines[i].opcodes ?? []); if (testLines[i].error) { expect(assembledLines[i].error).to.not.be.undefined; } else { expect(assembledLines[i].error).to.be.undefined; } } return asm; } describe("assemble", () => { it("nop", () => { runTest([ { line: " nop", opcodes: [0] }, ]); }); it("label", () => { const asm = runTest([ { line: " .org 5" }, { line: "main" }, ]); expect(asm.scopes[0].get("main")?.value).to.equal(5); }); it("label w/colon", () => { const asm = runTest([ { line: " .org 5" }, { line: "main:" }, ]); expect(asm.scopes[0].get("main")?.value).to.equal(5); }); // Mnemonics are allowed as labels. it("nop (as label)", () => { const asm = runTest([ { line: " .org 5" }, { line: "nop" }, ]); expect(asm.scopes[0].get("nop")?.value).to.equal(5); }); it("label w/inst", () => { const asm = runTest([ { line: " .org 5" }, { line: "main nop", opcodes: [0] }, ]); expect(asm.scopes[0].get("main")?.value).to.equal(5); }); it("ld a,c", () => { runTest([ { line: " ld a,c", opcodes: [0x79] }, ]); }); it("ld a,c w/spaces", () => { runTest([ { line: " ld a , c ", opcodes: [0x79] }, ]); }); it("ddcb param", () => { runTest([ { line: " rlc (ix+0x56)", opcodes: [0xDD, 0xCB, 0x56, 0x06] }, ]); }); it("bad mnemonic", () => { runTest([ { line: " foo", error: true }, ]); }); it("present identifier", () => { runTest([ { line: "foo .equ 6" }, { line: " ld a,foo", opcodes: [0x3E, 0x06] }, ]); }); it("missing identifier", () => { runTest([ { line: " ld a,main", opcodes: [0x3E, 0x00], error: true }, ]); }); it("#code without address", () => { runTest([ { line: "#code FOO" }, { line: " jp $", opcodes: [0xC3, 0x00, 0x00] }, ]); }); it("#code with address", () => { runTest([ { line: "#code FOO, 0x4000" }, { line: " jp $", opcodes: [0xC3, 0x00, 0x40] }, ]); }); }); describe("number parsing", () => { const tests = [ // Decimal. [ '0', 0 ], [ '00', 0 ], [ '5', 5 ], [ '123', 123 ], [ '0123', 123 ], // Hex. [ '$AB', 0xAB ], [ '0xAB', 0xAB ], // Looks like B suffix. [ '0ABH', 0xAB ], [ '0B1H', 0xB1 ], // Looks like 0x start. // Binary. [ '%1010', 0b1010 ], [ '0b1010', 0b1010 ], [ '1010B', 0b1010 ], // Current address. [ '$', 0x1234 ], [ '$+1', 0x1235 ], [ '$-1', 0x1233 ], // Negative numbers. [ '-5', -5 ], [ '-0xAB', -0xAB ], [ '-0b1010', -0b1010 ], [ '-0ABH', -0xAB ], [ '-1010B', -0b1010 ], [ '-$AB', -0xAB ], [ '-%1010', -0b1010 ], [ '-$', -0x1234 ], // Operators. [ '2 << 3', 16 ], [ '16 >> 3', 2 ], ]; for (const test of tests) { const input = test[0]; const expected = test[1]; it("parsing " + input, () => { const line = "foo .equ " + input; const asm = runTest([ { line: " .org 0x1234" }, { line: line }, ]); expect(asm.scopes[0].get("foo")?.value).to.be.equal(expected); }); } }); function runMacroTest(testLines: string[], expectedOpcodes: number[]): void { const asm = new Asm((pathname) => testLines); const sourceFile = asm.assembleFile("unused.asm"); if (sourceFile === undefined) { throw new Error("File not found"); } const opcodes: number[] = []; for (const assembledLine of sourceFile.assembledLines) { opcodes.splice(opcodes.length, 0, ... assembledLine.binary); } expect(opcodes).to.deep.equal(expectedOpcodes); } describe("assemble", () => { it("macro label first", () => { runMacroTest([ "foo macro", " nop", " endm", " foo", " foo", ], [0, 0]); }); it("macro label last", () => { runMacroTest([ " macro foo", " nop", " endm", " foo", " foo", ], [0, 0]); }); it("macro param label first", () => { runMacroTest([ "foo macro p1", " ld a, &p1", " endm", " foo 1", " foo 2", ], [0x3E, 1, 0x3E, 2]); }); it("macro param label last", () => { runMacroTest([ " macro foo p1", " ld a, \\p1", " endm", " foo 1", " foo 2", ], [0x3E, 1, 0x3E, 2]); }); it("macro params", () => { runMacroTest([ " macro foo p1, p2", " ld a, \\p1", " ld a, \\p2", " endm", " foo 1, 2", " foo 3, 4", ], [0x3E, 1, 0x3E, 2, 0x3E, 3, 0x3E, 4]); }); it("macro tag", () => { runMacroTest([ " macro foo #p1, #p2", " ld a, #p1", " ld a, #p2", " endm", " foo 1, 2", " foo 3, 4", ], [0x3E, 1, 0x3E, 2, 0x3E, 3, 0x3E, 4]); }); it("macro arg", () => { runMacroTest([ " macro foo p", " .text \\p", " endm", " foo 'A,B;C'", " foo \"A,B;C\"", ], [0x41, 0x2C, 0x42, 0x3B, 0x43, 0x41, 0x2C, 0x42, 0x3B, 0x43]); }); });
lkesteloot/z80-asm
src/assembler/OpcodesTypes.ts
<reponame>lkesteloot/z80-asm // Each opcode template can be a literal byte value or a variable like "nn". export type OpcodeTemplate = number | "nnnn" | "nn" | "offset" | "dd"; // Information from clr. export interface ClrInstruction { opcodes: string; undocumented: boolean; flags: string; byte_count: number; with_jump_clock_count: number; without_jump_clock_count: number; description: string; instruction: string; } // A particular variant of a mnemonic, such as "ld a,(hl)". export interface Variant { // The sequence of tokens, not including the mnemonic, such as ["a", ",", "(", "hl", ")"]. tokens: string[]; // The sequence of literal byte values or templates (like "nn"). opcode: OpcodeTemplate[]; // Optional clr information. TODO: Make not optional. clr: ClrInstruction | null; } // All information about a particular mnemonic, lke "ld". export interface MnemonicInfo { // The variants of this mnemonic. variants: Variant[]; } // Information about all mnemonics. export interface Mnemonics { // Map from mnemonic (like "ld") to information about all its variants. [mnemonic: string]: MnemonicInfo; } // All instructions. export interface Instructions { mnemonics: Mnemonics; }
45498106/crosscode-map-editor
backend/src/controllers/api.ts
<gh_stars>0 import * as fs from 'fs'; import * as path from 'path'; import {Response, Request, NextFunction} from 'express'; import {config} from '../config'; export let getAllFiles = (req: Request, res: Response) => { res.json({ images: listAllFiles(path.resolve(config.pathToCrosscode, 'media/'), [], 'png'), data: listAllFiles(path.resolve(config.pathToCrosscode, 'data/'), [], 'json') }); }; function listAllFiles(dir: string, filelist, ending: string): string[] { const files = fs.readdirSync(dir); filelist = filelist || []; files.forEach(function (file) { if (fs.statSync(path.resolve(dir, file)).isDirectory()) { filelist = listAllFiles(path.resolve(dir, file), filelist, ending); } else if (!ending || file.toLowerCase().endsWith(ending.toLowerCase())) { let normalized = path.resolve(dir, file).split(path.normalize(config.pathToCrosscode))[1]; normalized = normalized.split('\\').join('/'); if (normalized.startsWith('/')) { normalized = normalized.substr(1); } filelist.push(normalized); } }); return filelist; }
45498106/crosscode-map-editor
webapp/src/app/history/state-history.service.ts
import {Injectable} from '@angular/core'; import {BehaviorSubject} from 'rxjs'; import {CrossCodeMap} from '../shared/interfaces/cross-code-map'; export interface HistoryState { icon: string; name: string; state: CrossCodeMap; } @Injectable() export class StateHistoryService { maxStates = 100; states: BehaviorSubject<HistoryState[]> = new BehaviorSubject([]); selectedState: BehaviorSubject<{ state: HistoryState }> = new BehaviorSubject({state: null}); constructor() { } init(state: HistoryState) { this.selectedState.value.state = state; this.states.next([state]); } saveState(state: HistoryState) { const states = this.states.getValue(); const selected = this.selectedState.getValue(); const i = states.indexOf(selected.state); selected.state = state; states.length = i + 1; if (states.length >= this.maxStates) { states.shift(); } states.push(state); this.states.next(states); } undo() { const states = this.states.getValue(); const selected = this.selectedState.getValue(); let i = states.indexOf(selected.state); if (i <= 0) { return; } i--; this.selectedState.next({state: states[i]}); } redo() { const states = this.states.getValue(); const selected = this.selectedState.getValue(); let i = states.indexOf(selected.state); if (i === states.length - 1) { return; } i++; this.selectedState.next({state: states[i]}); } }
45498106/crosscode-map-editor
webapp/src/app/sidenav/entities/widgets/widget.module.ts
import {NgModule} from '@angular/core'; import {Vec2WidgetComponent} from './vec2-widget/vec2-widget.component'; import {JsonWidgetComponent} from './json-widget/json-widget.component'; import {BooleanWidgetComponent} from './boolean-widget/boolean-widget.component'; import {NumberWidgetComponent} from './number-widget/number-widget.component'; import {StringWidgetComponent} from './string-widget/string-widget.component'; import {MaterialModule} from '../../../material.module'; import {CommonModule} from '@angular/common'; import {FormsModule} from '@angular/forms'; import {FlexLayoutModule} from '@angular/flex-layout'; const COMPONENTS = [ StringWidgetComponent, NumberWidgetComponent, BooleanWidgetComponent, JsonWidgetComponent, Vec2WidgetComponent, ]; @NgModule({ imports: [ FormsModule, FlexLayoutModule, CommonModule, MaterialModule, ], declarations: COMPONENTS, entryComponents: COMPONENTS, exports: COMPONENTS }) export class WidgetModule { }
45498106/crosscode-map-editor
webapp/src/app/toolbar/toolbar.component.ts
<reponame>45498106/crosscode-map-editor import {Component, EventEmitter, OnInit, Output} from '@angular/core'; import {MapLoaderService} from '../shared/map-loader.service'; import {MatDialog} from '@angular/material'; import {MapSettingsComponent} from '../shared/dialogs/map-settings/map-settings.component'; import {CCMap} from '../shared/phaser/tilemap/cc-map'; import {GlobalEventsService} from '../shared/global-events.service'; import {OffsetMapComponent} from '../shared/dialogs/offset-map/offset-map.component'; @Component({ selector: 'app-toolbar', templateUrl: './toolbar.component.html', styleUrls: ['./toolbar.component.scss'] }) export class ToolbarComponent implements OnInit { @Output() onMenuClick = new EventEmitter(); map: CCMap; loaded: boolean; constructor(private mapLoader: MapLoaderService, private events: GlobalEventsService, private dialog: MatDialog) { } ngOnInit() { this.mapLoader.tileMap.subscribe(map => { this.map = map; }); this.events.loadComplete.subscribe(isLoaded => this.loaded = isLoaded); } loadMap(event) { this.mapLoader.loadMap(event); } saveMap() { const file = new Blob([JSON.stringify(this.map.exportMap(), null, 2)], {type: 'application/json'}); const a = document.createElement('a'), url = URL.createObjectURL(file); a.href = url; a.download = this.map.filename; document.body.appendChild(a); a.click(); setTimeout(function () { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 0); } openMapSettings() { this.dialog.open(MapSettingsComponent, { data: this.map }); } generateHeights() { this.events.generateHeights.next(); } offsetMap() { this.dialog.open(OffsetMapComponent, { data: this.map }); } }
45498106/crosscode-map-editor
webapp/src/app/shared/dialogs/map-settings/map-settings.component.ts
import {Component, Inject, OnInit} from '@angular/core'; import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material'; import {CrossCodeMap} from '../../interfaces/cross-code-map'; import {MapLoaderService} from '../../map-loader.service'; import {CCMap} from '../../phaser/tilemap/cc-map'; @Component({ selector: 'app-map-settings', templateUrl: './map-settings.component.html', styleUrls: ['./map-settings.component.scss'] }) export class MapSettingsComponent { private tileMap: CCMap; settings: CrossCodeMap = <any>{ levels: [{height: -32}, {height: 0}, {height: 32}, {height: 64}], attributes: {}, }; constructor(private loader: MapLoaderService, public ref: MatDialogRef<MapSettingsComponent>) { this.tileMap = loader.tileMap.getValue(); const tileMap = this.tileMap; if (!tileMap) { return; } const settings = this.settings; settings.mapWidth = tileMap.mapWidth; settings.mapHeight = tileMap.mapHeight; settings.levels = tileMap.levels; settings.masterLevel = tileMap.masterLevel; settings.attributes = tileMap.attributes; } update() { // TODO: add validation const settings = this.settings; const tileMap = this.tileMap; tileMap.levels = settings.levels; tileMap.masterLevel = settings.masterLevel; tileMap.attributes = settings.attributes; tileMap.resize(settings.mapWidth, settings.mapHeight); this.ref.close(); } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/helper.ts
import {Point} from '../interfaces/cross-code-map'; import {Globals} from '../globals'; import {CCMapLayer} from './tilemap/cc-map-layer'; export class Helper { /** * Transforms screen coordinates to world coordinates. * Phaser already offers a way to get world coordinates but it's messed up when the camera scales */ public static screenToWorld(x: number | Point, y?: number): Point { if (y === undefined) { y = (<any>x).y; x = (<any>x).x; } const p: Point = {}; const cam = Globals.game.camera; p.x = (<any>x + cam.x) / cam.scale.x; p.y = (y + cam.y) / cam.scale.y; return p; } /** Transforms phaser world coordinates to actual world coordinates (see {@link screenToWorld}) */ public static phaserWorldtoWorld(p: Point): Point { const out: Point = {}; const cam = Globals.game.camera; out.x = p.x / cam.scale.x; out.y = p.y / cam.scale.y; return out; } public static worldToTile(x: number, y: number): Point { const p: Point = {}; p.x = Math.floor(x / Globals.TILE_SIZE); p.y = Math.floor(y / Globals.TILE_SIZE); return p; } public static screenToTile(x: number | Point, y?: number): Point { let p = this.screenToWorld(x, y); p = this.worldToTile(p.x, p.y); return p; } /** gets the position of the tile in the tilemap */ public static getTilePos(tilesetSize: Point, index: number): Point { const tilesize = Globals.TILE_SIZE; const pos = {x: 0, y: 0}; pos.x = index % tilesetSize.x; pos.y = Math.floor(index / tilesetSize.x); if (pos.x === 0) { pos.x = tilesetSize.x; pos.y--; } pos.x--; return pos; } public static getTilesetSize(img: HTMLImageElement): Point { return { x: Math.ceil(img.width / Globals.TILE_SIZE), y: Math.ceil(img.height / Globals.TILE_SIZE) }; } public static clamp(val, min, max) { return Math.min(Math.max(val, min), max); } public static drawRect(context: CanvasRenderingContext2D, rect: Phaser.Rectangle, fillStyle, strokeStyle) { const o = new Phaser.Rectangle(rect.x + 0.5, rect.y + 0.5, rect.width - 1, rect.height); context.fillStyle = fillStyle; context.fillRect(o.x, o.y, o.width, o.height); context.lineWidth = 1; context.strokeStyle = strokeStyle; context.strokeRect(o.x, o.y, o.width, o.height); } public static deepFind(key, obj) { const paths = key.split('.'); let current = obj; for (let i = 0; i < paths.length; ++i) { if (current[paths[i]] === undefined || current[paths[i]] === null) { return current[paths[i]]; } else { current = current[paths[i]]; } } return current; } /** copies obj via JSON.parse(JSON.stringify(obj)); */ public static copy(obj) { return JSON.parse(JSON.stringify(obj)); } public static getJson(key: string, callback: (json) => void) { const game = Globals.game; // get json from cache if (game.cache.checkJSONKey(key)) { return callback(game.cache.getJSON(key)); } // load json game.load.json(key, Globals.URL + key + '.json'); game.load.onLoadComplete.addOnce(() => { return callback(game.cache.getJSON(key)); }); game.load.crossOrigin = 'anonymous'; game.load.start(); } /** * every key listener should check this method and only proceed when * false is returned, so the user can write everything into input fields * without messing up the map * */ public static isInputFocused() { if (Globals.disablePhaserInput) { return true; } const tag = document.activeElement.tagName.toLowerCase(); return tag === 'input' || tag === 'textarea'; } }
45498106/crosscode-map-editor
webapp/src/app/shared/height-map-generator/height-map-generator.service.ts
import {Injectable} from '@angular/core'; import {SharedModule} from '../shared.module'; import {GlobalEventsService} from '../global-events.service'; import {Globals} from '../globals'; import {CCMapLayer} from '../phaser/tilemap/cc-map-layer'; import {Point} from '../interfaces/cross-code-map'; import {CCMap} from '../phaser/tilemap/cc-map'; import {Vec2} from '../phaser/vec2'; import {Helper} from '../phaser/helper'; interface Dir { n: number; ne: number; e: number; se: number; s: number; sw: number; w: number; nw: number; } interface TilesetConfig { tileCountX: number; base: { mappingType: string, ground: Point, cliff: Point, cliffAlt?: Point, blockedTypes: string[], }; terrains?: { ground: Point, cliff: Point, border: boolean, }[]; } @Injectable({ providedIn: SharedModule }) export class HeightMapGeneratorService { // height map tiles private level0Id = 9; private levelOffset = 8; private typeOffset = 128; // collision tiles private CollTiles = { hole: 1, block_hole_offset: 16, block: 2, hole_sw: 4, hole_nw: 5, hole_ne: 6, hole_se: 7, block_sw: 8, block_nw: 9, block_ne: 10, block_se: 11, }; // background tiles private bgTiles = { BORDER_NW: [{x: 1, y: 0}, {x: 0, y: 1}], BORDER_N: [{x: 2, y: 0}, {x: 3, y: 0}], BORDER_NE: [{x: 4, y: 0}, {x: 5, y: 1}], BORDER_E: [{x: 3, y: 1}, {x: 3, y: 2}], BORDER_SE: [{x: 4, y: 3}, {x: 5, y: 2}], BORDER_S: [{x: 2, y: 3}, {x: 3, y: 3}], BORDER_SW: [{x: 0, y: 2}, {x: 1, y: 3}], BORDER_W: [{x: 2, y: 1}, {x: 2, y: 2}], CORNER_NW: {x: 1, y: 1}, CORNER_NE: {x: 4, y: 1}, CORNER_SE: {x: 4, y: 2}, CORNER_SW: {x: 1, y: 2}, }; private tilesetConfig: { [s: string]: TilesetConfig } = {}; constructor(private events: GlobalEventsService) { this.tilesetConfig['media/map/autumn-outside.png'] = { tileCountX: 32, base: { mappingType: 'TYPE1', ground: {x: 0, y: 0}, cliff: {x: 0, y: 5}, blockedTypes: ['CORNER_SW', 'CORNER_SE'] }, terrains: [{ ground: {x: 0, y: 1}, cliff: {x: 0, y: 5}, border: true }] }; this.tilesetConfig['media/map/bergen-trail.png'] = { tileCountX: 32, base: { mappingType: 'TYPE1', ground: {x: 0, y: 0}, cliff: {x: 0, y: 4}, cliffAlt: {x: 0, y: 10}, blockedTypes: [] }, terrains: [{ ground: {x: 1, y: 0}, cliff: {x: 6, y: 4}, border: true }, { ground: {x: 1, y: 2}, cliff: {x: 12, y: 4}, border: true }, { ground: {x: 12, y: 12}, cliff: {x: 12, y: 8}, border: true }] }; } public init(game: Phaser.Game) { this.events.generateHeights.subscribe(() => this.generateHeights()); const generateKey = game.input.keyboard.addKey(Phaser.Keyboard.A); generateKey.onDown.add(() => this.generateHeights()); } private generateHeights() { const game = Globals.game; const map = Globals.map; const extraSpace = 7; const topOffset = 1; map.resize(map.mapWidth, map.mapHeight + extraSpace, true); map.offsetMap({x: 0, y: extraSpace}, true, true); map.offsetMap({x: 0, y: -(extraSpace - topOffset)}, true, true); const masterLevel = map.masterLevel; const heightmap = map.layers.find(layer => layer.details.type === 'HeightMap'); for (let i = 0; i < map.levels.length; i++) { const collision = map.layers.find(layer => layer.details.level === i && layer.details.type === 'Collision'); const background = map.layers.find(layer => layer.details.level === i && layer.details.type === 'Background'); if (collision) { collision.clear(); } if (background) { background.clear(); } } for (let i = masterLevel; i < map.levels.length; i++) { const collision = map.layers.find(layer => layer.details.level === i && layer.details.type === 'Collision'); const background = map.layers.find(layer => layer.details.level === i && layer.details.type === 'Background'); if (!collision) { console.warn(`collision for level ${i} not found`); continue; } if (i === masterLevel && masterLevel > 0) { const waterBg = map.layers.find(layer => layer.details.level === i - 1 && layer.details.type === 'Background'); this.generateLayer(collision, waterBg, heightmap, i - 1, map, map.levels[i - 1].height - map.levels[masterLevel].height); } this.generateLayer(collision, background, heightmap, i, map, map.levels[i].height - map.levels[masterLevel].height); } console.log('WHYYYYYYYYYY'); map.offsetMap({x: 0, y: -topOffset}, false, true); map.resize(map.mapWidth, map.mapHeight - extraSpace, true); map.renderAll(); } generateLayer(collisions: CCMapLayer, background: CCMapLayer, heightmap: CCMapLayer, level: number, map: CCMap, height: number) { const data = heightmap.details.data; const minId = this.level0Id + this.levelOffset * (level + 1); const yOffset = Math.max(0, Math.floor(height / 16)); const masterLevel = map.masterLevel; for (let y = 0; y < data.length; y++) { for (let x = 0; x < data[y].length; x++) { const tile = data[y][x] % this.typeOffset; if (tile < minId && level >= masterLevel) { continue; } this.generateCollision(collisions, heightmap, x, y, level, masterLevel, tile, minId, yOffset); } } const backgroundTop = map.layers.find(layer => layer.details.level === background.details.level + 1 && layer.details.type === 'Background'); if (!backgroundTop) { return; } const tilesetConfig = this.tilesetConfig[background.details.tilesetName]; for (let y = 0; y < data.length; y++) { for (let x = 0; x < data[y].length; x++) { const tile = data[y][x] % this.typeOffset; this.generateBackground(background, backgroundTop, collisions, x, y, level, data[y][x], minId, map, tilesetConfig, heightmap); } } } private generateCollision(collisions: CCMapLayer, heightmap: CCMapLayer, x: number, y: number, level: number, masterLevel: number, tile: number, minId: number, yOffset: number) { const other = this.getNeighbours(x, y, heightmap, tile, true); // TODO: add static tiles (tile % this.levelOffset !== 0 should be static tiles) let tileId = this.CollTiles.block; if (this.dirCompare(other, minId, 'n ne e', 'n ne e se', 'nw n ne e', 'nw n ne e se')) { tileId = this.CollTiles.block_ne; } else if (this.dirCompare(other, minId, 'w nw n', 'w nw n ne', 'sw w nw n', 'sw w nw n ne')) { tileId = this.CollTiles.block_nw; } else if (this.dirCompare(other, minId, 's sw w nw', 'se s sw w', 's sw w', 'se s sw w nw', 'sw w')) { tileId = this.CollTiles.block_sw; } else if (this.dirCompare(other, minId, 'sw s se e', 's se e', 'ne e se s', 'ne e se s sw')) { tileId = this.CollTiles.block_se; } if (tileId !== this.CollTiles.block && level === masterLevel) { 'n e s w'.split(' ').some(key => { const id = other[key] % this.typeOffset; if (id === this.level0Id) { tileId += this.CollTiles.block_hole_offset; return true; } }); } // water coll // TODO: is kinda broken. below master level should use maxId instead of minId for dirCompare because collisions are inversed if (level < masterLevel) { const def = this.CollTiles; if (tile < this.level0Id + this.levelOffset) { tileId = def.hole; } else { switch (tileId) { case def.block: return; case def.block_se: tileId = def.hole_nw; break; case def.block_sw: tileId = def.hole_ne; break; case def.block_nw: tileId = def.hole_se; break; case def.block_ne: tileId = def.hole_sw; break; } } } collisions.details.data[Math.max(0, y - yOffset)][x] = tileId; } private generateBackground( background: CCMapLayer, backgroundTop: CCMapLayer, collisions: CCMapLayer, x: number, y: number, level: number, heightmapTile: number, minId: number, map: CCMap, tilesetconfig: TilesetConfig, heightmap: CCMapLayer) { let yHeight = map.levels[level + 1].height - map.levels[level].height; yHeight /= Globals.TILE_SIZE; let yOffset = map.levels[level].height - map.levels[map.masterLevel].height; yOffset /= Globals.TILE_SIZE; let collTile = collisions.details.data[y][x]; let other = this.getNeighbours(x, y, collisions, collTile); if (level < map.masterLevel) { collTile = this.getTile(x, y + yOffset, collisions, 0); if (y + yOffset >= collisions.details.height || y + yOffset < 0) { return; } other = this.getNeighbours(x, y + yOffset, collisions, collTile); collTile = this.holeToBlock(collTile); Object.keys(other).forEach(key => other[key] = this.holeToBlock(other[key])); } if (collTile === 0) { return; } // bottom if (this.isHole(other.s)) { let bgTile; const def = this.CollTiles; if (collTile === def.block) { bgTile = this.bgTiles.BORDER_S; } else if (collTile === def.block_nw || collTile === def.block_nw + def.block_hole_offset) { bgTile = this.bgTiles.BORDER_SE; } else if (collTile === def.block_ne || collTile === def.block_ne + def.block_hole_offset) { bgTile = this.bgTiles.BORDER_SW; } else { return; } // draw tiles (middle, top, bottom) for (let i = 0; i < yHeight; i++) { this.updateTile(x, y - i, bgTile, 1, background, tilesetconfig, true); } this.updateTile(x, y - yHeight, bgTile, 0, backgroundTop, tilesetconfig); const currentHeight = this.level0Id + this.levelOffset * level; let bottomHeightmapTile = currentHeight; const offsetY = y + 1 + yOffset; if (offsetY >= 0 && offsetY < heightmap.details.height) { bottomHeightmapTile = heightmap.details.data[offsetY][x] % this.typeOffset; } if (currentHeight - bottomHeightmapTile < this.levelOffset) { this.updateTile(x, y, bgTile, 2, background, tilesetconfig); } return; } // top if (this.isHole(other.n)) { let bgTile; const def = this.CollTiles; if (collTile === def.block) { bgTile = this.bgTiles.BORDER_N; } else if (collTile === def.block_sw || collTile === def.block_sw + def.block_hole_offset) { bgTile = this.bgTiles.BORDER_NE; } else if (collTile === def.block_se || collTile === def.block_se + def.block_hole_offset) { bgTile = this.bgTiles.BORDER_NW; } else { return; } Vec2.add(bgTile, tilesetconfig.base.cliff); this.updateTile(x, y - yHeight, bgTile, 0, backgroundTop, tilesetconfig); return; } // sides let bgTile; if (this.isHole(other.e)) { bgTile = this.bgTiles.BORDER_E; } if (this.isHole(other.w)) { bgTile = this.bgTiles.BORDER_W; } if (bgTile && collTile === this.CollTiles.block) { Vec2.add(bgTile, tilesetconfig.base.cliff); this.updateTile(x, y - yHeight, bgTile, 0, backgroundTop, tilesetconfig); return; } // floor if (collTile === this.CollTiles.block) { let tile = tilesetconfig.base.ground; // corners if (this.isHole(other.nw) && !tilesetconfig.base.blockedTypes.includes('CORNER_NW')) { tile = Vec2.add(this.bgTiles.CORNER_NW, tilesetconfig.base.cliff, true); } else if (this.isHole(other.ne) && !tilesetconfig.base.blockedTypes.includes('CORNER_NE')) { tile = Vec2.add(this.bgTiles.CORNER_NE, tilesetconfig.base.cliff, true); } else if (this.isHole(other.se) && !tilesetconfig.base.blockedTypes.includes('CORNER_SE')) { tile = Vec2.add(this.bgTiles.CORNER_SE, tilesetconfig.base.cliff, true); } else if (this.isHole(other.sw) && !tilesetconfig.base.blockedTypes.includes('CORNER_SW')) { tile = Vec2.add(this.bgTiles.CORNER_SW, tilesetconfig.base.cliff, true); } backgroundTop.updateTileChecked(x, y - yHeight, background.getTile(tile.x, tile.y)); return; } } // returns true if at least one pattern matches private dirCompare(neighbours: Dir, minIndex: number, ...patternString: string[]): boolean { return patternString.some(str => { const pattern = str.split(' '); let out = true; Object.keys(neighbours).forEach(key => { const index = neighbours[key] % this.typeOffset; if (pattern.includes(key)) { if (index < minIndex) { out = false; } } else { if (index >= minIndex) { out = false; } } }); return out; }); } private getNeighbours(x: number, y: number, layer: CCMapLayer, initial: number, extend: boolean = false): Dir { const out: Dir = { n: initial, ne: initial, e: initial, se: initial, s: initial, sw: initial, w: initial, nw: initial }; const w = layer.details.width; const h = layer.details.height; const data = layer.details.data; // TODO: i think extend is not neccessary if (x > 0) { out.w = data[y][x - 1]; } else if (extend) { out.w = data[y][x]; } if (x < w - 1) { out.e = data[y][x + 1]; } else if (extend) { out.e = data[y][x]; } if (y > 0) { out.n = data[y - 1][x]; } else if (extend) { out.n = data[y][x]; } if (y < h - 1) { out.s = data[y + 1][x]; } else if (extend) { out.s = data[y][x]; } if (x > 0 && y > 0) { out.nw = data[y - 1][x - 1]; } else if (extend) { if (x > 0) { out.nw = data[y][x - 1]; } else if (y > 0) { out.nw = data[y - 1][x]; } else { out.nw = data[y][x]; } } if (x < w - 1 && y > 0) { out.ne = data[y - 1][x + 1]; } else if (extend) { if (x < w - 1) { out.ne = data[y][x + 1]; } else if (y > 0) { out.ne = data[y - 1][x]; } else { out.ne = data[y][x]; } } if (y < h - 1 && x > 0) { out.sw = data[y + 1][x - 1]; } else if (extend) { if (y < h - 1) { out.sw = data[y + 1][x]; } else if (x > 0) { out.sw = data[y][x - 1]; } else { out.sw = data[y][x]; } } if (y < h - 1 && x < w - 1) { out.se = data[y + 1][x + 1]; } else if (extend) { if (y < h - 1) { out.se = data[y + 1][x]; } else if (x < w - 1) { out.se = data[y][x + 1]; } else { out.se = data[y][x]; } } return out; } private getTile(x: number, y: number, layer: CCMapLayer, oobValue: number): number { if (x < 0 || y < 0 || x >= layer.details.width || y >= layer.details.height) { return oobValue; } return layer.details.data[y][x]; } // converts collision tiles into block tiles (for layers below master level) private holeToBlock(tile): number { const def = this.CollTiles; switch (tile) { case def.hole: return 0; case def.hole_nw: return def.block_se; case def.hole_ne: return def.block_sw; case def.hole_se: return def.block_nw; case def.hole_sw: return def.block_ne; default: return def.block; } } private updateTile(x: number, y: number, tile: Point[], yOffset: number, layer: CCMapLayer, config: TilesetConfig, offsetAlternation: boolean = false) { let alternation = this.getAlternate(x, y); if (offsetAlternation) { alternation = 1 - alternation; } if (!tile[alternation]) { console.log('wtf'); } const newTile = Vec2.assign({}, tile[alternation]); newTile.y += yOffset; const bgTile = Vec2.add(newTile, config.base.cliff, true); layer.updateTileChecked(x, y, layer.getTile(bgTile.x, bgTile.y)); } private isHole(tile): boolean { return tile < this.CollTiles.block_sw && tile !== this.CollTiles.block; } private getAlternate(x, y) { return Math.abs((x + y) % 2); } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/phaser-events.service.ts
<filename>webapp/src/app/shared/phaser/phaser-events.service.ts import {Injectable} from '@angular/core'; import {Subject} from 'rxjs'; import Point = Phaser.Point; @Injectable({ providedIn: 'root' }) export class PhaserEventsService { // TODO: event should be informational (camera zoomed/map size changed) instead of a command updateMapBorder: Subject<boolean> = new Subject(); }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/tilemap/cc-map-layer.ts
import {MapLayer, Point} from '../../interfaces/cross-code-map'; import * as Phaser from 'phaser-ce'; import {Sortable} from '../../interfaces/sortable'; import {Helper} from '../helper'; import {Globals} from '../../globals'; export class CCMapLayer extends Phaser.Image implements Sortable { public details: MapLayer; public backgroundColor: { r: number, g: number, b: number, a: number }; private bitmap: Phaser.BitmapData; private tilesetImage: Phaser.Image; private tileCrop: Phaser.Rectangle; private tilesetSize: Point; zIndex: number; constructor(game: Phaser.Game, details: MapLayer) { super(game, 0, 0, ''); // this.backgroundColor = {r: 255, g: 128, b: 0, a: 1}; if (typeof details.level === 'string') { // possible levels // 'first' // 'last' // 'light' // 'postlight' // 'object1' // 'object2' // 'object3' if (!isNaN(<any>details.level)) { details.level = parseInt(details.level, 10); } else { details.levelName = details.level; if (details.level.startsWith('first')) { details.level = 0; } else { // TODO: get actual max level; details.level = 10; } } } if (typeof details.distance === 'string') { details.distance = parseFloat(details.distance); } this.details = details; this.bitmap = game.make.bitmapData(details.width * details.tilesize, details.height * details.tilesize); this.loadTexture(this.bitmap); game.add.existing(this); if (details.tilesetName) { this.tilesetImage = game.make.image(0, 0, details.tilesetName); this.tilesetSize = Helper.getTilesetSize(game.cache.getImage(details.tilesetName)); this.tileCrop = new Phaser.Rectangle(0, 0, Globals.TILE_SIZE, Globals.TILE_SIZE); this.tilesetImage.crop(this.tileCrop); } const skip = 'Navigation Collision HeightMap'.split(' '); // const skip = 'Navigation Background HeightMap'.split(' '); skip.forEach(type => { if (type === details.type) { this.visible = false; } }); this.zIndex = this.details.level * 10; if (isNaN(this.zIndex)) { this.zIndex = 999; } // this.visible = false; this.renderAll(); } renderAll() { const bitmap = this.bitmap; const tileset = this.tilesetImage; const details = this.details; const tileSize = details.tilesize; bitmap.clear(); if (this.backgroundColor) { const bg = this.backgroundColor; bitmap.fill(bg.r, bg.g, bg.b, bg.a); } for (let y = 0; y < details.data.length; y++) { for (let x = 0; x < details.data[y].length; x++) { const tile = details.data[y][x]; if (tile === 0) { continue; } this.makeTile(tile); bitmap.draw(tileset, x * tileSize, y * tileSize, tileSize, tileSize); } } } // checks bounds before drawing updateTileChecked(x: number, y: number, tile: number) { if (x >= 0 && x < this.details.data[0].length) { if (y >= 0 && y < this.details.data.length) { this.details.data[y][x] = tile; } } } drawTile(x: number, y: number, tile: number) { const bitmap = this.bitmap; const tileset = this.tilesetImage; const details = this.details; const tileSize = details.tilesize; const oldTile = details.data[y][x]; if (oldTile === tile) { return; } details.data[y][x] = tile; const tileX = x * tileSize; const tileY = y * tileSize; bitmap.clear(tileX, tileY, tileSize, tileSize); if (tile !== 0) { this.makeTile(tile); bitmap.draw(tileset, tileX, tileY); } } makeTile(index: number) { const tilesize = this.details.tilesize; const crop = this.tileCrop; const p = Helper.getTilePos(this.tilesetSize, index); crop.x = p.x * tilesize; crop.y = p.y * tilesize; this.tilesetImage.updateCrop(); } getTile(x: number, y: number) { let index = x + 1; index += y * this.tilesetSize.x; return index; } clear() { this.bitmap.clear(); this.details.data.forEach(arr => arr.fill(0)); } destroy() { if (this.bitmap) { this.bitmap.destroy(); } if (this.tilesetImage) { this.tilesetImage.destroy(); } super.destroy(); } resize(width: number, height: number, skipRender = false) { const data = this.details.data; data.length = height; for (let i = 0; i < data.length; i++) { if (!data[i]) { data[i] = new Array(width).fill(0); } else { if (width < this.details.width) { data[i].length = width; } else { while (data[i].length < width) { data[i].push(0); } } } } this.details.width = width; this.details.height = height; this.bitmap.resize(width * Globals.TILE_SIZE, height * Globals.TILE_SIZE); if (!skipRender) { this.renderAll(); } } offsetLayer(offset: Point, borderTiles = false, skipRender = false) { const data = this.details.data; const newData: number[][] = JSON.parse(JSON.stringify(data)); for (let y = 0; y < data.length; y++) { for (let x = 0; x < data[y].length; x++) { let newTile = 0; let row = data[y - offset.y]; if (!row && borderTiles) { row = offset.y > 0 ? data[0] : data[data.length - 1]; } if (row) { newTile = row[x - offset.x]; if (borderTiles && newTile === undefined) { newTile = offset.x > 0 ? row[0] : row[row.length - 1]; } } newData[y][x] = newTile || 0; } } this.details.data = newData; if (!skipRender) { this.renderAll(); } } fill(newTile: number, p: Point) { const data = this.details.data; const prev = data[p.y][p.x]; if (newTile === prev) { return; } let toCheck: Point[] = [p]; while (toCheck.length > 0) { const currP = toCheck.pop(); const tile = data[currP.y][currP.x]; if (tile === prev) { data[currP.y][currP.x] = newTile; toCheck = toCheck.concat(this.getNeighbours(currP)); } } this.renderAll(); } private getNeighbours(p: Point): Point[] { const out: Point[] = []; if (p.x > 0) { out.push({x: p.x - 1, y: p.y}); } if (p.x < this.details.width - 1) { out.push({x: p.x + 1, y: p.y}); } if (p.y > 0) { out.push({x: p.x, y: p.y - 1}); } if (p.y < this.details.height - 1) { out.push({x: p.x, y: p.y + 1}); } return out; } exportLayer() { const out: MapLayer = Object.assign({}, this.details); if (out.levelName) { out.level = out.levelName; out.levelName = undefined; } return out; } }
45498106/crosscode-map-editor
webapp/src/app/shared/http-client.service.ts
import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs'; import {Globals} from './globals'; declare let nw: any; declare let chrome: any; declare let requireNode: any; @Injectable() export class HttpClientService { private fs; private path; private config; private isClicked = false; constructor(private http: HttpClient) { if (Globals.isNwjs) { this.fs = requireNode('fs'); this.path = requireNode('path'); try { this.config = JSON.parse(this.fs.readFileSync(this.path.join(nw.App.dataPath, 'config.json'))); Globals.URL = 'file:///' + this.config.pathToCrosscode; } catch (e) { this.selectCcFolder(); } } } getAllFiles(): Observable<Object> { if (!Globals.isNwjs) { return this.http.get(Globals.URL + 'api/allFiles'); } return new Observable(obs => { try { const o = { images: this.listAllFiles(this.config.pathToCrosscode + 'media/', [], 'png'), data: this.listAllFiles(this.config.pathToCrosscode + 'data/', [], 'json') }; obs.next(o); obs.complete(); } catch (e) { console.error(e); this.selectCcFolder(); } }); } private selectCcFolder() { if (this.isClicked) { return; } const fs = this.fs; const path = this.path; const dirInput = document.getElementById('inputDirectory'); dirInput.addEventListener('change', function (evt) { const ccPath: string = (<any>this).value + '\\'; fs.writeFileSync(path.join(nw.App.dataPath, 'config.json'), JSON.stringify({pathToCrosscode: ccPath}, null, 2)); console.log(nw.App.dataPath); chrome.runtime.reload(); }, false); dirInput.click(); this.isClicked = true; } private listAllFiles(dir: string, filelist, ending: string): string[] { const files = this.fs.readdirSync(dir); const that = this; filelist = filelist || []; files.forEach(function (file) { if (that.fs.statSync(dir + file).isDirectory()) { filelist = that.listAllFiles(dir + file + '/', filelist, ending); } else if (!ending || file.toLowerCase().endsWith(ending.toLowerCase())) { filelist.push((dir + file).split(that.config.pathToCrosscode)[1]); } }); return filelist; } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/map-pan.ts
import {Point} from '../interfaces/cross-code-map'; import {Helper} from './helper'; export class MapPan extends Phaser.Plugin { private button: Phaser.DeviceButton; private isScrolling = false; private startMouse: Point = {}; private startCam: Point = {}; private zoomKey: Phaser.Key; constructor(game: Phaser.Game, parent) { super(game, parent); this.active = true; this.hasUpdate = true; this.button = game.input.activePointer.middleButton; this.button.onDown.add(() => this.onMouseDown()); this.button.onUp.add(() => this.onMouseUp()); this.zoomKey = game.input.keyboard.addKey(Phaser.Keyboard.ALT); game.input.mouse.mouseWheelCallback = (v) => this.onMouseWheel(v); } onMouseDown() { this.isScrolling = true; this.startMouse.x = this.game.input.x; this.startMouse.y = this.game.input.y; this.startCam.x = this.game.camera.x; this.startCam.y = this.game.camera.y; } onMouseUp() { this.isScrolling = false; } onMouseWheel(event) { if (!this.zoomKey.isDown) { return; } const cam = this.game.camera; const prevScale = cam.scale.x; let scale = event.deltaY > 0 ? 0.8 : 1.25; scale *= cam.scale.x; if (scale > 0.4 && scale < 8) { cam.scale.setTo(scale); // adjust position const mouseX = this.game.input.worldX / prevScale; const mouseY = this.game.input.worldY / prevScale; const multiplier = scale - prevScale; cam.x += mouseX * multiplier; cam.y += mouseY * multiplier; } this.game['PhaserEventsService'].updateMapBorder.next(true); } update() { if (this.isScrolling) { // mouse const dx = this.game.input.x - this.startMouse.x; const dy = this.game.input.y - this.startMouse.y; // dx /= this.game.camera.scale.x; // dy /= this.game.camera.scale.y; this.game.camera.x = this.startCam.x - dx; this.game.camera.y = this.startCam.y - dy; } } }
45498106/crosscode-map-editor
webapp/src/app/shared/global-events.service.ts
import {Injectable} from '@angular/core'; import {BehaviorSubject, Subject} from 'rxjs'; import {EditorView} from './interfaces/editor-view'; import {CCEntity} from './phaser/entities/cc-entity'; import {MapEntity, Point} from './interfaces/cross-code-map'; @Injectable() export class GlobalEventsService { currentView: BehaviorSubject<EditorView> = new BehaviorSubject(null); selectedEntity: BehaviorSubject<CCEntity> = new BehaviorSubject(null); showAddEntityMenu: Subject<{ worldPos: Point, definitions: any }> = new Subject(); generateNewEntity: Subject<MapEntity> = new Subject(); loadComplete: Subject<boolean> = new Subject(); generateHeights: Subject<void> = new Subject(); offsetMap: Subject<Point> = new Subject(); toggleVisibility: Subject<void> = new Subject(); constructor() { } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/entities/template.ts
import {CCEntity, ScaleSettings} from './cc-entity'; export class Template extends CCEntity { private attributes = {}; public getAttributes() { return this.attributes; } getScaleSettings(): ScaleSettings { return undefined; } protected setupType(settings: any) { } }
45498106/crosscode-map-editor
webapp/src/app/editor/add-entity-menu/add-entity-menu.component.ts
<filename>webapp/src/app/editor/add-entity-menu/add-entity-menu.component.ts import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core'; import {GlobalEventsService} from '../../shared/global-events.service'; import {MapEntity, Point} from '../../shared/interfaces/cross-code-map'; import {MatMenuTrigger} from '@angular/material'; import {Vec2} from '../../shared/phaser/vec2'; import {Helper} from '../../shared/phaser/helper'; @Component({ selector: 'app-add-entity-menu', templateUrl: './add-entity-menu.component.html', styleUrls: ['./add-entity-menu.component.scss'] }) export class AddEntityMenuComponent { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; @ViewChild('filter') filter: ElementRef; pos: Point = {x: 0, y: 0}; keys: string[]; filteredKeys: string[]; searchInput: string; private worldPos: Point; private mousePos: Point = {}; constructor(private events: GlobalEventsService) { document.onmousemove = e => { this.mousePos.x = e.pageX; this.mousePos.y = e.pageY; }; this.events.showAddEntityMenu.subscribe(val => { Vec2.assign(this.pos, this.mousePos); this.worldPos = val.worldPos; if (!this.keys) { this.keys = Object.keys(val.definitions); } this.searchInput = ''; this.filteredKeys = this.keys.slice(); setTimeout(() => { this.trigger.openMenu(); this.filter.nativeElement.focus(); }, 0); }); } generateEntity(key: string) { const entity: MapEntity = { x: this.worldPos.x, y: this.worldPos.y, type: key, level: 0, settings: {} }; this.events.generateNewEntity.next(entity); } filterKeys(search: string) { this.searchInput = search; this.filteredKeys = this.keys.filter(key => { if (!search) { return true; } return key.toLowerCase().includes(search.toLowerCase()); }); console.log(this.filteredKeys); } }
45498106/crosscode-map-editor
webapp/src/app/shared/json-editor/json-editor.component.ts
import {AfterViewInit, Component, ElementRef, Inject, Input, OnInit, Optional, ViewChild} from '@angular/core'; import JSONEditor, {JSONEditorOptions} from 'jsoneditor'; import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material'; import {Globals} from '../globals'; @Component({ selector: 'app-json-editor', templateUrl: './json-editor.component.html', styleUrls: ['./json-editor.component.scss'] }) export class JsonEditorComponent implements AfterViewInit { @ViewChild('editor') container: ElementRef; private editor: JSONEditor; private options: JSONEditorOptions; data; private key: string; json = JSON; constructor(@Optional() @Inject(MAT_DIALOG_DATA) data, public ref: MatDialogRef<JsonEditorComponent>) { this.data = data.val; this.key = data.key; ref.afterClosed().subscribe(() => { Globals.disablePhaserInput = false; }); } ngAfterViewInit() { Globals.disablePhaserInput = true; this.options = {}; this.options.onChange = () => { this.data = this.editor.get(); }; this.editor = new JSONEditor(this.container.nativeElement, this.options); this.editor.set(this.data); this.editor.setName(this.key); this.editor.expandAll(); } setJson(val) { this.data = JSON.parse(val); this.editor.set(this.data); this.editor.expandAll(); } }
45498106/crosscode-map-editor
backend/src/config.ts
export let config = { pathToCrosscode: 'D:/programming/CrossCode/entpackt/assets/' };
45498106/crosscode-map-editor
webapp/src/app/shared/shared.module.ts
<filename>webapp/src/app/shared/shared.module.ts<gh_stars>0 import {NgModule} from '@angular/core'; import {GlobalEventsService} from './global-events.service'; import {HostDirective} from './host.directive'; import {HttpClientService} from './http-client.service'; import {MapLoaderService} from './map-loader.service'; import {MapSettingsComponent} from './dialogs/map-settings/map-settings.component'; import {FloatingWindowComponent} from './floating-window/floating-window.component'; import {JsonEditorComponent} from './json-editor/json-editor.component'; import {FormsModule} from '@angular/forms'; import {MaterialModule} from '../material.module'; import {AngularDraggableModule} from 'angular2-draggable'; import {CommonModule} from '@angular/common'; import {FlexLayoutModule} from '@angular/flex-layout'; import {OffsetMapComponent} from './dialogs/offset-map/offset-map.component'; @NgModule({ imports: [ FormsModule, FlexLayoutModule, CommonModule, MaterialModule, AngularDraggableModule, ], declarations: [ HostDirective, MapSettingsComponent, JsonEditorComponent, FloatingWindowComponent, OffsetMapComponent, ], providers: [ HttpClientService, MapLoaderService, GlobalEventsService, ], entryComponents: [ JsonEditorComponent, MapSettingsComponent, OffsetMapComponent, ], exports: [ HostDirective, MapSettingsComponent, JsonEditorComponent, FloatingWindowComponent, ] }) export class SharedModule { }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/entities/entity-registry.service.ts
<reponame>45498106/crosscode-map-editor<gh_stars>0 import {Injectable} from '@angular/core'; import {DefaultEntity} from './default-entity'; import {CCEntity} from './cc-entity'; import {Prop} from './prop'; import {ScalableProp} from './scalable-prop'; import {ItemDestruct} from './item-destruct'; @Injectable({ providedIn: 'root' }) export class EntityRegistryService { private entities: { [type: string]: any } = {}; private defaultEntity: any; constructor() { this.setDefaultEntity(DefaultEntity); this.register('Prop', Prop); this.register('ScalableProp', ScalableProp); this.register('ItemDestruct', ItemDestruct); } private setDefaultEntity(entity: any) { this.defaultEntity = entity; } private register(type: string, entity: any) { this.entities[type] = entity; } public getDefaultEntity(): new (...args) => CCEntity { return this.defaultEntity; } public getEntity(type: string): new (...args) => CCEntity { return this.entities[type] || this.defaultEntity; } }
45498106/crosscode-map-editor
webapp/src/app/shared/dialogs/offset-map/offset-map.component.ts
<reponame>45498106/crosscode-map-editor<gh_stars>0 import {Component, OnInit} from '@angular/core'; import {MapLoaderService} from '../../map-loader.service'; import {MatDialogRef} from '@angular/material'; import {Point} from '../../interfaces/cross-code-map'; import {GlobalEventsService} from '../../global-events.service'; @Component({ selector: 'app-offset-map', templateUrl: './offset-map.component.html', styleUrls: ['./offset-map.component.scss'] }) export class OffsetMapComponent { offset: Point; constructor(private events: GlobalEventsService, public ref: MatDialogRef<OffsetMapComponent>) { this.offset = {x: 0, y: 0}; } update() { this.events.offsetMap.next(this.offset); this.ref.close(); } }
45498106/crosscode-map-editor
backend/src/server.ts
<reponame>45498106/crosscode-map-editor import * as express from 'express'; import * as bodyParser from 'body-parser'; import * as logger from 'morgan'; import * as errorHandler from 'errorhandler'; import * as cors from 'cors'; import {config} from './config'; // Controllers (route handlers). import * as apiController from './controllers/api'; const app = express(); /** * Express configuration. */ app.set('port', process.env.PORT || 8080); app.use(cors()); app.use(express.static(config.pathToCrosscode, {maxAge: 0})); // app.use(compression()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); /** * Primary app routes. */ app.get('/api/allFiles', apiController.getAllFiles); /** * Error Handler. Provides full stack - remove for production */ app.use(errorHandler()); /** * Start Express server. */ app.listen(app.get('port'), () => { console.log((' App is running at http://localhost:%d in %s mode'), app.get('port'), app.get('env')); console.log(' Press CTRL-C to stop\n'); }); module.exports = app;
45498106/crosscode-map-editor
webapp/src/app/shared/interfaces/editor-view.ts
<gh_stars>1-10 export enum EditorView { Layers, Entities }
45498106/crosscode-map-editor
webapp/src/app/phaser/phaser.component.ts
import {AfterViewInit, Component, ElementRef, HostListener, OnDestroy, OnInit} from '@angular/core'; import * as Phaser from 'phaser-ce'; import {MapLoaderService} from '../shared/map-loader.service'; import {Subscription} from 'rxjs'; import {MapPan} from '../shared/phaser/map-pan'; import {CCMap} from '../shared/phaser/tilemap/cc-map'; import {TileDrawer} from '../shared/phaser/tilemap/tile-drawer'; import {EntityManager} from '../shared/phaser/entities/entity-manager'; import {GlobalEventsService} from '../shared/global-events.service'; import {EditorView} from '../shared/interfaces/editor-view'; import {Globals} from '../shared/globals'; import {HttpClientService} from '../shared/http-client.service'; import {StateHistoryService} from '../history/state-history.service'; import {EntityRegistryService} from '../shared/phaser/entities/entity-registry.service'; import {PhaserEventsService} from '../shared/phaser/phaser-events.service'; import {HeightMapGeneratorService} from '../shared/height-map-generator/height-map-generator.service'; @Component({ selector: 'app-phaser', templateUrl: './phaser.component.html', styleUrls: ['./phaser.component.scss'] }) export class PhaserComponent implements OnInit, OnDestroy { game: Phaser.Game; tileMap: CCMap; sub: Subscription; private fpsLogCounter = 0; border: Phaser.Rectangle; // plugins private mapPan: MapPan; private tileDrawer: TileDrawer; private entityManager: EntityManager; constructor(private element: ElementRef, private mapLoader: MapLoaderService, private globalEvents: GlobalEventsService, private entityRegistry: EntityRegistryService, private stateHistory: StateHistoryService, private phaserEventsService: PhaserEventsService, private http: HttpClientService, private heightGenerator: HeightMapGeneratorService) { } ngOnInit() { this.http.getAllFiles().subscribe(res => { this.game = new Phaser.Game( screen.width * window.devicePixelRatio, screen.height * window.devicePixelRatio, Phaser.WEBGL_MULTI, 'content', { create: () => this.create(), update: () => this.update(), render: () => this.render(), preload: () => this.preload(res), }, undefined, false); Globals.game = this.game; }); } create() { const game = this.game; game.time.advancedTiming = true; this.game['StateHistoryService'] = this.stateHistory; this.game['MapLoaderService'] = this.mapLoader; this.game['EntityRegistryService'] = this.entityRegistry; this.game['PhaserEventsService'] = this.phaserEventsService; this.game['GlobalEventsService'] = this.globalEvents; game.stage.backgroundColor = '#616161'; game.canvas.oncontextmenu = function (e) { e.preventDefault(); }; game.world.setBounds(-100000, -100000, 200000, 200000); game.scale.scaleMode = Phaser.ScaleManager.USER_SCALE; const scale = 1 / window.devicePixelRatio; game.scale.setUserScale(scale, scale); game.renderer.renderSession.roundPixels = true; Phaser.Canvas.setImageRenderingCrisp(this.game.canvas); this.tileMap = new CCMap(game); Globals.map = this.tileMap; this.sub = this.mapLoader.map.subscribe((map) => { if (map) { this.tileMap.loadMap(map); this.rescaleBorder(); } }); this.phaserEventsService.updateMapBorder.subscribe(a => this.rescaleBorder()); // plugins this.mapPan = game.plugins.add(MapPan); this.entityManager = game.plugins.add(EntityManager); this.entityManager.setGlobalEvents(this.globalEvents); this.tileDrawer = game.plugins.add(TileDrawer); this.globalEvents.currentView.subscribe(view => { if (view === EditorView.Layers) { this.tileDrawer.activate(); this.tileDrawer.selectLayer(this.mapLoader.selectedLayer.getValue(), this.tileMap); this.entityManager.deactivate(); console.log(this.game.world.children); } else if (view === EditorView.Entities) { this.tileDrawer.selectLayer(null); this.tileDrawer.deactivate(); this.entityManager.activate(); } }); this.border = new Phaser.Rectangle(0, 0, 0, 0); this.mapLoader.selectedLayer.subscribe(layer => this.tileDrawer.selectLayer(layer)); this.globalEvents.currentView.next(EditorView.Layers); this.heightGenerator.init(game); } preload(res) { // res.data.forEach(json => { // this.game.load.json(json, Globals.URL + json); // }); res.images.forEach(img => { this.game.load.image(img, Globals.URL + img); }); this.game.load.json('definitions.json', 'assets/definitions.json'); this.game.load.json('destructibles.json', 'assets/destructibles.json'); this.game.load.crossOrigin = 'anonymous'; this.game.load.onLoadComplete.addOnce(() => { this.globalEvents.loadComplete.next(true); }); } update() { if (Globals.zIndexUpdate) { Globals.zIndexUpdate = false; this.game.world.children.sort(this.sortFunc); } } sortFunc(a, b) { const va = a.zIndex || 0; const vb = b.zIndex || 0; const diff = va - vb; if (diff !== 0) { return diff; } return a.z - b.z; } render() { // expensive call, use only for debugging this.game.debug.text(this.game.time.fps.toString(), 2, 14, '#00ff00'); // this.fpsLogCounter++; // if (this.fpsLogCounter > 60) { // this.fpsLogCounter %= 60; // console.log(this.game.time.fps); // } this.game.debug.geom(this.border, '#F00', false); } ngOnDestroy() { if (this.sub) { this.sub.unsubscribe(); } } private rescaleBorder() { if (!this.tileMap.layers) { return; } const s = this.tileMap.layers[0].details.tilesize * this.game.camera.scale.x; this.border.resize(this.tileMap.mapWidth * s, this.tileMap.mapHeight * s); } }
45498106/crosscode-map-editor
webapp/src/app/sidenav/entities/widgets/abstract-widget.ts
<reponame>45498106/crosscode-map-editor import {Input} from '@angular/core'; import {CCEntity} from '../../../shared/phaser/entities/cc-entity'; export abstract class AbstractWidget { @Input() key: string; @Input() attribute: any; @Input() entity: CCEntity; setSetting(key: string, value: any, updateType = true, parse = false) { if (parse) { value = JSON.parse(value); } this.entity.details.settings[key] = value; if (updateType) { this.updateType(); } } toInt(val) { return parseInt(val, 10); } updateSettings() { this.entity.updateSettings(); } updateType() { this.entity.updateType(); } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/entities/item-destruct.ts
<reponame>45498106/crosscode-map-editor import {CCEntity, ScaleSettings} from './cc-entity'; import {Helper} from '../helper'; import {PropDef} from './prop'; import * as Phaser from 'phaser-ce'; export class ItemDestruct extends CCEntity { private attributes = { desType: { type: 'String', description: 'Type of destructible object', options: null, Yi: true }, items: { type: 'ItemsDropRate', description: 'Items dropped', bd: true }, perma: { type: 'Boolean', description: 'True if cannot be respawned', default: 'false', R: true }, trigger: { type: 'String', description: 'var tp set to true once the prop has been destroyed. Only works once.', R: true }, enemyInfo: { type: 'EnemyType', description: 'Enemy to spawn after destruction', bd: true, Yi: true } }; public getAttributes() { return this.attributes; } getScaleSettings(): ScaleSettings { return undefined; } protected setupType(settings: any) { Helper.getJson('data/global-settings', (globalSettings) => { const destructibles = this.game.cache.getJSON('destructibles.json'); let desType; if (settings.desType) { desType = settings.desType; } else { desType = globalSettings.ENTITY.ItemDestruct[settings.__GLOBAL__].desType; } const def = destructibles[desType]; this.anchor.set(0.5, 1); this.entitySettings = <any>{ sheets: { fix: [{ gfx: def.Aa.sheet.src, x: def.Aa.sheet.offX, y: def.Aa.sheet.offY, w: def.Aa.sheet.width, h: def.Aa.sheet.height }] }, baseSize: def.size }; this.updateSettings(); }); } }
45498106/crosscode-map-editor
webapp/src/main.ts
<filename>webapp/src/main.ts<gh_stars>0 import {enableProdMode} from '@angular/core'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {AppModule} from './app/app.module'; import {environment} from './environments/environment'; import {Globals} from './app/shared/globals'; declare let requireNode: any; if (environment.production) { enableProdMode(); } try { if (requireNode) { Globals.isNwjs = typeof requireNode('nw.gui') !== 'undefined'; } else { Globals.isNwjs = false; } } catch (e) { Globals.isNwjs = false; } console.log('is nwjs: ', Globals.isNwjs); platformBrowserDynamic().bootstrapModule(AppModule);
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/entities/prop.ts
<reponame>45498106/crosscode-map-editor import {CCEntity, InputEvents, ScaleSettings} from './cc-entity'; import {Helper} from '../helper'; import {Fix} from '../../interfaces/props'; export interface PropDef { name: string; size: { x: number; y: number; z: number }; collType: string; fix?: Fix; anims?: { SUB: any[]; frames: any[]; framesGfxOffset: any[]; namedSheets: any; repeat: boolean; shape: string; sheet: string; time: number; }; effects?: { hide: string; sheet: string; show: string; }; } export class Prop extends CCEntity { private attributes = { propType: { type: 'PropType', description: 'Type of prop' }, propAnim: { type: 'EntityAnim', description: 'Animation of prop' }, AG: { type: 'CondAnims', description: 'Animations shown by conditions' }, spawnCondition: { type: 'VarCondition', description: 'Condition for prop to appear', bd: true }, HL: { type: 'VarName', description: 'Variable to be changed when prop is touched', R: true }, interact: { type: 'PropInteract', description: 'Interaction for this property', bd: true, R: true }, jGa: { type: 'Effect', description: 'Effect to show when showing entity', R: true }, Zrb: { type: 'Effect', description: 'Effect to show when hiding entity', R: true }, MB: { type: 'Effect', description: 'Effect to be shown permanently', R: true }, hideCondition: { type: 'VarCondition', description: 'Condition for entity to become transparent', R: true } }; public getAttributes() { return this.attributes; } getScaleSettings(): ScaleSettings { return undefined; } protected setupType(settings: any) { if (!settings.propType) { console.warn('prop without prop type'); return this.generateNoImageType(); } Helper.getJson('data/props/' + settings.propType.sheet, (sheet) => { let prop: PropDef; if (!sheet) { console.warn('prop without sheet', settings); return this.generateNoImageType(); } for (let i = 0; i < sheet.props.length; i++) { const p = sheet.props[i]; if (settings.propType.name === p.name) { prop = p; break; } } if (!prop) { console.error('prop not found: ' + settings.propType.name); return this.generateNoImageType(); } this.anchor.set(0.5, 1); this.entitySettings = <any>{sheets: {fix: []}}; if (prop.fix) { this.entitySettings.sheets.fix[0] = prop.fix; this.entitySettings.sheets.renderMode = prop.fix.renderMode; } else { console.log('sheet not found for prop: ' + prop.name); console.log(this.group.x); console.log(this.group.y); return this.generateNoImageType(0, 255, 60); } this.entitySettings.baseSize = prop.size; this.entitySettings.collType = prop.collType; this.updateSettings(); }); } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/entities/entity-manager.ts
import {CCEntity, InputEvents} from './cc-entity'; import {Sortable} from '../../interfaces/sortable'; import {Helper} from '../helper'; import {CCMap} from '../tilemap/cc-map'; import {CrossCodeMap, MapEntity} from '../../interfaces/cross-code-map'; import {Vec2} from '../vec2'; import {GlobalEventsService} from '../../global-events.service'; import {Globals} from '../../globals'; import {SelectionBox} from './selection-box'; import {EntityRegistryService} from './entity-registry.service'; enum MouseButtons { Left, Right, Middle } export class EntityManager extends Phaser.Plugin implements Sortable { public zIndex: number; private keyBindings: Phaser.SignalBinding[] = []; private map: CCMap; private entities: CCEntity[]; private multiSelectKey: Phaser.Key; private copyKey: Phaser.Key; private pasteKey: Phaser.Key; private deleteKey: Phaser.Key; private gridKey: Phaser.Key; private visibilityKey: Phaser.Key; private inputEvents: InputEvents = {}; private selectedEntities: CCEntity[]; private copyEntities: CCEntity[]; private globalEvents: GlobalEventsService; private selectionBox: SelectionBox; // image to receive input behind the sprites private inputImg: Phaser.Image; constructor(game: Phaser.Game, parent) { super(game, parent); this.active = true; this.hasUpdate = true; this.zIndex = 900; this.selectedEntities = []; this.multiSelectKey = game.input.keyboard.addKey(Phaser.Keyboard.SHIFT); this.copyKey = game.input.keyboard.addKey(Phaser.Keyboard.C); this.pasteKey = game.input.keyboard.addKey(Phaser.Keyboard.V); this.deleteKey = game.input.keyboard.addKey(Phaser.Keyboard.DELETE); this.gridKey = game.input.keyboard.addKey(Phaser.Keyboard.G); this.visibilityKey = game.input.keyboard.addKey(Phaser.Keyboard.R); game.input.keyboard.removeKeyCapture(this.copyKey.keyCode); game.input.keyboard.removeKeyCapture(this.pasteKey.keyCode); game.input.keyboard.removeKeyCapture(this.deleteKey.keyCode); game.input.keyboard.removeKeyCapture(this.gridKey.keyCode); game.input.keyboard.removeKeyCapture(this.visibilityKey.keyCode); this.selectionBox = new SelectionBox(this.game); this.inputImg = game.add.image(-9999, -9999); this.inputImg.width = 999999; this.inputImg.height = 999999; let buttonPressed: MouseButtons; this.inputImg.events.onInputDown.add((e, pointer) => { if (pointer.middleButton.isDown) { buttonPressed = MouseButtons.Middle; } else if (pointer.leftButton.isDown) { buttonPressed = MouseButtons.Left; this.selectionBox.onInputDown(Helper.screenToWorld(pointer)); } else if (pointer.rightButton.isDown) { buttonPressed = MouseButtons.Right; } }); this.inputImg.events.onInputUp.add((e, pointer) => { if (buttonPressed === MouseButtons.Middle) { return; } if (buttonPressed === MouseButtons.Right) { this.selectEntity(null); this.showAddEntityMenu(); } if (buttonPressed === MouseButtons.Left) { const entities = this.selectionBox.onInputUp(); if (!this.multiSelectKey.isDown) { this.selectEntity(null, false); } entities.forEach(entity => { this.selectEntity(entity, true); }); } }); this.inputEvents.onLeftClick = (e, pointer) => { this.selectEntity(e, this.multiSelectKey.isDown); }; this.inputEvents.onInputDown = (e, pointer) => { if (pointer.leftButton.isDown) { // to allow instant drag of a single entity if (this.selectedEntities.indexOf(e) < 0) { if (!this.multiSelectKey.isDown) { this.selectEntity(e); } } this.selectedEntities.forEach(entity => { entity.startOffset = Vec2.sub(Helper.screenToWorld(pointer), entity.group, true); entity.isDragged = true; }); } }; this.inputEvents.onInputUp = (e, pointer, isOver) => { this.selectedEntities.forEach(entity => { entity.isDragged = false; }); }; } /** generates all entities and adds proper input handling */ initialize(ccMap: CCMap, mapInput: CrossCodeMap) { this.map = ccMap; if (this.entities) { this.entities.forEach(e => e.destroy()); } this.entities = []; if (mapInput.entities) { mapInput.entities.forEach((entity, i) => { // if (entity.type === 'Prop' || entity.type === 'ScalableProp') { // return; // } // if (i > 0) { // return; // } this.generateEntity(entity); }); } } update() { this.selectionBox.update(this.entities); } selectEntity(entity: CCEntity, multiple = false) { if (multiple) { const i = this.selectedEntities.indexOf(entity); if (i >= 0) { entity.setSelected(false); this.selectedEntities.splice(i, 1); } else { entity.setSelected(true); this.selectedEntities.push(entity); } } else if (this.selectedEntities[0] !== entity || this.selectedEntities.length !== 1) { this.globalEvents.selectedEntity.next(entity); } } generateEntity(entity: MapEntity): CCEntity { const registry: EntityRegistryService = this.game['EntityRegistryService']; const entityClass = registry.getEntity(entity.type); const ccEntity = new entityClass(this.game, this.map, entity.x, entity.y, this.inputEvents, entity.type); ccEntity.setSettings(entity.settings); ccEntity.level = entity.level; this.entities.push(ccEntity); return ccEntity; } setGlobalEvents(globalEvents: GlobalEventsService) { this.globalEvents = globalEvents; this.globalEvents.selectedEntity.subscribe(entity => { this.selectedEntities.forEach(e => e.setSelected(false)); this.selectedEntities = []; if (entity) { entity.setSelected(true); this.selectedEntities.push(entity); } }); this.globalEvents.generateNewEntity.subscribe(entity => { // TODO: better generate level from collision tiles entity.level = this.map.masterLevel; const e = this.generateEntity(entity); // level offset const offset = this.map.levels[e.details.level.level]; e.group.y += offset.height; // entity manager is activated if (this.inputImg.inputEnabled) { e.setEnableInput(true); this.selectEntity(e); } }); } copy() { console.log(Helper.isInputFocused()); this.copyEntities = this.selectedEntities.slice(); } paste() { if (this.copyEntities.length === 0) { return; } const offset = Vec2.create(this.copyEntities[0].group); offset.y -= this.map.levels[this.copyEntities[0].details.level.level].height; const mousePos = Vec2.create(Helper.screenToWorld(this.game.input.mousePointer)); this.selectEntity(null); this.copyEntities.forEach(e => { const entityDef = e.exportEntity(); Vec2.sub(entityDef, offset); Vec2.add(entityDef, mousePos); const newEntity = this.generateEntity(entityDef); newEntity.setEnableInput(true); this.selectEntity(newEntity, this.copyEntities.length > 1); }); console.log(this.entities); } deleteSelectedEntities() { this.selectedEntities.forEach(e => { const i = this.entities.indexOf(e); this.entities.splice(i, 1); e.destroy(); }); this.selectEntity(null); } deactivate() { this.inputImg.inputEnabled = false; this.keyBindings.forEach(binding => binding.detach()); this.keyBindings = []; if (!this.map) { return; } this.selectEntity(null); this.entities.forEach(entity => { entity.setEnableInput(false); entity.setSelected(false); }); } activate() { this.inputImg.inputEnabled = true; this.inputImg.input.priorityID = 1; this.keyBindings.push(this.gridKey.onDown.add(() => { console.log('grid key down'); console.log(Helper.isInputFocused()); if (Helper.isInputFocused()) { return; } Globals.entitySettings.enableGrid = !Globals.entitySettings.enableGrid; })); this.keyBindings.push(this.deleteKey.onDown.add(() => { if (Helper.isInputFocused()) { return; } this.deleteSelectedEntities(); })); this.keyBindings.push(this.copyKey.onDown.add(() => { if (!this.game.input.keyboard.isDown(Phaser.Keyboard.CONTROL)) { return; } if (Helper.isInputFocused()) { return; } this.copy(); })); this.keyBindings.push(this.pasteKey.onDown.add(() => { if (!this.game.input.keyboard.isDown(Phaser.Keyboard.CONTROL)) { return; } if (Helper.isInputFocused()) { return; } this.paste(); })); this.keyBindings.push(this.visibilityKey.onDown.add(() => { if (Helper.isInputFocused()) { return; } this.entities.forEach(e => { e.group.visible = !e.group.visible; }); })); if (!this.map) { return; } this.entities.forEach(entity => { entity.setEnableInput(true); }); } exportEntities(): MapEntity[] { const out = []; this.entities.forEach(e => out.push(e.exportEntity())); return out; } private showAddEntityMenu() { this.globalEvents.showAddEntityMenu.next({ worldPos: Helper.screenToWorld(this.game.input.mousePointer), definitions: this.game.cache.getJSON('definitions.json', false) }); } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/entities/scalable-prop.ts
<filename>webapp/src/app/shared/phaser/entities/scalable-prop.ts import {CCEntity, InputEvents, ScaleSettings} from './cc-entity'; import {Point, Point3} from '../../interfaces/cross-code-map'; import {Helper} from '../helper'; export interface ScalablePropDef { baseSize: Point3; terrain: string; scalableX: boolean; scalableY: boolean; scalableStep: number; renderHeight?: number; renderMode: string; collType: string; gfx: string; gfxBaseX: number; gfxBaseY: number; patterns: { x: number; y: number; w: number; h: number; xCount: number; yCount: number; }; timePadding: Point; effects: { sheet: string; show: string; hide: string; }; pivot: Point; jsonINSTANCE?: string; srcX?: number; srcY?: number; width?: number; } export class ScalableProp extends CCEntity { private attributes = { propConfig: { type: 'ScalablePropConfig', description: 'Type of Scalable Prop' }, patternOffset: { type: 'Vec2', description: 'Start offset of the repeating pattern in pixels' }, timeOffset: { type: 'Number', description: 'Time offset of the animation' }, spawnCondition: { type: 'VarCondition', description: 'Condition for prop to appear', bd: true }, HL: { type: 'VarName', description: 'Variable to be changed when prop is touched', R: true }, blockNavMap: { type: 'Boolean', sta: 'If true, block path map and update when destroyed' }, hideCondition: { type: 'VarCondition', description: 'Condition for entity to become transparent', R: true } }; private scaleSettings: ScaleSettings = {}; public getAttributes() { return this.attributes; } getScaleSettings(): ScaleSettings { return this.scaleSettings; } protected setupType(settings: any) { if (!settings.propConfig) { console.warn('scalable prop without prop config'); return this.generateNoImageType(); } Helper.getJson('data/scale-props/' + settings.propConfig.sheet, (sheet) => { let prop: ScalablePropDef = sheet.entries[settings.propConfig.name]; if (!prop) { console.error('scale-prop not found: ' + settings.propConfig.name); return this.generateNoImageType(); } this.entitySettings = <any>{}; if (prop.jsonINSTANCE) { const jsonInstance = sheet.jsonTEMPLATES[prop.jsonINSTANCE]; const p = jsonInstance.patterns; this.replaceJsonParams(jsonInstance, prop); prop = jsonInstance; } if (prop.gfx) { this.entitySettings.sheets = { fix: [{ gfx: prop.gfx, x: prop.gfxBaseX + prop.patterns.x, y: prop.gfxBaseY + prop.patterns.y, w: prop.patterns.w, h: prop.patterns.h, renderHeight: prop.renderHeight }], renderMode: prop.renderMode, flipX: false, }; } this.scaleSettings = { scalableX: prop.scalableX, scalableY: prop.scalableY, scalableStep: prop.scalableStep, baseSize: prop.baseSize }; Object.assign(this.entitySettings, this.scaleSettings); this.entitySettings.collType = prop.collType; this.entitySettings.pivot = prop.pivot; this.updateSettings(); }); } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/vec2.ts
<reponame>45498106/crosscode-map-editor // Vector tools (source: http://impactjs.com/forums/impact-engine/vector-math-helper-class/page/1) import {Point} from '../interfaces/cross-code-map'; export class Vec2 { /** * @inline * @param otherVec */ public static create(otherVec) { const res = <Point>{}; res.x = (otherVec && otherVec.x || 0); res.y = (otherVec && otherVec.y || 0); return res; } /** * @inline * @param x * @param y */ public static createC(x, y) { const res = <Point>{}; res.x = (x || 0); res.y = (y || 0); return res; } /** * @inline * @param v1 * @param v2 */ public static assign(v1, v2) { v1.x = (v2.x || 0); v1.y = (v2.y || 0); return v1; } /** * @inline * @param v * @param x * @param y */ public static assignC(v, x, y) { v.x = (x || 0); v.y = (y || 0); return v; } /** * @inline * @param v1 * @param v2 * @param {boolean=} copy */ public static add(v1, v2, copy?) { const res = copy || false ? {} : v1; res.x = (v1.x || 0) + (v2.x || 0); res.y = (v1.y || 0) + (v2.y || 0); return res; } /** * @inline * @param v1 * @param x * @param y * @param {boolean=} copy */ public static addC(v1, x, y, copy?) { const res = copy || false ? {} : v1; y = y === undefined || y === null ? x : y; res.x = (v1.x || 0) + (x || 0); res.y = (v1.y || 0) + (y || 0); return res; } /** * @inline * @param v1 * @param v2 * @param {boolean=} copy */ public static sub(v1, v2, copy?) { const res = copy || false ? {} : v1; res.x = (v1.x || 0) - (v2.x || 0); res.y = (v1.y || 0) - (v2.y || 0); return res; } /** * @inline * @param v1 * @param x * @param y * @param {boolean=} copy */ public static subC(v1, x, y, copy?) { const res = copy ? {} : v1; y = y === undefined || y === null ? x : y; res.x = (v1.x || 0) - (x || 0); res.y = (v1.y || 0) - (y || 0); return res; } /** * @inline * @param v1 * @param v2 * @param {boolean=} copy */ public static mul(v1, v2, copy?) { const res = copy || false ? {} : v1; res.x = (v1.x || 0) * (v2.x || 0); res.y = (v1.y || 0) * (v2.y || 0); return res; } /** * @inline * @param v1 * @param x * @param y * @param {boolean=} copy */ public static mulC(v1, x, y, copy?) { const res = copy || false ? {} : v1; y = y === undefined || y === null ? x : y; res.x = (v1.x || 0) * (x || 0); res.y = (v1.y || 0) * (y || 0); return res; } /** * @inline * @param v1 * @param f * @param {boolean=} copy */ public static mulF(v1, f, copy?) { const res = copy || false ? {} : v1; res.x = (v1.x || 0) * (f || 0); res.y = (v1.y || 0) * (f || 0); return res; } /** * @inline * @param v1 * @param v2 * @param {boolean=} copy */ public static div(v1, v2, copy?) { const res = copy || false ? {} : v1; res.x = (v1.x || 0) / (v2.x || 0); res.y = (v1.y || 0) / (v2.y || 0); return res; } /** * @inline * @param v1 * @param x * @param y * @param {boolean=} copy */ public static divC(v1, x, y?, copy?) { const res = copy || false ? {} : v1; y = y === undefined || y === null ? x : y; res.x = (v1.x || 0) / (x || 0); res.y = (v1.y || 0) / (y || 0); return res; } /** * @inline * @param v1 * @param v2 */ public static dot(v1, v2) { return (v1.x || 0) * (v2.x || 0) + (v1.y || 0) * (v2.y || 0); } /** * @inline * @param v1 * @param v2 */ public static dotR(v1, v2) { return -(v1.y || 0) * (v2.x || 0) + (v1.x || 0) * (v2.y || 0); } /** * @inline * @param v * @param newLength * @param {boolean=} copy */ public static vlength(v, newLength?, copy?) { const oldLength = Math.sqrt((v.x || 0) * (v.x || 0) + (v.y || 0) * (v.y || 0)); if (newLength) { return Vec2.mulC(v, oldLength ? newLength / oldLength : 1, null, copy); } else { return oldLength; } } /** * @inline * @param v * @param min * @param max * @param {boolean=} copy */ public static limit(v, min, max, copy?) { const length = Vec2.vlength(v); if (length > max) { return Vec2.mulC(v, max / length, null, copy); } else if (length < min) { return Vec2.mulC(v, min / length, null, copy); } else { return copy || false ? Vec2.create(v) : v; } } /** * @inline * @param v * @param {boolean=} copy */ public static normalize(v, copy?) { return Vec2.vlength(v, 1, copy); } /** * @inline * @param v */ public static clockangle(v) { let result = Math.acos(-(v.y || 0) / Vec2.vlength(v)); if (v.x < 0) { result = 2 * Math.PI - result; } return result || 0; } /** * @inline * @param v1 * @param v2 */ public static angle(v1, v2) { const result = Math.acos(Vec2.dot(v1, v2) / ( Vec2.vlength(v1) * Vec2.vlength(v2) )); return result || 0; } /** * @inline * @param v * @param angle * @param {boolean=} copy */ public static rotate(v, angle, copy?) { const res = copy || false ? {} : v; const x = v.x || 0; res.x = Math.cos(angle) * x + Math.sin(angle) * (v.y || 0); res.y = Math.sin(-angle) * x + Math.cos(angle) * (v.y || 0); return res; } /** * @inline * @param v * @param {boolean=} copy */ public static rotate90CW(v, copy?) { const res = copy || false ? {} : v; const x = (v.x || 0); res.x = (v.y || 0); res.y = -x; return res; } /** * @inline * @param v * @param {boolean=} copy */ public static rotate90CCW(v, copy?) { const res = copy || false ? {} : v; const x = (v.x || 0); res.x = -(v.y || 0); res.y = x; return res; } /** * @inline * @param v * @param {boolean=} copy */ public static flip(v, copy?) { const res = copy || false ? {} : v; res.x = -v.x; res.y = -v.y; return res; } /** * @inline * @param v1 * @param v2 */ public static equal(v1, v2) { return v1.x === v2.x && v1.y === v2.y; } /** * @inline * @param v1 * @param v2 */ public static distance(v1, v2) { const x = ((v1.x - v2.x) || 0); const y = ((v1.y - v2.y) || 0); return Math.sqrt(x * x + y * y); } /** * @inline * @param v1 * @param v2 */ public static distance2(v1, v2) { const x = ((v1.x - v2.x) || 0); const y = ((v1.y - v2.y) || 0); return x * x + y * y; } /** * @inline * @param v1 * @param v2 * @param i * @param {boolean=} copy */ public static lerp(v1, v2, i, copy?) { const res = copy || false ? {} : v1; res.x = (v1.x || 0) * (1 - i) + (v2.x || 0) * i; res.y = (v1.y || 0) * (1 - i) + (v2.y || 0) * i; return res; } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/entities/default-entity.ts
import {CCEntity} from './cc-entity'; export class DefaultEntity extends CCEntity { private settings; getAttributes() { const out = {}; Object.keys(this.settings).forEach(key => { out[key] = { type: 'Unknown' }; }); return out; } getScaleSettings() { return null; } protected setupType(settings: any) { this.settings = settings; this.generateNoImageType(); } }
45498106/crosscode-map-editor
webapp/src/app/material.module.ts
<filename>webapp/src/app/material.module.ts import {NgModule} from '@angular/core'; import { MatAutocompleteModule, MatButtonModule, MatCheckboxModule, MatDialogModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatProgressSpinnerModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSnackBarModule, MatTabsModule, MatToolbarModule, MatTooltipModule } from '@angular/material'; const MODULES = [ MatButtonModule, MatTooltipModule, MatCheckboxModule, MatToolbarModule, MatRippleModule, MatMenuModule, MatSidenavModule, MatAutocompleteModule, MatDialogModule, MatTabsModule, MatInputModule, MatSelectModule, MatSnackBarModule, MatProgressSpinnerModule, MatListModule, MatIconModule ]; @NgModule({ imports: MODULES, exports: MODULES, }) export class MaterialModule { }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/tilemap/tile-drawer.ts
import {CCMapLayer} from './cc-map-layer'; import {Globals} from '../../globals'; import {SortableGroup} from '../../interfaces/sortable'; import {Helper} from '../helper'; import {MapLayer, Point} from '../../interfaces/cross-code-map'; import {Vec2} from '../vec2'; import {CCMap} from './cc-map'; import {MapLoaderService} from '../../map-loader.service'; import {HistoryState} from '../../../history/state-history.service'; import {GlobalEventsService} from '../../global-events.service'; export class TileDrawer extends Phaser.Plugin { private layer: CCMapLayer; private selectedTiles: { tiles: { id: number; offset: Point }[], img: Phaser.Image, tilesetSize: Point, bitmap: Phaser.BitmapData, imgName: string }; private toggleTilemapKey: Phaser.Key; private graphics: Phaser.Graphics; private group: SortableGroup; private tilesetImg: Phaser.Image; private tileSelectMap: CCMapLayer; private keyBindings: Phaser.SignalBinding[] = []; private rightClickStart: Point; private rightClickEnd: Point; private renderLayersTransparent = false; private transparentKey: Phaser.Key; private visibilityKey: Phaser.Key; private fillKey: Phaser.Key; private map: CCMap; constructor(game: Phaser.Game, parent) { super(game, parent); this.active = true; this.hasUpdate = true; this.toggleTilemapKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); this.fillKey = game.input.keyboard.addKey(Phaser.Keyboard.F); this.transparentKey = game.input.keyboard.addKey(Phaser.Keyboard.R); this.visibilityKey = game.input.keyboard.addKey(Phaser.Keyboard.V); this.game.input.keyboard.removeKeyCapture(this.fillKey.keyCode); this.game.input.keyboard.removeKeyCapture(this.transparentKey.keyCode); this.group = game.add.group(); // needs custom property because z gets reset to the index after a sort is done this.group.zIndex = 1000; this.graphics = game.add.graphics(0, 0); this.setDefaultStyle(); this.graphics.drawRect(0, 0, Globals.TILE_SIZE, Globals.TILE_SIZE); this.selectedTiles = <any>{}; this.selectedTiles.tiles = []; this.selectedTiles.bitmap = game.make.bitmapData(30 * Globals.TILE_SIZE, 30 * Globals.TILE_SIZE, 'tileDrawer'); this.selectedTiles.img = game.make.image(0, 0); this.selectedTiles.img.loadTexture(this.selectedTiles.bitmap); this.selectedTiles.img.alpha = 0.5; this.group.add(this.graphics); this.group.add(this.selectedTiles.img); } selectLayer(selectedLayer: CCMapLayer, map?: CCMap) { this.layer = selectedLayer; this.map = map || this.map; this.setLayerAlpha(); // hide when no layer selected or has no tileset if (!selectedLayer || !selectedLayer.details.tilesetName) { this.group.visible = false; return; } Globals.zIndexUpdate = true; this.group.visible = true; this.tilesetImg = this.game.make.image(0, 0, selectedLayer.details.tilesetName); this.tilesetImg.crop(new Phaser.Rectangle(0, 0, Globals.TILE_SIZE * 10, Globals.TILE_SIZE * 10)); const tilesetSize = Helper.getTilesetSize(this.game.cache.getImage(selectedLayer.details.tilesetName)); this.selectedTiles.tilesetSize = tilesetSize; // create tileset selector map if (this.tileSelectMap) { this.tileSelectMap.destroy(); this.group.remove(this.tileSelectMap); } const details: MapLayer = <MapLayer>{}; details.width = tilesetSize.x; details.height = tilesetSize.y; details.tilesetName = selectedLayer.details.tilesetName; details.tilesize = Globals.TILE_SIZE; details.data = new Array(details.height); let counter = 1; for (let y = 0; y < details.height; y++) { details.data[y] = []; for (let x = 0; x < details.width; x++) { details.data[y][x] = counter; counter++; } } this.tileSelectMap = new CCMapLayer(this.game, details); this.tileSelectMap.backgroundColor = {r: 255, g: 128, b: 0, a: 1}; this.tileSelectMap.renderAll(); this.tileSelectMap.visible = false; this.group.add(this.tileSelectMap, false, 0); } update() { const graphics = this.graphics; const game = this.game; graphics.visible = true; // hide cursor when no map loaded if (!this.layer) { graphics.visible = false; return; } const p = Helper.screenToTile(game.input.mousePointer); // render selection border if (this.rightClickStart) { this.graphics.clear(); this.setDefaultStyle(); this.clampToBounds(this.tileSelectMap.visible ? this.tileSelectMap : this.layer, p); this.rightClickEnd = p; const diff = Vec2.sub(p, this.rightClickStart, true); const start = {x: 0, y: 0}; if (diff.x >= 0) { diff.x++; } else { start.x = Globals.TILE_SIZE; diff.x--; } if (diff.y >= 0) { diff.y++; } else { start.y = Globals.TILE_SIZE; diff.y--; } this.graphics.drawRect( start.x, start.y, diff.x * Globals.TILE_SIZE, diff.y * Globals.TILE_SIZE); return; } // position tile drawer border to cursor graphics.x = p.x * Globals.TILE_SIZE; graphics.y = p.y * Globals.TILE_SIZE; this.selectedTiles.img.x = graphics.x; this.selectedTiles.img.y = graphics.y; // draw tiles (skip when tile selector is open) if (game.input.mousePointer.leftButton.isDown && !this.tileSelectMap.visible) { this.selectedTiles.tiles.forEach(tile => { const finalPos = { x: p.x + tile.offset.x, y: p.y + tile.offset.y }; if (this.isInBounds(this.layer, finalPos)) { this.layer.drawTile(finalPos.x, finalPos.y, tile.id); } }); } } deactivate() { this.keyBindings.forEach(binding => binding.detach()); this.keyBindings = []; this.game.input.keyboard.removeKeyCapture(this.toggleTilemapKey.keyCode); } activate() { this.keyBindings.push(this.game.input.mousePointer.leftButton.onUp.add(() => { const ccmap: CCMap = <any>this.game['MapLoaderService'].tileMap.getValue(); const stateContainer = <any> this.game['StateHistoryService'].selectedState.getValue(); if (!stateContainer.state) { return; } const curr = stateContainer.state.state; const state = ccmap.exportMap(); const currJson = JSON.stringify(curr); const stateJson = JSON.stringify(state); if (currJson !== stateJson) { this.game['StateHistoryService'].saveState({ name: 'Tile Drawer', icon: 'create', state: JSON.parse(stateJson) }); } })); this.keyBindings.push(this.game.input.mousePointer.rightButton.onDown.add(() => this.onMouseRightDown())); this.keyBindings.push(this.game.input.mousePointer.rightButton.onUp.add(() => this.onMouseRightUp())); this.keyBindings.push(this.toggleTilemapKey.onDown.add(() => this.toggleTileSelectorMap())); this.keyBindings.push(this.fillKey.onDown.add(() => { if (!Helper.isInputFocused()) { this.fill(); } })); this.keyBindings.push(this.transparentKey.onDown.add(() => { if (!Helper.isInputFocused()) { this.renderLayersTransparent = !this.renderLayersTransparent; this.setLayerAlpha(); } })); this.keyBindings.push(this.visibilityKey.onDown.add(() => { if (!Helper.isInputFocused()) { const events: GlobalEventsService = this.game['GlobalEventsService']; events.toggleVisibility.next(); } })); this.game.input.keyboard.addKeyCapture(this.toggleTilemapKey.keyCode); } private setLayerAlpha() { if (this.map) { this.map.layers.forEach(layer => { layer.alpha = this.renderLayersTransparent ? 0.5 : 1; }); if (this.layer) { this.layer.alpha = 1; } } } private toggleTileSelectorMap() { const game = this.game; if (!this.layer) { this.tileSelectMap.visible = false; return; } this.tileSelectMap.visible = !this.tileSelectMap.visible; if (this.tileSelectMap.visible) { const p2 = Helper.screenToTile(0, 0); Vec2.addC(p2, 1, 1); Vec2.assign(this.tileSelectMap, p2); Vec2.mulF(this.tileSelectMap, Globals.TILE_SIZE); } } private onMouseRightDown() { if (!this.layer) { return; } // only start tile copy when cursor in bounds const p = Helper.screenToTile(this.game.input.mousePointer); if (!this.isInBounds(this.tileSelectMap.visible ? this.tileSelectMap : this.layer, p)) { return; } this.rightClickStart = p; } private onMouseRightUp() { if (!this.layer) { return; } this.selectedTiles.tiles = []; this.graphics.clear(); this.setDefaultStyle(); // cancel current selection when out of bounds if (!this.rightClickStart) { this.graphics.drawRect(0, 0, Globals.TILE_SIZE, Globals.TILE_SIZE); this.selectedTiles.tiles.push({id: 0, offset: {x: 0, y: 0}}); this.selectedTiles.bitmap.clear(); return; } // select tiles const start = this.rightClickStart; const end = this.rightClickEnd; let data = this.layer.details.data; if (this.tileSelectMap.visible) { data = this.tileSelectMap.details.data; const offset = Vec2.create(this.tileSelectMap); Vec2.divC(offset, Globals.TILE_SIZE); Vec2.sub(start, offset); Vec2.sub(end, offset); } const smaller = { x: Math.min(start.x, end.x), y: Math.min(start.y, end.y) }; const bigger = { x: Math.max(start.x, end.x), y: Math.max(start.y, end.y) }; for (let x = smaller.x; x <= bigger.x; x++) { for (let y = smaller.y; y <= bigger.y; y++) { this.selectedTiles.tiles.push({ id: data[y][x], offset: {x: x - smaller.x, y: y - smaller.y} }); // console.log('pos', {x: x, y: y}); } } console.log(this.selectedTiles.tiles[0].id); this.renderPreview(data, smaller); this.graphics.drawRect( 0, 0, (bigger.x + 1 - smaller.x) * Globals.TILE_SIZE, (bigger.y + 1 - smaller.y) * Globals.TILE_SIZE); this.rightClickStart = null; this.rightClickEnd = null; } private renderPreview(data: number[][], offset: Point) { const tiles = this.selectedTiles; const bitmap = tiles.bitmap; bitmap.clear(); tiles.tiles.forEach(tile => { const finalPos = Vec2.add(tile.offset, offset, true); const id = data[finalPos.y][finalPos.x]; const pos = Helper.getTilePos(tiles.tilesetSize, id); if (id === 0) { return; } this.tilesetImg.cropRect.x = pos.x * Globals.TILE_SIZE; this.tilesetImg.cropRect.y = pos.y * Globals.TILE_SIZE; this.tilesetImg.cropRect.width = Globals.TILE_SIZE; this.tilesetImg.cropRect.height = Globals.TILE_SIZE; this.tilesetImg.updateCrop(); bitmap.draw( this.tilesetImg, tile.offset.x * Globals.TILE_SIZE, tile.offset.y * Globals.TILE_SIZE, Globals.TILE_SIZE, Globals.TILE_SIZE ); }); } private setDefaultStyle() { this.graphics.lineStyle(1, 0xFFFFFF, 0.7); } private isInBounds(layer: CCMapLayer, p: Point): boolean { const offset = Vec2.create(layer); Vec2.divC(offset, Globals.TILE_SIZE); return p.x >= offset.x && p.y >= offset.y && p.x < layer.details.width + offset.x && p.y < layer.details.height + offset.y; } private clampToBounds(layer: CCMapLayer, p: Point) { const offset = Vec2.create(layer); Vec2.divC(offset, Globals.TILE_SIZE); p.x = Helper.clamp(p.x, offset.x, layer.details.width - 1 + offset.x); p.y = Helper.clamp(p.y, offset.y, layer.details.height - 1 + offset.y); } private fill() { if (!this.layer || this.tileSelectMap.visible) { return; } const game = this.game; const p = Helper.screenToTile(game.input.mousePointer); if (this.selectedTiles.tiles.length > 0) { this.layer.fill(this.selectedTiles.tiles[0].id, p); } } }
45498106/crosscode-map-editor
webapp/src/app/history/history.component.ts
<reponame>45498106/crosscode-map-editor import {Component, ElementRef, OnInit, ViewChild, ViewEncapsulation} from '@angular/core'; import {HistoryState, StateHistoryService} from './state-history.service'; @Component({ selector: 'app-history', templateUrl: './history.component.html', styleUrls: ['./history.component.scss'], encapsulation: ViewEncapsulation.None }) export class HistoryComponent implements OnInit { @ViewChild('listContainer') list: ElementRef; states: HistoryState[] = []; selected; selectedIndex; constructor(private stateHistory: StateHistoryService) { stateHistory.states.subscribe(states => { this.states = states; this.updateSelected(this.selected); if (!this.list) { return; } setTimeout(() => { const el = this.list.nativeElement; console.log(el); el.scrollTop = el.scrollHeight * 2; }, 0); }); stateHistory.selectedState.subscribe(container => { this.updateSelected(container); }); } ngOnInit() { } updateSelected(container) { if (!container) { return; } this.selected = container; this.selectedIndex = this.states.indexOf(container.state); } create() { this.stateHistory.saveState({ state: <any>{name: Math.random()}, name: '' + Math.random().toFixed(7), icon: 'house' }); } undo() { this.stateHistory.undo(); } redo() { this.stateHistory.redo(); } selectState(state) { this.stateHistory.selectedState.next({state: state}); } }
45498106/crosscode-map-editor
webapp/src/app/sidenav/entities/widgets/vec2-widget/vec2-widget.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {AbstractWidget} from '../abstract-widget'; import {Point} from '../../../../shared/interfaces/cross-code-map'; @Component({ selector: 'app-vec2-widget', templateUrl: './vec2-widget.component.html', styleUrls: ['./vec2-widget.component.scss', '../../entities.component.scss'] }) export class Vec2WidgetComponent extends AbstractWidget implements OnInit { @Input() step = 1; @Input() minSize: Point = {x: -9999, y: -9999}; @Input() enableX = true; @Input() enableY = true; constructor() { super(); } ngOnInit() { } setVal(key, val) { val -= val % this.step; const setting = this.entity.details.settings[this.key]; setting[key] = Math.max(val, this.minSize[key]); this.updateType(); } }
45498106/crosscode-map-editor
webapp/src/app/sidenav/entities/widgets/boolean-widget/boolean-widget.component.ts
import {Component, OnInit} from '@angular/core'; import {AbstractWidget} from '../abstract-widget'; @Component({ selector: 'app-boolean-widget', templateUrl: './boolean-widget.component.html', styleUrls: ['./boolean-widget.component.scss', '../../entities.component.scss'] }) export class BooleanWidgetComponent extends AbstractWidget implements OnInit { constructor() { super(); } ngOnInit() { } }
45498106/crosscode-map-editor
webapp/src/app/sidenav/entities/widgets/json-widget/json-widget.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {AbstractWidget} from '../abstract-widget'; import {JsonEditorComponent} from '../../../../shared/json-editor/json-editor.component'; import {MatDialog} from '@angular/material'; @Component({ selector: 'app-json-widget', templateUrl: './json-widget.component.html', styleUrls: ['./json-widget.component.scss', '../../entities.component.scss'] }) export class JsonWidgetComponent extends AbstractWidget implements OnInit { @Input() custom; private timer; json = JSON; constructor(private dialog: MatDialog) { super(); } ngOnInit() { } openJsonEditor() { const ref = this.dialog.open(JsonEditorComponent, { data: { val: this.custom ? this.custom[this.key] : this.entity.details.settings[this.key], key: this.key } }); ref.afterClosed().subscribe(res => { if (res) { this.setCustomSetting(this.key, JSON.stringify(res)); } }); } setCustomSetting(key, value) { if (this.timer !== undefined) { clearTimeout(this.timer); } this.timer = setTimeout(() => { value = JSON.parse(value); if (this.custom) { this.custom[key] = value; } else { this.entity.details.settings[key] = value; } this.updateType(); }, 500); } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/tilemap/cc-map.ts
<reponame>45498106/crosscode-map-editor import {Attributes, CrossCodeMap, MapLayer, Point} from '../../interfaces/cross-code-map'; import {CCMapLayer} from './cc-map-layer'; import {Globals} from '../../globals'; import {EntityManager} from '../entities/entity-manager'; import {Helper} from '../helper'; import {StateHistoryService} from '../../../history/state-history.service'; import {Subscription} from 'rxjs'; import {GlobalEventsService} from '../../global-events.service'; import {PhaserEventsService} from '../phaser-events.service'; export class CCMap { name: string; levels: { height: number }[]; mapWidth: number; mapHeight: number; masterLevel: number; layers: CCMapLayer[] = []; attributes: Attributes; screen: Point; private historySub: Subscription; private offsetSub: Subscription; private keyBinding: Phaser.SignalBinding; filename: string; private props = [ 'name', 'levels', 'mapWidth', 'mapHeight', 'masterLevel', 'attributes', 'screen', ]; private inputLayers: MapLayer[]; constructor(private game: Phaser.Game) { const stateHistory: StateHistoryService = game['StateHistoryService']; this.historySub = stateHistory.selectedState.subscribe(container => { if (!container || !container.state) { return; } const i = this.layers.indexOf(this.game['MapLoaderService'].selectedLayer.getValue()); this.loadMap(Helper.copy(container.state.state), true); if (i >= 0 && this.layers.length > i) { this.game['MapLoaderService'].selectedLayer.next(this.layers[i]); } }); const undoKey = game.input.keyboard.addKey(Phaser.Keyboard.Z); this.keyBinding = undoKey.onDown.add(() => { if (Helper.isInputFocused()) { return; } if (game.input.keyboard.isDown(Phaser.KeyCode.CONTROL)) { if (game.input.keyboard.isDown(Phaser.KeyCode.SHIFT)) { stateHistory.redo(); } else { stateHistory.undo(); } } }); const globalEvents: GlobalEventsService = this.game['GlobalEventsService']; this.offsetSub = globalEvents.offsetMap.subscribe(offset => this.offsetMap(offset)); } destroy() { this.historySub.unsubscribe(); this.offsetSub.unsubscribe(); this.keyBinding.detach(); } loadMap(map: CrossCodeMap, skipInit = false) { const game = this.game; this.props.forEach(prop => this[prop] = map[prop]); this.filename = map.filename; this.inputLayers = map.layer; // cleanup everything before loading new map this.layers.forEach(layer => layer.destroy()); this.layers = []; // load needed assets for sprite props console.log(map.entities.length); // generate Map Layers if (this.inputLayers) { this.inputLayers.forEach(layer => { const ccLayer = new CCMapLayer(game, layer); this.layers.push(ccLayer); }); this.inputLayers = null; } // generate Map Entities game.plugins.plugins.forEach(plugin => { if (plugin instanceof EntityManager) { (<EntityManager>plugin).initialize(this, map); } }); if (!skipInit) { this.game['StateHistoryService'].init({ name: 'load', icon: 'insert_drive_file', state: Helper.copy(this.exportMap()) }); } this.game['MapLoaderService'].tileMap.next(this); this.game['MapLoaderService'].selectedLayer.next(this.layers[0]); } resize(width: number, height: number, skipRender = false) { this.mapWidth = width; this.mapHeight = height; this.layers.forEach(layer => layer.resize(width, height, skipRender)); const events: PhaserEventsService = this.game['PhaserEventsService']; events.updateMapBorder.next(true); } offsetMap(offset: Point, borderTiles = false, skipRender = false) { this.layers.forEach(layer => layer.offsetLayer(offset, borderTiles, skipRender)); } renderAll() { this.layers.forEach(layer => layer.renderAll()); } exportMap(): CrossCodeMap { const out: CrossCodeMap = <any>{}; this.props.forEach(prop => out[prop] = this[prop]); this.game.plugins.plugins.forEach(plugin => { if (plugin instanceof EntityManager) { out.entities = (<EntityManager>plugin).exportEntities(); } }); out.layer = []; this.layers.forEach(l => out.layer.push(l.exportLayer())); return out; } }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/entities/cc-entity.ts
import {Sortable, SortableGroup} from '../../interfaces/sortable'; import {CCMap} from '../tilemap/cc-map'; import {MapEntity, Point, Point3} from '../../interfaces/cross-code-map'; import {Helper} from '../helper'; import * as Phaser from 'phaser-ce'; import {Vec2} from '../vec2'; import {Globals} from '../../globals'; export interface InputEvents { onLeftClick?: (entity: CCEntity, pointer: Phaser.Pointer) => void; onInputDown?: (entity: CCEntity, pointer: Phaser.Pointer) => void; onInputUp?: (entity: CCEntity, pointer: Phaser.Pointer, isOver: boolean) => void; onDragStart?: (entity: CCEntity, pointer: Phaser.Pointer, x: number, y: number) => void; onDragUpdate?: (entity: CCEntity, pointer: Phaser.Pointer, x: number, y: number, point: Point, fromStart: boolean) => void; onDragStop?: (entity: CCEntity, pointer: Phaser.Pointer) => void; } export interface ScaleSettings { scalableX?: boolean; scalableY?: boolean; baseSize?: Point; scalableStep?: number; } export abstract class CCEntity extends Phaser.Image implements Sortable { private map: CCMap; public group: SortableGroup; private levelOffsetGroup: SortableGroup; private boundingBoxOffsetGroup: SortableGroup; private text: Phaser.Text; // for all sprites private images: Phaser.Image[] = []; // input (is handled mostly by entity manager) private collisionBitmap: Phaser.BitmapData; public collisionImage: Phaser.Image; private inputEvents: InputEvents = {}; private selected = false; private leftClickOpts: { timer?: number; pos?: Point; } = {}; // drag public isDragged = false; public startOffset: Point = {}; zIndex: number; details: { level: { level: number, offset: number }, type: string, settings: any }; entitySettings: { collType: string; baseSize: Point3; sheets: { fix: { gfx: string | Phaser.BitmapData; x: number; y: number; w: number; h: number; renderHeight?: number; offsetX?: number; offsetY?: number; flipX?: boolean; flipY?: boolean; }[], offset?: Point; renderMode?: string; singleColor?: boolean; flipX: boolean; } scalableX: boolean; scalableY: boolean; scalableStep: number; pivot: Point; } = <any>{}; protected constructor(game: Phaser.Game, map: CCMap, x: number, y: number, inputEvents: InputEvents, typeName: string) { super(game, 0, 0, null); this.setInputEvents(inputEvents); this.map = map; game.add.existing(this); this.details = <any>{ type: typeName }; this.boundingBoxOffsetGroup = game.add.group(); this.boundingBoxOffsetGroup.add(this); this.levelOffsetGroup = game.add.group(); this.levelOffsetGroup.add(this.boundingBoxOffsetGroup); this.group = game.add.group(); this.group.add(this.levelOffsetGroup); // actual coordinates of the entity this.group.x = Math.round(x); this.group.y = Math.round(y); const collImg = this.game.add.image(); this.collisionImage = collImg; collImg.alpha = 0; this.levelOffsetGroup.add(collImg); collImg.inputEnabled = false; // handle hover input collImg.events.onInputOver.add(() => { if (!this.selected) { collImg.alpha = 0.35; } }); collImg.events.onInputOut.add(() => { if (!this.selected) { collImg.alpha = 0; } }); this.visible = false; this.setEvents(); } updateSettings() { const s = this.entitySettings; const settings = this.details.settings; const game = this.game; this.images.forEach(img => img.destroy()); this.images = []; // bound box offset if (s.baseSize) { this.boundingBoxOffsetGroup.x = s.baseSize.x / 2; this.boundingBoxOffsetGroup.y = s.baseSize.y; } // setup sprite if (s.sheets && s.sheets.fix) { if (s.scalableX || s.scalableY) { // scalable const fix = s.sheets.fix[0]; const width = settings.size.x; const height = (fix.renderHeight || s.baseSize.z) + settings.size.y; for (let x = 0; x < width; x += fix.w) { const imgWidth = Math.min(fix.w, width - x); for (let y = 0; y < height; y += fix.h) { const imgHeight = Math.min(fix.h, height - y); const img = game.add.image(x, -y + settings.size.y + s.baseSize.z, null, null, this.boundingBoxOffsetGroup); img.loadTexture(fix.gfx); img.crop(new Phaser.Rectangle(fix.x, fix.y, imgWidth, imgHeight)); img.anchor.set(0, 1); this.images.push(img); } } this.boundingBoxOffsetGroup.x = 0; this.boundingBoxOffsetGroup.y = -s.baseSize.z; } else { // default s.sheets.fix.forEach(sheet => { const img = this.game.add.image(sheet.offsetX, sheet.offsetY, sheet.gfx, undefined, this.boundingBoxOffsetGroup); img.crop(new Phaser.Rectangle(sheet.x, sheet.y, sheet.w, sheet.h)); img.anchor.set(0.5, 1); img.scale.set(sheet.flipX ? -1 : 1, sheet.flipY ? -1 : 1); this.images.push(img); }); if (s.sheets.offset) { this.images.forEach(img => Vec2.add(img, s.sheets.offset)); } if (s.sheets.flipX) { this.images.forEach(img => img.scale.x *= -1); } } if (s.sheets.renderMode === 'lighter') { this.images.forEach(img => img.blendMode = PIXI.blendModes.ADD); } else if (s.sheets.renderMode === 'source-over') { // TODO: no idea what that actually is console.warn('renderMode source-over found'); } } this.drawBoundingBox(); } set level(level: any) { const details = this.details; if (typeof level === 'object') { details.level = level; } else { details.level = { level: level, offset: 0 }; } this.updateLevel(); } updateLevel() { this.updateZIndex(); const level = this.map.levels[this.details.level.level]; let height = 0; if (level) { height = level.height; } const offset = this.details.level.offset; this.levelOffsetGroup.y = -(height + offset); } // TODO: refactor setSettings(settings: any) { this.details.settings = settings; this.updateType(); } setEnableInput(enable: boolean) { if (!this.collisionImage) { return; } this.collisionImage.inputEnabled = enable; this.collisionImage.alpha = 0; this.collisionImage.visible = enable; if (enable) { this.collisionImage.input.priorityID = 10; } } setSelected(selected: boolean) { this.selected = selected; if (this.collisionImage) { this.collisionImage.alpha = selected ? 0.6 : 0; } } destroy() { this.group.destroy(); this.levelOffsetGroup.destroy(); this.boundingBoxOffsetGroup.destroy(); if (this.collisionBitmap) { this.collisionBitmap.destroy(); } if (this.text) { this.text.destroy(); } super.destroy(); } update() { super.update(); this.leftClickOpts.timer += this.game.time.elapsed; if (this.isDragged) { const p = Helper.screenToWorld(this.game.input.mousePointer); this.group.x = Math.round(p.x - this.startOffset.x); this.group.y = Math.round(p.y - this.startOffset.y); const settings = Globals.entitySettings; if (settings.enableGrid) { const diffX = this.group.x % settings.gridSize; if (diffX * 2 < settings.gridSize) { this.group.x -= diffX; } else { this.group.x += settings.gridSize - diffX; } const diffY = this.group.y % settings.gridSize; if (diffY * 2 < settings.gridSize) { this.group.y -= diffY; } else { this.group.y += settings.gridSize - diffY; } } this.updateZIndex(); } } updateZIndex() { let zIndex = this.details.level.level * 10 + 1; // TODO: hack to display OLPlatform over objects because right now Object Layer is always on level 10 if (this.details.type === 'OLPlatform') { zIndex += 100; } // sort entities by y when on same level zIndex += this.group.y * 0.000001; this.group.zIndex = zIndex; Globals.zIndexUpdate = true; } exportEntity(): MapEntity { const out = { type: this.details.type, x: this.group.x, y: this.group.y, level: this.details.level.offset ? this.details.level : this.details.level.level, settings: this.details.settings }; return JSON.parse(JSON.stringify(out)); } public abstract getScaleSettings(): ScaleSettings; public abstract getAttributes(); protected abstract setupType(settings: any); public updateType() { const settings = this.details.settings; this.setupType(settings); /* if (type === 'Prop' && settings.propType) { Helper.getJson('data/props/' + settings.propType.sheet, (sheet) => { let prop: PropDef; for (let i = 0; i < sheet.props.length; i++) { const p = sheet.props[i]; if (settings.propType.name === p.name) { prop = p; break; } } if (!prop) { console.error('prop not found: ' + settings.propType.name); return this.generateUndefinedType(); } this.anchor.y = 1; this.anchor.x = 0.5; this.entitySettings = <any>{sheets: {fix: []}}; if (prop.fix) { this.entitySettings.sheets.fix[0] = prop.fix; this.entitySettings.sheets.renderMode = prop.fix.renderMode; } else { console.log('sheet not found for prop: ' + prop.name); console.log(this.group.x); console.log(this.group.y); return this.generateUndefinedType(0, 255, 60); } this.entitySettings.baseSize = prop.size; this.entitySettings.collType = prop.collType; this.updateSettings(); }); } else if (type === 'ScalableProp' && settings.propConfig) { Helper.getJson('data/scale-props/' + settings.propConfig.sheet, (sheet) => { let prop: ScalableProp = sheet.entries[settings.propConfig.name]; if (!prop) { console.error('scale-prop not found: ' + settings.propConfig.name); return this.generateUndefinedType(); } this.entitySettings = <any>{}; if (prop.jsonINSTANCE) { const jsonInstance = sheet.jsonTEMPLATES[prop.jsonINSTANCE]; const p = jsonInstance.patterns; this.replaceJsonParams(jsonInstance, prop); prop = jsonInstance; } if (prop.gfx) { this.entitySettings.sheets = { fix: [{ gfx: prop.gfx, x: prop.gfxBaseX + prop.patterns.x, y: prop.gfxBaseY + prop.patterns.y, w: prop.patterns.w, h: prop.patterns.h }], renderMode: prop.renderMode, flipX: false, }; } this.entitySettings.scalableX = prop.scalableX; this.entitySettings.scalableY = prop.scalableY; this.entitySettings.scalableStep = prop.scalableStep; this.entitySettings.baseSize = prop.baseSize; this.entitySettings.collType = prop.collType; this.entitySettings.pivot = prop.pivot; this.updateSettings(); }); } else { // other entities; const def = this.definition; if (!def.definitions && !def.definitionRef) { return this.generateUndefinedType(); } this.entitySettings = <any>{sheets: {}}; if (def.scalableX || def.scalableY) { this.entitySettings.scalableX = def.scalableX; this.entitySettings.scalableY = def.scalableY; } else { this.anchor.y = 1; this.anchor.x = 0.5; } if (def.definitionRef) { let defKey = def.definitionRef; let matched: string[] | string; // replace vars while (true) { matched = defKey.split('${')[1]; if (!matched) { break; } matched = matched.split('}'); if (matched.length === 1) { break; } matched = matched[0]; let val = Helper.deepFind(matched, settings); if (val) { val = val.replace('.', '/'); } defKey = defKey.replace('${' + matched + '}', val); } Helper.getJson(defKey, json => { if (!json) { return this.generateUndefinedType(); } const animKey = 'data/animations/' + json.anims.replace('.', '/'); Helper.getJson(animKey, anim => { const namedSheet = anim.namedSheets.move; if (!namedSheet) { return this.generateUndefinedType(); } const sheets = this.entitySettings.sheets; sheets.fix = [{ gfx: namedSheet.src, x: (namedSheet.offX || 0), y: (namedSheet.offY || 0), w: namedSheet.width, h: namedSheet.height, }]; this.entitySettings.baseSize = {x: 16, y: 16, z: Math.abs(namedSheet.height - 16)}; this.updateSettings(); }); }); } else { let attr = settings[def.definitionAttribute]; if (!attr) { attr = 'default'; } const entityDef = def.definitions[attr]; if (!entityDef) { return this.generateUndefinedType(); } this.entitySettings.baseSize = entityDef.size; if (settings.zHeight) { this.entitySettings.baseSize.z = settings.zHeight; } else if (settings.wallZHeight) { this.entitySettings.baseSize.z = settings.wallZHeight; } if (entityDef.fix) { this.entitySettings.sheets.fix = entityDef.fix; this.entitySettings.sheets.flipX = entityDef.flipX; this.entitySettings.sheets.offset = entityDef.offset; } else { const c = entityDef.color || {r: 150, g: 0, b: 255, a: 0.5}; this.generateSingleColorSheet(c.r, c.g, c.b, c.a); } this.updateSettings(); } } */ } public generateNoImageType(r?: number, g?: number, b?: number, a?: number) { const settings = this.details.settings; const baseSize = settings.size || {x: 16, y: 16}; baseSize.z = settings.zHeight || settings.wallZHeight || 0; this.entitySettings = <any>{}; this.entitySettings.baseSize = baseSize; const scaleSettings = this.getScaleSettings(); if (scaleSettings && (scaleSettings.scalableX || scaleSettings.scalableY)) { this.entitySettings.scalableX = scaleSettings.scalableX; this.entitySettings.scalableY = scaleSettings.scalableY; } else { this.anchor.y = 1; this.anchor.x = 0.5; } this.generateSingleColorSheet(r || 155, g || 60, b || 40); this.updateSettings(); } private generateSingleColorSheet(r: number, g: number, b: number, a?: number) { const size = this.entitySettings.baseSize; const singleColor = this.game.make.bitmapData(size.x, size.y); singleColor.fill(r, g, b, a || 0.5); this.entitySettings.sheets = { fix: [{ gfx: singleColor, x: 0, y: 0, w: size.x, h: size.y, }], singleColor: true, flipX: false, }; } protected replaceJsonParams(jsonInstance, prop: any) { Object.entries(jsonInstance).forEach(([key, value]) => { if (value['jsonPARAM']) { jsonInstance[key] = prop[value['jsonPARAM']]; return; } if (typeof value === 'object') { this.replaceJsonParams(value, prop); } }); } private setInputEvents(inputEvents: InputEvents) { const events = this.inputEvents; const input = inputEvents; events.onInputDown = (o, pointer) => { if (pointer.leftButton.isDown) { this.leftClickOpts.timer = 0; this.leftClickOpts.pos = Vec2.create(pointer); } if (input.onInputDown) { input.onInputDown(this, pointer); } }; events.onInputUp = (o, pointer, isOver) => { if (input.onInputUp) { input.onInputUp(this, pointer, isOver); } if (isOver && this.leftClickOpts.timer < 200 && Vec2.distance2(pointer, this.leftClickOpts.pos) < 10) { if (input.onLeftClick) { input.onLeftClick(this, pointer); } } }; } public getBoundingBox(): Phaser.Rectangle { const img = this.collisionImage; const p = Helper.phaserWorldtoWorld(img.world); const rect = new Phaser.Rectangle(p.x, p.y, img.width, img.height); return rect; } private setEvents() { if (!this.collisionImage) { return; } Object.entries(this.inputEvents).forEach(([key, value]) => { if (!value) { return; } if (!this.collisionImage.events[key]) { return; } this.collisionImage.events[key].removeAll(); this.collisionImage.events[key].add(value); }); } private drawBoundingBox() { const s = this.entitySettings; if (this.collisionBitmap) { this.collisionBitmap.destroy(); } const size = Object.assign({}, this.details.settings.size || s.baseSize); try { size.z = size.z || this.details.settings.zHeight || this.details.settings.wallZHeight || s.baseSize.z || 0; } catch (e) { console.log(this); console.error(e); } const inputArea = new Phaser.Rectangle(0, 0, size.x, size.y); this.collisionBitmap = this.game.make.bitmapData(inputArea.width, inputArea.height + size.z); const context = this.collisionBitmap.context; const outline = 'rgba(0,0,0,1)'; const bottomRect = new Phaser.Rectangle(0, size.z, inputArea.width, inputArea.height - 1); // show middle and top part only if entity is not flat if (size.z > 0) { const middleRect = new Phaser.Rectangle(0, inputArea.height, inputArea.width, size.z - 1); Helper.drawRect(context, middleRect, 'rgba(255, 40, 40, 0.5)', outline); const topRect = new Phaser.Rectangle(0, 0, inputArea.width, inputArea.height); Helper.drawRect(context, topRect, 'rgba(255, 255, 40, 1)', outline); Helper.drawRect(context, bottomRect, 'rgba(255, 255, 40, 0.1)', outline); } else { Helper.drawRect(context, bottomRect, 'rgba(255, 255, 40, 1)', outline); } const collImg = this.collisionImage; collImg.x = inputArea.x; collImg.y = inputArea.y - (size.z || 0); collImg.loadTexture(this.collisionBitmap); this.generateText(this.details.settings.name, size); } private generateText(name: string, size: Point) { if (name) { if (!this.text) { this.text = this.game.add.text(0, 0, '', { font: '400 18pt Roboto', fill: 'white', stroke: 'black', strokeThickness: 2 }, this.levelOffsetGroup); this.text.scale.set(0.274); this.text.anchor.set(0.5, 0.5); } this.text.setText(name); this.text.position.set(size.x / 2, size.y / 2); } else if (this.text) { this.text.destroy(); this.text = null; } } }
45498106/crosscode-map-editor
webapp/src/app/sidenav/sidenav.component.ts
import {Component, OnInit, ViewEncapsulation} from '@angular/core'; import {animate, style, transition, trigger} from '@angular/animations'; import {MapLoaderService} from '../shared/map-loader.service'; import {CCMap} from '../shared/phaser/tilemap/cc-map'; import {CCMapLayer} from '../shared/phaser/tilemap/cc-map-layer'; import {EditorView} from '../shared/interfaces/editor-view'; import {GlobalEventsService} from '../shared/global-events.service'; import {MatTabChangeEvent} from '@angular/material'; @Component({ selector: 'app-sidenav', animations: [ trigger('transition', [ transition(':enter', [ style({opacity: 0}), animate('80ms', style({opacity: 1})) ]) ]) ], templateUrl: './sidenav.component.html', styleUrls: ['./sidenav.component.scss'], encapsulation: ViewEncapsulation.None }) export class SidenavComponent implements OnInit { selectedLayer: CCMapLayer; tilemap: CCMap; currentView: EditorView; editorViewEnum = EditorView; constructor(private mapLoader: MapLoaderService, private globalEvents: GlobalEventsService) { } ngOnInit() { this.mapLoader.selectedLayer.subscribe(layer => { if (layer) { this.selectedLayer = layer; } }); this.mapLoader.tileMap.subscribe(tilemap => this.tilemap = tilemap); this.globalEvents.currentView.subscribe(view => this.currentView = view); } tabChanged(event: MatTabChangeEvent) { this.globalEvents.currentView.next(event.index === 0 ? EditorView.Layers : EditorView.Entities); } }
45498106/crosscode-map-editor
webapp/src/app/sidenav/entities/entities.component.ts
import {Component, ComponentFactoryResolver, OnInit, ViewChild, ViewContainerRef} from '@angular/core'; import {CCEntity} from '../../shared/phaser/entities/cc-entity'; import {GlobalEventsService} from '../../shared/global-events.service'; import {MapLoaderService} from '../../shared/map-loader.service'; import {CCMap} from '../../shared/phaser/tilemap/cc-map'; import {HostDirective} from '../../shared/host.directive'; import {AbstractWidget} from './widgets/abstract-widget'; import {WidgetRegistryService} from './widgets/widget-registry.service'; import {Vec2WidgetComponent} from './widgets/vec2-widget/vec2-widget.component'; @Component({ selector: 'app-entities', templateUrl: './entities.component.html', styleUrls: ['./entities.component.scss'] }) export class EntitiesComponent implements OnInit { @ViewChild(HostDirective) appHost: HostDirective; entity: CCEntity; map: CCMap; constructor(private events: GlobalEventsService, private loader: MapLoaderService, private componentFactoryResolver: ComponentFactoryResolver, private widgetRegistry: WidgetRegistryService) { events.selectedEntity.subscribe(e => { // clear focus of input fields to enable phaser inputs again (<HTMLElement>document.activeElement).blur(); this.entity = e; this.loadSettings(e); }); loader.tileMap.subscribe(map => this.map = map); } ngOnInit() { } setLevel(level: number) { this.entity.details.level.level = Number(level); this.entity.updateLevel(); } setOffset(offset: number) { this.entity.details.level.offset = Number(offset); this.entity.updateLevel(); } loadSettings(entity: CCEntity) { console.log(entity); if (!this.appHost) { return; } const ref = this.appHost.viewContainerRef; ref.clear(); if (!entity) { return; } const def = entity.getScaleSettings(); if (def && (def.scalableX || def.scalableY)) { const vec2Widget: Vec2WidgetComponent = <Vec2WidgetComponent>this.generateWidget(entity, 'size', {type: 'Vec2'}, ref); vec2Widget.enableX = def.scalableX; vec2Widget.enableY = def.scalableY; vec2Widget.step = def.scalableStep; vec2Widget.minSize = def.baseSize; // TODO implement scalable prop then delete this /*if (def.type === 'ScalableProp') { vec2Widget.enableX = entity.entitySettings.scalableX; vec2Widget.enableY = entity.entitySettings.scalableY; vec2Widget.step = entity.entitySettings.scalableStep; vec2Widget.minSize = entity.entitySettings.baseSize; } else { vec2Widget.enableX = def.scalableX; vec2Widget.enableY = def.scalableY; vec2Widget.minSize = entity.entitySettings.baseSize; }*/ } Object.entries(entity.getAttributes()).forEach(([key, val]) => { this.generateWidget(entity, key, val, ref); }); } private generateWidget(entity: CCEntity, key: string, val, ref: ViewContainerRef) { const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.widgetRegistry.getWidget(val.type)); const componentRef = ref.createComponent(componentFactory); const instance = <AbstractWidget> componentRef.instance; instance.entity = entity; instance.key = key; instance.attribute = val; return instance; } }
45498106/crosscode-map-editor
webapp/src/app/shared/interfaces/sortable.ts
<reponame>45498106/crosscode-map-editor export interface Sortable { zIndex?: number; } export interface SortableGroup extends Phaser.Group, Sortable { }
45498106/crosscode-map-editor
webapp/src/app/shared/map-loader.service.ts
<filename>webapp/src/app/shared/map-loader.service.ts import {Injectable} from '@angular/core'; import {MatSnackBar} from '@angular/material'; import {Observable, BehaviorSubject} from 'rxjs'; import {CrossCodeMap} from './interfaces/cross-code-map'; import {CCMap} from './phaser/tilemap/cc-map'; import {CCMapLayer} from './phaser/tilemap/cc-map-layer'; @Injectable() export class MapLoaderService { private _map: BehaviorSubject<CrossCodeMap> = new BehaviorSubject(null); tileMap: BehaviorSubject<CCMap> = new BehaviorSubject(null); selectedLayer: BehaviorSubject<CCMapLayer> = new BehaviorSubject(null); constructor(private snackBar: MatSnackBar) { } loadMap(event) { const files: FileList = event.target.files; if (files.length === 0) { return; } const file = files[0]; const reader = new FileReader(); reader.onload = (e: any) => { try { const map = JSON.parse(e.target.result); if (!map.mapHeight) { throw new Error('invalid map'); } map.filename = file.name; this._map.next(map); } catch (e) { console.error(e); this.snackBar.open('Error: ' + e.message, undefined, { duration: 2500 }); return; } }; reader.readAsText(file); } get map(): Observable<CrossCodeMap> { return this._map.asObservable(); } }
45498106/crosscode-map-editor
webapp/src/app/app.module.ts
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppRoutingModule} from './app-routing.module'; import {AppComponent} from './app.component'; import {EditorComponent} from './editor/editor.component'; import {PhaserComponent} from './phaser/phaser.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {ToolbarComponent} from './toolbar/toolbar.component'; import {FlexLayoutModule} from '@angular/flex-layout'; import {SidenavComponent} from './sidenav/sidenav.component'; import {FormsModule} from '@angular/forms'; import {LayersComponent} from './sidenav/layers/layers.component'; import {EntitiesComponent} from './sidenav/entities/entities.component'; import {WidgetRegistryService} from './sidenav/entities/widgets/widget-registry.service'; import {AddEntityMenuComponent} from './editor/add-entity-menu/add-entity-menu.component'; import {HttpClientModule} from '@angular/common/http'; import {SharedModule} from './shared/shared.module'; import {MaterialModule} from './material.module'; import {HistoryModule} from './history/history.module'; import {WidgetModule} from './sidenav/entities/widgets/widget.module'; import {StateHistoryService} from './history/state-history.service'; @NgModule({ declarations: [ AppComponent, EditorComponent, PhaserComponent, ToolbarComponent, SidenavComponent, LayersComponent, EntitiesComponent, AddEntityMenuComponent, ], imports: [ BrowserModule, AppRoutingModule, FormsModule, FlexLayoutModule, MaterialModule, HttpClientModule, BrowserAnimationsModule, WidgetModule, SharedModule, HistoryModule, ], providers: [ WidgetRegistryService, StateHistoryService, ], bootstrap: [AppComponent] }) export class AppModule { }
45498106/crosscode-map-editor
webapp/src/app/sidenav/layers/layers.component.ts
import {Component, OnInit, ViewEncapsulation} from '@angular/core'; import {CCMap} from '../../shared/phaser/tilemap/cc-map'; import {CCMapLayer} from '../../shared/phaser/tilemap/cc-map-layer'; import {MapLoaderService} from '../../shared/map-loader.service'; import {animate, animateChild, keyframes, query, stagger, style, transition, trigger} from '@angular/animations'; import {GlobalEventsService} from '../../shared/global-events.service'; @Component({ selector: 'app-layers', templateUrl: './layers.component.html', styleUrls: ['./layers.component.scss'], encapsulation: ViewEncapsulation.None }) export class LayersComponent implements OnInit { selectedLayer: CCMapLayer; tilemap: CCMap; constructor(private mapLoader: MapLoaderService, events: GlobalEventsService) { events.toggleVisibility.subscribe(() => { if (this.selectedLayer) { this.toggleVisibility({ stopPropagation: () => { } }, this.selectedLayer); } }); } ngOnInit() { this.mapLoader.selectedLayer.subscribe(layer => this.selectedLayer = layer); this.mapLoader.tileMap.subscribe(tilemap => this.tilemap = tilemap); } getDisplayName(layer: CCMapLayer): string { return `${layer.details.name} (${layer.details.level})`; } toggleVisibility(event, layer: CCMapLayer) { event.stopPropagation(); layer.visible = !layer.visible; if (layer.visible) { this.selectLayer(layer); } } selectLayer(layer: CCMapLayer) { layer.visible = true; this.mapLoader.selectedLayer.next(layer); } }
45498106/crosscode-map-editor
webapp/src/app/sidenav/entities/widgets/string-widget/string-widget.component.ts
<reponame>45498106/crosscode-map-editor<gh_stars>0 import {Component, OnInit, ViewEncapsulation} from '@angular/core'; import {AbstractWidget} from '../abstract-widget'; @Component({ selector: 'app-string-widget', templateUrl: './string-widget.component.html', styleUrls: ['./string-widget.component.scss', '../../entities.component.scss'] }) export class StringWidgetComponent extends AbstractWidget implements OnInit { keys: string[] = []; constructor() { super(); } ngOnInit() { const attr = this.attribute; if (attr && attr.options) { this.keys = Object.keys(attr.options); } } }
45498106/crosscode-map-editor
webapp/src/app/shared/globals.ts
<reponame>45498106/crosscode-map-editor<gh_stars>0 import {CCMap} from './phaser/tilemap/cc-map'; export class Globals { static isNwjs = false; static game: Phaser.Game; static map: CCMap; static TILE_SIZE = 16; static URL = 'http://localhost:8080/'; static entitySettings = { gridSize: 8, enableGrid: false }; static disablePhaserInput = false; static zIndexUpdate = false; }
45498106/crosscode-map-editor
webapp/src/app/shared/phaser/entities/selection-box.ts
<filename>webapp/src/app/shared/phaser/entities/selection-box.ts import {Point} from '../../interfaces/cross-code-map'; import {Helper} from '../helper'; import {SortableGroup} from '../../interfaces/sortable'; import {CCEntity} from './cc-entity'; export class SelectionBox { private active = false; private start: Point; private game: Phaser.Game; private graphics: Phaser.Graphics; private selectedEntities: Set<CCEntity>; constructor(game: Phaser.Game) { this.game = game; this.selectedEntities = new Set<CCEntity>(); const group: SortableGroup = game.add.group(); group.zIndex = 10000; this.graphics = game.add.graphics(0, 0, group); } public onInputDown(pos: Point) { this.active = true; this.start = pos; this.selectedEntities.clear(); } public update(entities: CCEntity[]) { if (!this.active) { return; } const pos = Helper.screenToWorld(this.game.input.mousePointer); const start = this.start; let x1 = start.x; let y1 = start.y; let x2 = pos.x; let y2 = pos.y; if (x2 < x1) { const tmp = x1; x1 = x2; x2 = tmp; } if (y2 < y1) { const tmp = y1; y1 = y2; y2 = tmp; } const rect = new Phaser.Rectangle(x1, y1, x2 - x1, y2 - y1); this.graphics.clear(); this.graphics.beginFill(0x3335ed, 0.3); this.graphics.lineStyle(1, 0x3335ed, 0.8); this.graphics.drawRect(rect.x, rect.y, rect.width, rect.height); this.graphics.endFill(); entities.forEach(e => { const events = e.collisionImage.events; if (rect.intersects(e.getBoundingBox(), 0)) { events.onInputOver.dispatch(); this.selectedEntities.add(e); } else { events.onInputOut.dispatch(); this.selectedEntities.delete(e); } }); } public onInputUp(): Set<CCEntity> { if (!this.active) { return; } this.graphics.clear(); this.active = false; this.selectedEntities.forEach(e => { e.collisionImage.events.onInputOut.dispatch(); }); return this.selectedEntities; } }
45498106/crosscode-map-editor
webapp/src/app/shared/floating-window/floating-window.component.ts
<filename>webapp/src/app/shared/floating-window/floating-window.component.ts import {Component, Input, OnInit, ViewEncapsulation} from '@angular/core'; @Component({ selector: 'app-floating-window', templateUrl: './floating-window.component.html', styleUrls: ['./floating-window.component.scss'] }) export class FloatingWindowComponent implements OnInit { @Input() visible = true; @Input() title: string; @Input() height: string; @Input() width: string; @Input() top: string | number = 0; @Input() right: string | number = 0; constructor() { } ngOnInit() { } onDragEnd($event) { // console.log($event); } toggle() { this.visible = !this.visible; } }
BirMa/components
projects/components/table/src/subcomponents/table-pagination.component.spec.ts
<filename>projects/components/table/src/subcomponents/table-pagination.component.spec.ts import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DebugElement, ViewChild } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { MatCardModule } from '@angular/material/card'; import { MatPaginator, MatPaginatorIntl, MatPaginatorModule, PageEvent } from '@angular/material/paginator'; import { MatSelectModule } from '@angular/material/select'; import { By } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { IPsTableIntlTexts } from '../..'; import { PsTablePaginationComponent } from './table-pagination.component'; const testIntl: IPsTableIntlTexts = { firstPageLabel: 'a', lastPageLabel: 'b', previousPageLabel: 'c', nextPageLabel: 'd', itemsPerPageLabel: 'e', getRangeLabel: () => 'fnc', searchLabel: 'f', sortLabel: 'g', refreshListLabel: 'h', settingsLabel: 'i', noEntriesLabel: 'j', saveLabel: 'k', cancelLabel: 'l', displayedColumnsLabel: 'm', }; @Component({ template: ` <ps-table-pagination [pageSize]="pageSize" [dataLength]="dataLength" [pageIndex]="pageIndex" [pageSizeOptions]="pageSizeOptions" [intl]="intl" [pageDebounce]="pageDebounce" (page)="onPage($event)" ></ps-table-pagination> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) class PaginationTestComponent { public pageSize = 5; public dataLength = 15; public pageIndex = 0; public intl = testIntl; public pageDebounce: number; @ViewChild(PsTablePaginationComponent) public pagination: PsTablePaginationComponent; public onPage = (_: PageEvent) => {}; } describe('PsTablePaginationComponent', () => { describe('Unit tests', () => { let component: PsTablePaginationComponent; const cd = { markForCheck: () => {} } as ChangeDetectorRef; beforeEach(() => { component = new PsTablePaginationComponent(cd); }); it('should set Intl correctly', () => { component.intl = testIntl; component.paginator = new MatPaginator(new MatPaginatorIntl(), cd); expect(component.paginator._intl.firstPageLabel).toEqual('a'); expect(component.paginator._intl.lastPageLabel).toEqual('b'); expect(component.paginator._intl.previousPageLabel).toEqual('c'); expect(component.paginator._intl.nextPageLabel).toEqual('d'); expect(component.paginator._intl.itemsPerPageLabel).toEqual('e'); expect(component.paginator._intl.getRangeLabel(0, 0, 0)).toEqual('fnc'); }); it('should debounce pageEvent, if pageDebounce-Property is set', fakeAsync(() => { const pageEmitSpy = spyOn(component.page, 'emit'); component.pageDebounce = 300; component.onPage({ length: 9999 } as PageEvent); tick(299); expect(pageEmitSpy).not.toHaveBeenCalled(); tick(2); expect(pageEmitSpy).toHaveBeenCalledTimes(1); expect(pageEmitSpy).toHaveBeenCalledWith({ length: 9999 } as PageEvent); })); }); describe('Integration tests', () => { let component: PaginationTestComponent; let fixture: ComponentFixture<PaginationTestComponent>; let debugElement: DebugElement; beforeEach(() => { TestBed.configureTestingModule({ declarations: [PaginationTestComponent, PsTablePaginationComponent], imports: [BrowserAnimationsModule, FormsModule, MatPaginatorModule, MatSelectModule, MatCardModule], }); fixture = TestBed.createComponent(PaginationTestComponent); component = fixture.componentInstance; debugElement = fixture.debugElement.query(By.directive(PsTablePaginationComponent)); fixture.detectChanges(); }); it('should bind the page events correctly', fakeAsync(() => { const onPageSpy = spyOn(component, 'onPage'); const paginatorNextButtonEl = debugElement.nativeElement .querySelectorAll('.mat-paginator-navigation-next') .item(0) as HTMLButtonElement; paginatorNextButtonEl.dispatchEvent(new MouseEvent('click')); expect(onPageSpy).toHaveBeenCalledWith({ previousPageIndex: 0, pageIndex: 1, pageSize: 5, length: 15 }); })); it('should calculate pages correctly', () => { for (const data of [ [15, 5, 3], [11, 5, 3], [15, 10, 2], ]) { component.dataLength = data[0]; component.pageSize = data[1]; fixture.detectChanges(); expect(component.pagination.pages.length).toEqual(data[2]); } }); it('should update pages correctly', () => { component.dataLength = 15; component.pageSize = 5; fixture.detectChanges(); fixture.detectChanges(); expect(component.pagination.pages.length).toEqual(3); }); it('should update Intl correctly', () => { const updateIntlSpy = spyOn<any>(component.pagination, 'updatePaginatorIntl').and.callThrough(); component.intl = { ...testIntl, firstPageLabel: 'changed' }; fixture.detectChanges(); expect(updateIntlSpy).toHaveBeenCalled(); expect(component.pagination.intl.firstPageLabel).toEqual('changed'); }); }); });
BirMa/components
projects/prosoft-components-demo/src/app/form-field-demo/form-field-demo.component.ts
<filename>projects/prosoft-components-demo/src/app/form-field-demo/form-field-demo.component.ts import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ViewEncapsulation, Input } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { of } from 'rxjs'; import { PsFormFieldSubscriptType } from '@prosoft/components/form-field'; import { MatFormFieldAppearance } from '@angular/material/form-field'; @Component({ selector: 'app-reference-column', template: ` <ps-form-field [appearance]="appearance" [hint]="hint" [hintToggle]="hintToggle" [subscriptType]="subscriptType"> <mat-label>Referenz Column</mat-label> <input matInput [(ngModel)]="value" type="text" /> </ps-form-field> `, changeDetection: ChangeDetectionStrategy.OnPush, }) export class ReferenceColumnComponent { @Input() public subscriptType: PsFormFieldSubscriptType = 'single-line'; @Input() public hintToggle = false; @Input() public hint = 'hint text'; @Input() public appearance: MatFormFieldAppearance = 'legacy'; public value = ''; } @Component({ selector: 'app-form-field-demo', templateUrl: './form-field-demo.component.html', styleUrls: ['./form-field-demo.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class FormFieldDemoComponent { public subscriptType: PsFormFieldSubscriptType = 'single-line'; public hintToggle = false; public hintText = 'hint text'; public appearance: MatFormFieldAppearance = 'outline'; public asyncLabel$ = of('Custom Label'); public ctrlCountNumbers = Array(7).fill(1); public value = ''; public get disabled(): boolean { return this._disabled; } public set disabled(value: boolean) { for (const ctrlName in this.form.controls) { if (!this.form.controls.hasOwnProperty(ctrlName)) { continue; } const ctrl = this.form.controls[ctrlName]; if (value) { ctrl.disable(); } else { ctrl.enable(); } } this._disabled = value; this.cd.markForCheck(); } public customLabel = true; public get error(): boolean { return this._error; } public set error(value: boolean) { for (const ctrlName in this.form.controls) { if (!this.form.controls.hasOwnProperty(ctrlName)) { continue; } const ctrl = this.form.controls[ctrlName]; if (value) { ctrl.setValidators(() => ({ error1: 'error value 1', error2: 'this is a very long error is will be truncated in this demo', })); } else { ctrl.setValidators(null); } ctrl.updateValueAndValidity(); } this._error = value; this.cd.markForCheck(); } public form = new FormGroup({ select: new FormControl('item_ok'), checkbox: new FormControl(null), radio: new FormControl(null), prefixText: new FormControl(null), slider: new FormControl(null), psSelect: new FormControl(1), }); public showControls = true; public psSelectData = [ { key: 1, label: 'Option 1' }, { key: 2, label: 'Option 2' }, { key: 3, label: 'Option 3' }, ]; private _disabled = false; private _error = false; constructor(private cd: ChangeDetectorRef) { for (const ctrlName in this.form.controls) { if (!this.form.controls.hasOwnProperty(ctrlName)) { continue; } const ctrl = this.form.controls[ctrlName]; (ctrl as any).psLabel = ctrlName; } } }
BirMa/components
projects/components/card/public_api.ts
export { PsCardComponent } from './src/card.component'; export { PsCardActionsSectionDirective, PsCardCaptionSectionDirective, PsCardDescriptionSectionDirective, PsCardFooterSectionDirective, PsCardTopButtonSectionDirective, } from './src/card.directives'; export { PsCardModule } from './src/card.module';
BirMa/components
projects/components/header/src/header.component.spec.ts
import { HarnessLoader } from '@angular/cdk/testing'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { ChangeDetectionStrategy, Component, ViewChild } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { MatButtonModule } from '@angular/material/button'; import { PsHeaderComponent, PsHeaderModule } from '..'; import { PsHeaderHarness } from './testing/header.harness'; @Component({ selector: 'ps-test-component', template: ` <ps-header [caption]="caption" [description]="description"> <ng-container *psHeaderTopButtonSection> <button mat-button color="accent" *ngIf="addButtons">testButton</button> </ng-container> <ng-container *psHeaderCaptionSection> <h1 style="background-color: cyan;" *ngIf="addCaptionTemplate">caption text</h1> </ng-container> <ng-container *psHeaderDescriptionSection> <span style="background-color: lightblue;" *ngIf="addDescriptionTemplate">description text</span> </ng-container> </ps-header> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestDataSourceComponent { public caption: string; public description: string; public addButtons = false; public addCaptionTemplate = false; public addDescriptionTemplate = false; @ViewChild(PsHeaderComponent) headerComponent: PsHeaderComponent; } describe('PsHeaderComponent', () => { let fixture: ComponentFixture<TestDataSourceComponent>; let component: TestDataSourceComponent; let loader: HarnessLoader; let header: PsHeaderHarness; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [PsHeaderModule, MatButtonModule], declarations: [TestDataSourceComponent], }); fixture = TestBed.createComponent(TestDataSourceComponent); component = fixture.componentInstance; expect(component).toBeDefined(); loader = TestbedHarnessEnvironment.loader(fixture); header = await loader.getHarness(PsHeaderHarness); }); it('should show caption text', async () => { expect(await header.getCaptionText()).toBeFalsy(); component.caption = 'foo'; expect(await header.getCaptionText()).toBe('foo'); }); it('should show caption template', async () => { expect(await header.getCaptionText()).toBeFalsy(); component.addCaptionTemplate = true; const nodes = await header.getCaptionTemplateNodes(); expect(nodes.length).toEqual(1); const captionNode = nodes[0]; expect(await captionNode.matchesSelector('h1')).toEqual(true); expect(await captionNode.text()).toEqual('caption text'); }); it('should show caption text when input and template are set at the same time', async () => { expect(await header.getCaptionText()).toBeFalsy(); component.caption = 'foo'; expect(await header.getCaptionText()).toBeTruthy(); component.addCaptionTemplate = true; expect(await header.getCaptionText()).toBeTruthy(); const nodes = await header.getCaptionTemplateNodes(); expect(nodes.length).toEqual(0); }); it('should show description text', async () => { expect(await header.getDescriptionText()).toBeFalsy(); component.description = 'bar'; expect(await header.getDescriptionText()).toBe('bar'); }); it('should show description template', async () => { expect(await header.getDescriptionText()).toBeFalsy(); component.addDescriptionTemplate = true; const nodes = await header.getDescriptionTemplateNodes(); expect(nodes.length).toEqual(1); const descriptionNode = nodes[0]; expect(await descriptionNode.matchesSelector('span')).toEqual(true); expect(await descriptionNode.text()).toEqual('description text'); }); it('should show description text when input and template are set at the same time', async () => { expect(await header.getDescriptionText()).toBeFalsy(); component.description = 'foo'; expect(await header.getDescriptionText()).toBeTruthy(); component.addDescriptionTemplate = true; expect(await header.getDescriptionText()).toBeTruthy(); const nodes = await header.getDescriptionTemplateNodes(); expect(nodes.length).toEqual(0); }); it('should show buttons', async () => { let btns = await header.getActionTemplateNodes(); expect(btns.length).toBe(0); component.addButtons = true; btns = await header.getActionTemplateNodes(); expect(btns.length).toBe(1); expect(await btns[0].text()).toEqual('testButton'); }); });
BirMa/components
projects/components/block-ui/src/block-ui.component.spec.ts
import { CommonModule } from '@angular/common'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ViewChild } from '@angular/core'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { MatSpinner } from '@angular/material/progress-spinner'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { PsBlockUiComponent } from './block-ui.component'; import { PsBlockUiModule } from './block-ui.module'; @Component({ selector: 'ps-test-component', template: ` <ps-block-ui [blocked]="blocked" [spinnerText]="spinnerText"> <div id="content">test text</div> </ps-block-ui> `, // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection changeDetection: ChangeDetectionStrategy.Default, }) export class TestComponent { public blocked = false; public spinnerText: string = null; @ViewChild(PsBlockUiComponent, { static: true }) blockui: PsBlockUiComponent; constructor(public cd: ChangeDetectorRef) {} } describe('PsBlockUiComponent', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [NoopAnimationsModule, CommonModule, PsBlockUiModule], declarations: [TestComponent], }).compileComponents(); }) ); it( 'should work', waitForAsync(() => { const fixture = TestBed.createComponent(TestComponent); const component = fixture.componentInstance; expect(component).toBeDefined(); fixture.detectChanges(); const contentDebugEl = fixture.debugElement.query(By.css('#content')); expect(contentDebugEl).not.toBe(null); expect(contentDebugEl.nativeElement.textContent).toBe('test text'); expect(fixture.debugElement.query(By.directive(MatSpinner))).toBe(null); component.blocked = true; fixture.detectChanges(); expect(fixture.debugElement.query(By.directive(MatSpinner))).not.toBe(null); const containerEl = fixture.debugElement.query(By.css('.ps-block-ui__overlay-content')); expect(containerEl.nativeElement.children.length).toBe(1); component.spinnerText = 'spinner text'; fixture.detectChanges(); expect(containerEl.nativeElement.children.length).toBe(2); expect(containerEl.nativeElement.children[1].textContent).toBe('spinner text'); }) ); });
BirMa/components
projects/components/table/src/subcomponents/table-header.component.ts
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, TemplateRef, ViewEncapsulation, HostBinding, } from '@angular/core'; import { IPsTableIntlTexts } from '@prosoft/components/core'; import { IPsTableSortDefinition } from '../models'; @Component({ selector: 'ps-table-header', template: ` <h2 *ngIf="caption" class="ps-table-header__caption">{{ caption }}</h2> <div *ngIf="customHeader" class="ps-table-header__custom-content"> <ng-container [ngTemplateOutlet]="customHeader"></ng-container> </div> <ps-table-sort *ngIf="showSorting" class="ps-table-header__sort" [sortColumn]="sortColumn" [sortDirection]="sortDirection" [sortDefinitions]="sortDefinitions" [intl]="intl" (sortChanged)="sortChanged.emit($event)" ></ps-table-sort> <ps-table-search *ngIf="filterable" class="ps-table-header__search" [searchText]="searchText" [debounceTime]="300" [intl]="intl" (searchChanged)="searchChanged.emit($event)" ></ps-table-search> <div *ngIf="topButtonSection" class="ps-table-header__actions"> <ng-container [ngTemplateOutlet]="topButtonSection" [ngTemplateOutletContext]="{ $implicit: selectedRows }"></ng-container> </div> `, styles: [ ` ps-table-header { padding: 0 16px; display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; } .ps-table-header__caption { flex-basis: 100%; } .ps-table-header__sort { flex: 0 1 350px; margin-right: auto; /* This counters the margin of the actions to push the search back to the middle */ } .ps-table-header__search { flex: 0 1 800px; } .ps-table-header__actions { flex-basis: auto; margin: 0.3em 8px 1em; text-align: end; align-self: flex-end; margin-left: auto; /* This ensures that the actions are always right, even if there is no other flex item */ } `, ], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class PsTableHeaderComponent { @Input() public intl: IPsTableIntlTexts; @Input() public caption: string; @Input() public topButtonSection: TemplateRef<any> | null; @Input() public customHeader: TemplateRef<any> | null; @Input() public selectedRows: any[]; @Input() public showSorting: boolean; @Input() public sortColumn: string; @Input() public sortDirection: 'asc' | 'desc'; @Input() public sortDefinitions: IPsTableSortDefinition[] = []; @Input() public filterable: boolean; @Input() public searchText: string; @Output() public readonly sortChanged = new EventEmitter<{ sortColumn: string; sortDirection: 'asc' | 'desc' }>(); @Output() public readonly searchChanged = new EventEmitter<string>(); @HostBinding('style.padding-top') public get paddingTop() { return !this.caption && (this.showSorting || this.filterable || this.topButtonSection) ? '1em' : '0'; } }
BirMa/components
projects/components/form/src/form-data-source.ts
<filename>projects/components/form/src/form-data-source.ts import { FormGroup } from '@angular/forms'; import { IPsButton, IPsException } from '@prosoft/components/core'; import { IPsSavebarMode } from '@prosoft/components/savebar'; import { Observable } from 'rxjs'; /** * @deprecated Will be replaced with IPsBtton */ // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface IPsFormButton extends IPsButton {} /** * @deprecated Will be replaced with IPsException */ // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface IPsFormException extends IPsException {} export interface IPsFormDataSourceConnectOptions { errorInView$: Observable<boolean>; scrollToError(): void; } export interface IPsFormDataSource { readonly form: FormGroup; readonly autocomplete: 'on' | 'off'; readonly buttons: IPsButton[]; readonly contentVisible: boolean; readonly contentBlocked: boolean; readonly exception: IPsException | null; readonly savebarMode: IPsSavebarMode; connect(options: IPsFormDataSourceConnectOptions): Observable<void>; disconnect(): void; }
BirMa/components
projects/components/schematics/ps-select-load-trigger-and-sort-by-rename/index.ts
<reponame>BirMa/components import { DirEntry, FileEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; const touchedFiles: string[] = []; export default (): Rule => (tree: Tree, context: SchematicContext) => { context.logger.info('"ps-select: rename LoadTrigger and SortBy enums from PascalCase to camelCase" started...'); traverseDirectory(tree.root, tree, context); if (touchedFiles.length) { context.logger.info(`Modified files: ${touchedFiles.join(', ')}`); } else { context.logger.info('No modifications required.'); } context.logger.info('"ps-select: rename LoadTrigger and SortBy enums from PascalCase to camelCase" finished'); return tree; }; function traverseDirectory(directory: DirEntry, tree: Tree, _context: SchematicContext) { const dirPath = directory.path; if (dirPath.endsWith('/dist') || dirPath.endsWith('/node_modules') || dirPath.endsWith('/.angular')) { // Skip these directories return; } for (const subDir of directory.subdirs) { traverseDirectory(directory.dir(subDir), tree, _context); } for (const fileName of directory.subfiles.filter((subFile) => subFile.endsWith('.ts'))) { const file = directory.file(fileName); if (file) { updateFile(file, tree, _context); } } } function updateFile(file: FileEntry, tree: Tree, _context: SchematicContext) { const content = file.content.toString(); if (content.indexOf('PsSelectLoadTrigger') === -1 && content.indexOf('PsSelectSortBy') === -1) { return; } if (content.indexOf('PsSelectLoadTrigger') !== -1) { camelize(content, 'PsSelectLoadTrigger', 'Initial'); camelize(content, 'PsSelectLoadTrigger', 'FirstPanelOpen'); camelize(content, 'PsSelectLoadTrigger', 'EveryPanelOpen'); camelize(content, 'PsSelectLoadTrigger', 'All'); } if (content.indexOf('PsSelectSortBy') !== -1) { camelize(content, 'PsSelectSortBy', 'None'); camelize(content, 'PsSelectSortBy', 'Selected'); camelize(content, 'PsSelectSortBy', 'Comparer'); camelize(content, 'PsSelectSortBy', 'Both'); } tree.overwrite(file.path, content); touchedFiles.push(file.path); } function camelize(fileContent: string, enumName: string, pascalCaseValue: string) { fileContent.replace(`${enumName}.${pascalCaseValue}`, `${enumName}.${pascalCaseValue.toLowerCase()}`); }
BirMa/components
projects/components/core/src/intl.ts
import { Injectable } from '@angular/core'; import { MatPaginatorIntl } from '@angular/material/paginator'; import { Subject } from 'rxjs'; export interface IPsSavebarIntlTexts { saveLabel: string; saveAndCloseLabel: string; cancelLabel: string; } // Can be removed with Typescript 3.5 type Pick<T, K extends keyof T> = { [P in K]: T[P] }; type Exclude<T, U> = T extends U ? never : T; type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; export interface IPsTableIntlTexts extends Omit<MatPaginatorIntl, 'changes'> { searchLabel: string; sortLabel: string; refreshListLabel: string; settingsLabel: string; noEntriesLabel: string; saveLabel: string; cancelLabel: string; displayedColumnsLabel: string; } export declare type PsIntlKeys = 'form' | 'savebar' | 'table'; @Injectable({ providedIn: 'root' }) export abstract class PsIntlService { public intlChanged$ = new Subject<void>(); public abstract get(intlKey: 'table'): IPsTableIntlTexts; public abstract get(intlKey: 'savebar'): IPsSavebarIntlTexts; public abstract get(intlKey: PsIntlKeys): IPsSavebarIntlTexts | IPsTableIntlTexts; // eslint-disable-next-line @typescript-eslint/ban-types public merge<T extends {}>(intl1: T, overrides: Partial<T>): T { if (!overrides) { return intl1; } const result: any = Object.assign({}, intl1); for (const [key, value] of Object.entries(overrides)) { if (value) { result[key] = value; } } return result; } } @Injectable() export class PsIntlServiceEn extends PsIntlService { private paginatorIntl = new MatPaginatorIntl(); private formSavebarIntl: IPsSavebarIntlTexts = { saveLabel: 'Save', saveAndCloseLabel: 'Save & close', cancelLabel: 'Cancel', }; private tableIntl: IPsTableIntlTexts = { saveLabel: 'Save', cancelLabel: 'Cancel', searchLabel: 'Search', sortLabel: 'Sorting', refreshListLabel: 'Refresh list', settingsLabel: 'List settings', noEntriesLabel: 'No entries', displayedColumnsLabel: 'Displayed columns', itemsPerPageLabel: this.paginatorIntl.itemsPerPageLabel, nextPageLabel: this.paginatorIntl.nextPageLabel, previousPageLabel: this.paginatorIntl.previousPageLabel, firstPageLabel: this.paginatorIntl.firstPageLabel, lastPageLabel: this.paginatorIntl.lastPageLabel, getRangeLabel: this.paginatorIntl.getRangeLabel, }; public get(intlKey: 'table'): IPsTableIntlTexts; public get(intlKey: 'savebar'): IPsSavebarIntlTexts; public get(intlKey: PsIntlKeys): IPsSavebarIntlTexts | IPsTableIntlTexts { switch (intlKey) { case 'table': return this.tableIntl; case 'savebar': return this.formSavebarIntl; default: return null; } } }
BirMa/components
projects/prosoft-components-demo/src/app/savebar-demo/savebar-demo.component.ts
<reponame>BirMa/components import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/core'; import { AbstractControl, FormControl, FormGroup } from '@angular/forms'; @Component({ selector: 'app-savebar-demo', template: ` <ps-savebar [form]="form" (save)="onButtonClick('save')" (saveAndClose)="onButtonClick('saveAndClose')" (cancel)="onButtonClick('cancel')" > <mat-card> <form [formGroup]="form"> <mat-form-field> <mat-label>Input 1</mat-label> <input type="text" matInput formControlName="input1" /> </mat-form-field> <div style="height: 100vh;"></div> <mat-form-field> <mat-label>Input 2</mat-label> <input type="text" matInput formControlName="input2" /> </mat-form-field> </form> </mat-card> <ng-container *psSavebarRightContent> <button mat-stroked-button type="button" (click)="onButtonClick('custom')">Custom Button</button> </ng-container> </ps-savebar> `, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class SavebarDemoComponent { public form = new FormGroup( { input1: new FormControl('a'), input2: new FormControl('b'), }, [ (formGroup: AbstractControl) => formGroup.value.input1 === formGroup.value.input2 ? null : { equal: 'input1 and input2 must be equal' }, ] ); public onButtonClick(buttonName: string) { alert(buttonName + ' button clicked'); } }
BirMa/components
projects/components/select/src/defaults/default-select-data-source.ts
import { BehaviorSubject, combineLatest, isObservable, merge, NEVER, Observable, of, Subject } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, filter, map, shareReplay, skip, startWith, switchMap, take, takeUntil, tap, } from 'rxjs/operators'; import { PsSelectItem } from '../models'; import { PsSelectDataSource } from '../select-data-source'; export declare type MaybeObservable<T> = T | Observable<T>; export interface PsSelectDataSourceOptions<T = any> { mode: 'id' | 'entity'; idKey: keyof T; labelKey: keyof T; disabledKey?: keyof T; items: MaybeObservable<T[]> | (() => MaybeObservable<T[]>); searchDebounce?: number; loadTrigger?: PsSelectLoadTrigger; sortBy?: PsSelectSortBy; } export function isPsSelectOptionsData(value: any): value is PsSelectDataSourceOptions { return typeof value === 'object' && 'idKey' in value && 'labelKey' in value && 'items' in value && 'mode' in value; } export const enum PsSelectLoadTrigger { // eslint-disable-next-line no-bitwise initial = 1 << 0, // eslint-disable-next-line no-bitwise firstPanelOpen = 1 << 1, // eslint-disable-next-line no-bitwise everyPanelOpen = 1 << 2, all = initial + firstPanelOpen + everyPanelOpen, } export const enum PsSelectSortBy { // eslint-disable-next-line no-bitwise none = 0, // eslint-disable-next-line no-bitwise selected = 1 << 0, // eslint-disable-next-line no-bitwise comparer = 1 << 1, both = selected + comparer, } export class DefaultPsSelectDataSource<T = any> extends PsSelectDataSource<T> { private _searchDebounceTime: number; private _loadTrigger: PsSelectLoadTrigger; private _sortBy: PsSelectSortBy; private _isPanelOpen$ = new BehaviorSubject<boolean>(false); private _searchText$ = new BehaviorSubject<string>(''); private _currentValues$ = new BehaviorSubject<T[]>([]); private _ngUnsubscribe$ = new Subject<void>(); private _loadData: () => Observable<PsSelectItem<T>[]>; constructor(options: PsSelectDataSourceOptions) { super(); this._searchDebounceTime = options.searchDebounce ?? 300; this._loadTrigger = options.loadTrigger ?? PsSelectLoadTrigger.initial; this._sortBy = options.sortBy ?? PsSelectSortBy.both; let loadData: () => Observable<PsSelectItem<T>[]>; const entityToSelectItem = createEntityToSelectItemMapper(options.mode, options.idKey, options.labelKey, options.disabledKey); const items = options.items; if (typeof items !== 'function') { const data$ = ensureObservable(items).pipe( map((x) => x.map(entityToSelectItem)), takeUntil(this._ngUnsubscribe$) ); loadData = () => data$; } else { const func: () => T[] | Observable<T[]> = items as any; loadData = () => ensureObservable(func()).pipe(map((x) => x.map(entityToSelectItem))); } if (options.mode === 'entity') { this.compareWith = createEntityComparer(options.idKey); this.getItemsForValues = (values: any[]) => values.map(entityToSelectItem); } this._loadData = () => { this.loading = true; this.error = null; return loadData().pipe( catchError((err: Error | any) => { this.error = err; return of([] as PsSelectItem<T>[]); }), tap(() => { this.loading = false; }) ); }; } public connect(): Observable<PsSelectItem<T>[]> { const optionsLoadTrigger$ = this._createOptionsLoadTrigger(); const loadedOptions$ = optionsLoadTrigger$.pipe( switchMap(() => this._loadData()), startWith<PsSelectItem<T>[]>([]), map((options) => options.map(normalizeLabel)), shareReplay({ bufferSize: 1, refCount: true }) ); // generate values as options, that aren't in the loaded options const missingOptions$ = loadedOptions$.pipe( switchMap((options) => this._currentValues$.pipe(map((values) => values.filter((value) => !options.find((o) => this.compareWith(o.value, value))))) ), distinctUntilChanged((a, b) => { if (a.length !== b.length) { return false; } for (const value of a) { if (!b.find((o) => this.compareWith(o, value))) { return false; } } return true; }), map((missingValues) => this.getItemsForValues(missingValues).map(normalizeLabel)) ); let renderOptions$ = combineLatest([loadedOptions$, missingOptions$]).pipe( debounceTime(0), map(([options, missingOptions]) => missingOptions.concat(options)) ); if (this._sortBy) { const sortTrigger$ = this._createSortTrigger(); renderOptions$ = renderOptions$.pipe( switchMap((unsortedOptions) => sortTrigger$.pipe(map(() => this._cloneAndSort(unsortedOptions)))) ); } // searchtext handling renderOptions$ = renderOptions$.pipe( switchMap((options) => this._searchText$.pipe( debounceTime(this._searchDebounceTime), startWith(this._searchText$.value), map((x) => (x || '').toLowerCase()), distinctUntilChanged(), map((searchText) => { options.forEach((option) => { option.hidden = this.searchCompare(option, searchText); }); return options; }) ) ) ); return renderOptions$; } public disconnect(): void { this._isPanelOpen$.complete(); this._searchText$.complete(); this._currentValues$.complete(); this._ngUnsubscribe$.next(); this._ngUnsubscribe$.complete(); } public panelOpenChanged(panelOpen: boolean): void { this._isPanelOpen$.next(panelOpen); } public searchTextChanged(searchText: string): void { this._searchText$.next(searchText); } public selectedValuesChanged(values: T[]): void { this._currentValues$.next(values); } public getItemsForValues(values: T[]): PsSelectItem<T>[] { return values.map((v) => ({ value: v, label: `??? (ID: ${v})`, })); } /** * Sort comparer for the items. * Note: Selected items will still be at the top. */ public sortCompare = (a: PsSelectItem, b: PsSelectItem): number => a.label.localeCompare(b.label); /** * Search comparer for the items. */ public searchCompare = (option: PsSelectItem, searchText: string): boolean => option.label.toLowerCase().indexOf(searchText) === -1; private _createOptionsLoadTrigger(): Observable<void> { const loadTriggers: Observable<any>[] = []; // eslint-disable-next-line no-bitwise if (this._loadTrigger & PsSelectLoadTrigger.initial) { loadTriggers.push(of(null)); } const panelOpen$ = this._isPanelOpen$.pipe( distinctUntilChanged(), filter((panelOpen) => panelOpen) ); // eslint-disable-next-line no-bitwise if (this._loadTrigger & PsSelectLoadTrigger.everyPanelOpen) { loadTriggers.push(panelOpen$); // eslint-disable-next-line no-bitwise } else if (this._loadTrigger & PsSelectLoadTrigger.firstPanelOpen) { loadTriggers.push(panelOpen$.pipe(take(1))); } return merge(...loadTriggers); } private _createSortTrigger(): Observable<unknown> { const panelCloseEvent$ = this._isPanelOpen$.pipe( skip(1), // we don't need the initial value distinctUntilChanged(), filter((x) => !x) // we only care about close-events ); const valueChangedWhileClosed$ = this._isPanelOpen$.pipe( distinctUntilChanged(), switchMap((panelOpen) => (panelOpen ? NEVER : this._currentValues$.pipe(skip(1)))) ); // initially and on panel close we must sort the selected options to the top return merge(panelCloseEvent$, valueChangedWhileClosed$).pipe(startWith(0)); } private _cloneAndSort(unsortedOptions: PsSelectItem<T>[]) { let selectedOptionsSet: WeakSet<PsSelectItem> = null; // eslint-disable-next-line no-bitwise if (this._sortBy & PsSelectSortBy.selected) { const selectedOptions = unsortedOptions.filter((option) => this._currentValues$.value.find((value) => this.compareWith(option.value, value)) ); selectedOptionsSet = new WeakSet(selectedOptions); } const sortedOptions = unsortedOptions.slice().sort((a, b) => { // eslint-disable-next-line no-bitwise if (this._sortBy & PsSelectSortBy.selected) { const aSelected = +selectedOptionsSet.has(a); const bSelected = +selectedOptionsSet.has(b); const selectedDifferent = bSelected - aSelected; if (selectedDifferent) { return selectedDifferent; } } // eslint-disable-next-line no-bitwise return this._sortBy & PsSelectSortBy.comparer ? this.sortCompare(a, b) : 0; }); return sortedOptions; } } export function ensureObservable<T>(data: T | Observable<T>): Observable<T> { if (!isObservable(data)) { data = of(data); } return data; } function createEntityToSelectItemMapper( mode: 'id' | 'entity', idKey: keyof any, labelKey: keyof any, disabledKey: keyof any ): (item: any) => PsSelectItem<any> { if (mode === 'id') { return (item: any) => ({ value: item[idKey], label: item[labelKey], entity: item, disabled: (disabledKey && item[disabledKey]) || false, }); } return (item: any) => ({ value: item, label: item[labelKey], entity: item, disabled: (disabledKey && item[disabledKey]) || false, }); } function createEntityComparer(idKey: keyof any) { return (entity1: any, entity2: any) => { // Wenn sie gleich sind, sind sie wohl gleich :D if (entity1 === entity2) { return true; } // Wenn der typ ungleich ist, dann sind sie nicht gleich if (typeof entity1 !== typeof entity2) { return false; } // Wenn eins von beidem falsy ist, es aber nicht das gleiche falsy ist (check oben), dann sind sie nicht gleich if (!entity1 || !entity2) { return false; } // Wenn es kein Object ist, wird es nicht unterstützt und wir geben false zurück if (typeof entity1 !== 'object') { return false; } return entity1[idKey] === entity2[idKey]; }; } function normalizeLabel(option: PsSelectItem) { if (!option.label) { option.label = ''; } else if (!(typeof option.label === 'string')) { option.label = `${option.label}`; } return option; }