repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
Annmary12/blog-with-angular
src/app/app.module.ts
<filename>src/app/app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; // pages import { HomeComponent } from './pages/home/home.component'; // components import { NavBarComponent } from './components/NavBar/nav-bar.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent, HomeComponent, NavBarComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
thycoding/OLED
OLED.ts
// 6x8 font const Font_5x7 = hex`000000000000005F00000007000700147F147F14242A072A12231308646237495522500005030000001C2241000041221C00082A1C2A0808083E080800503000000808080808006060000020100804023E5149453E00427F400042615149462141454B311814127F1027454545393C4A49493001710905033649494936064949291E003636000000563600000008142241141414141441221408000201510906324979413E7E1111117E7F494949363E414141227F4141221C7F494949417F090901013E414151327F0808087F00417F41002040413F017F081422417F404040407F0204027F7F0408107F3E4141413E7F090909063E4151215E7F09192946464949493101017F01013F4040403F1F2040201F7F2018207F63140814630304780403615149454300007F4141020408102041417F000004020102044040404040000102040020545454787F484444383844444420384444487F3854545418087E090102081454543C7F0804047800447D40002040443D00007F10284400417F40007C041804787C0804047838444444387C14141408081414187C7C080404084854545420043F4440203C4040207C1C2040201C3C4030403C44281028440C5050503C4464544C44000836410000007F000000413608000201020402` //% weight=10 color=#019b9b icon="\uf121" block="OLED" namespace OLED { export enum DISPLAY_ONOFF { //% block="ON" DISPLAY_ON = 1, //% block="OFF" DISPLAY_OFF = 0 } const MIN_X = 0 const MIN_Y = 0 const MAX_X = 127 const MAX_Y = 63 let _I2CAddr = 60 let _screen = pins.createBuffer(1025) let _buf2 = pins.createBuffer(2) let _buf3 = pins.createBuffer(3) let _buf4 = pins.createBuffer(4) let _buf7 = pins.createBuffer(7) _buf7[0] = 0x40 let _DRAW = 1 let _cx = 0 let _cy = 0 function cmd1(d: number) { let n = d % 256; pins.i2cWriteNumber(_I2CAddr, n, NumberFormat.UInt16BE); } function cmd2(d1: number, d2: number) { _buf3[0] = 0; _buf3[1] = d1; _buf3[2] = d2; pins.i2cWriteBuffer(_I2CAddr, _buf3); } function cmd3(d1: number, d2: number, d3: number) { _buf4[0] = 0; _buf4[1] = d1; _buf4[2] = d2; _buf4[3] = d3; pins.i2cWriteBuffer(_I2CAddr, _buf4); } function set_pos(col: number = 0, page: number = 0) { cmd1(0xb0 | page) // page number cmd1(0x00 | (col % 16)) // lower start column address cmd1(0x10 | (col >> 4)) // upper start column address } // clear bit function clrbit(d: number, b: number): number { if (d & (1 << b)) d -= (1 << b) return d } /** * draw / refresh screen */ function draw(d: number) { if (d > 0) { set_pos() pins.i2cWriteBuffer(_I2CAddr, _screen) } } /** * set pixel in OLED */ //% blockId="OLED_PIXEL" block="set pixel at x %x|y %y|color %color" //% x.max=128 x.min=0 x.defl=0 //% y.max=64 y.min=0 y.defl=0 //% color.max=1 color.min=0 color.defl=1 //% weight=65 blockGap=8 export function pixel(x: number, y: number, color: number = 1) { let page = y >> 3 let shift_page = y % 8 let ind = x + page * 128 + 1 let b = (color) ? (_screen[ind] | (1 << shift_page)) : clrbit(_screen[ind], shift_page) _screen[ind] = b if (_DRAW) { set_pos(x, page) _buf2[0] = 0x40 _buf2[1] = b pins.i2cWriteBuffer(_I2CAddr, _buf2) } } function char(c: string, col: number, row: number, color: number = 1) { let p = (Math.min(127, Math.max(c.charCodeAt(0), 32)) - 32) * 5 let ind = col + row * 128 + 1 for (let i = 0; i < 5; i++) { _screen[ind + i] = (color > 0) ? Font_5x7[p + i] : Font_5x7[p + i] ^ 0xFF _buf7[i + 1] = _screen[ind + i] } _screen[ind + 5] = (color > 0) ? 0 : 0xFF _buf7[6] = _screen[ind + 5] set_pos(col, row) pins.i2cWriteBuffer(_I2CAddr, _buf7) } /** * show text in OLED */ //% blockId="OLED_SHOWSTRING" block="show string %s|at col %col|row %row|color %color" //% s.defl='Hello' //% col.max=120 col.min=0 col.defl=0 //% row.max=7 row.min=0 row.defl=0 //% color.max=1 color.min=0 color.defl=1 //% weight=80 blockGap=8 inlineInputMode=inline export function String(s: string, col: number, row: number, color: number = 1) { for (let n = 0; n < s.length; n++) { char(s.charAt(n), col, row, color) col += 6 if (col > (MAX_X - 6)) return } } /** * show a number in OLED */ //% blockId="OLED_NUMBER" block="show Number %num|at col %col|row %row|color %color" //% num.defl=100 //% col.max=120 col.min=0 col.defl=0 //% row.max=7 row.min=0 row.defl=0 //% color.max=1 color.min=0 color.defl=1 //% weight=80 blockGap=8 inlineInputMode=inline export function Number(num: number, col: number, row: number, color: number = 1) { String(num.toString(), col, row, color) } function scroll() { _cx = 0 _cy++ if (_cy > 7) { _cy = 7 _screen.shift(128) _screen[0] = 0x40 draw(1) } } /** * print a text in OLED */ //% block="print %s|color %color|newline %newline" //% s.defl="string" //% color.max=1 color.min=0 color.defl=1 //% newline.defl=true //% weight=80 blockGap=8 inlineInputMode=inline export function printString(s: string, color: number, newline: boolean = true) { for (let n = 0; n < s.length; n++) { char(s.charAt(n), _cx, _cy, color) _cx += 6 if (_cx > 120) { scroll() } } if (newline) { scroll() } } /** * print a Number in OLED */ //% block="print number %num|color %color|newline %newline" //% s.defl="0" //% color.max=1 color.min=0 color.defl=1 //% newline.defl=true //% weight=80 blockGap=8 inlineInputMode=inline export function printNumber(num: number, color: number, newline: boolean = true) { printString(num.toString(), color, newline) } /** * draw a horizontal line */ //% blockId="OLED12864_I2C_HLINE" block="draw a horizontal line at x %x|y %y|length %len|color %color" //% x.max=127 x.min=0 x.defl=0 //% y.max=63 y.min=0 y.defl=0 //% len.max=128 len.min=1 len.defl=16 //% color.max=1 color.min=0 color.defl=1 //% weight=71 blockGap=8 inlineInputMode=inline export function hline(x: number, y: number, len: number, color: number = 1) { let _sav = _DRAW if ((y < MIN_Y) || (y > MAX_Y)) return _DRAW = 0 for (let i = x; i < (x + len); i++) if ((i >= MIN_X) && (i <= MAX_X)) pixel(i, y, color) _DRAW = _sav draw(_DRAW) } /** * draw a vertical line */ //% blockId="OLED_VLINE" block="draw a vertical line at x %x|y %y|length %len|color %color" //% x.max=127 x.min=0 x.defl=0 //% y.max=63 y.min=0 y.defl=0 //% len.max=128 len.min=1 len.defl=16 //% color.max=1 color.min=0 color.defl=1 //% weight=71 blockGap=8 inlineInputMode=inline export function vline(x: number, y: number, len: number, color: number = 1) { let _sav = _DRAW _DRAW = 0 if ((x < MIN_X) || (x > MAX_X)) return for (let i = y; i < (y + len); i++) if ((i >= MIN_Y) && (i <= MAX_Y)) pixel(x, i, color) _DRAW = _sav draw(_DRAW) } /** * draw a rectangle */ //% blockId="OLED_RECT" block="draw a rectangle at x1 %x1|y1 %y1|x2 %x2|y2 %y2|color %color" //% color.defl=1 //% weight=70 blockGap=8 inlineInputMode=inline export function rect(x1: number, y1: number, x2: number, y2: number, color: number = 1) { if (x1 > x2) x1 = [x2, x2 = x1][0]; if (y1 > y2) y1 = [y2, y2 = y1][0]; _DRAW = 0 hline(x1, y1, x2 - x1 + 1, color) hline(x1, y2, x2 - x1 + 1, color) vline(x1, y1, y2 - y1 + 1, color) vline(x2, y1, y2 - y1 + 1, color) _DRAW = 1 draw(1) } /** * invert display * @param d true: invert / false: normal, eg: true */ //% blockId="OLED_INVERT" block="Invert display %d" //% weight=62 blockGap=8 export function invert(d: boolean = true) { let n = (d) ? 0xA7 : 0xA6 cmd1(n) } /** * clear screen */ //% blockId="OLED_CLEAR" block="Clear screen" //% weight=30 blockGap=8 export function clear() { _cx = _cy = 0 _screen.fill(0) _screen[0] = 0x40 draw(1) } /** * turn on/off screen */ //% blockId="OLED_ON" block="Display %on" //% on.defl=1 //% weight=62 blockGap=8 export function display(on: DISPLAY_ONOFF=DISPLAY_ONOFF.DISPLAY_ON) { let d = (on == DISPLAY_ONOFF.DISPLAY_ON) ? 0xAF : 0xAE; cmd1(d) } /** * OLED initialize */ //% blockId="OLED_init" block="Initial OLED" //% weight=10 blockGap=8 export function init() { cmd1(0xAE) // SSD1306_DISPLAYOFF cmd1(0xA4) // SSD1306_DISPLAYALLON_RESUME cmd2(0xD5, 0xF0) // SSD1306_SETDISPLAYCLOCKDIV cmd2(0xA8, 0x3F) // SSD1306_SETMULTIPLEX cmd2(0xD3, 0x00) // SSD1306_SETDISPLAYOFFSET cmd1(0 | 0x0) // line #SSD1306_SETSTARTLINE cmd2(0x8D, 0x14) // SSD1306_CHARGEPUMP cmd2(0x20, 0x00) // SSD1306_MEMORYMODE cmd3(0x21, 0, 127) // SSD1306_COLUMNADDR cmd3(0x22, 0, 63) // SSD1306_PAGEADDR cmd1(0xa0 | 0x1) // SSD1306_SEGREMAP cmd1(0xc8) // SSD1306_COMSCANDEC cmd2(0xDA, 0x12) // SSD1306_SETCOMPINS cmd2(0x81, 0xCF) // SSD1306_SETCONTRAST cmd2(0xd9, 0xF1) // SSD1306_SETPRECHARGE cmd2(0xDB, 0x40) // SSD1306_SETVCOMDETECT cmd1(0xA6) // SSD1306_NORMALDISPLAY cmd2(0xD6, 0) // zoom off cmd1(0xAF) // SSD1306_DISPLAYON clear() } init(); }
Accessible-Concepts/scrumlr.io
src/api/callApi.ts
<reponame>Accessible-Concepts/scrumlr.io<gh_stars>10-100 import Parse from "parse"; /** * Helper function for calls on the cloud functions of the Parse server backend. * * @param endpoint the name of the endpoint * @param request the request parameters * * @returns the asynchronous server response wrapped in a `Promise` */ export const callAPI = <RequestType, ResponseType>(endpoint: string, request: RequestType) => Parse.Cloud.run(endpoint, request) as Promise<ResponseType>;
Accessible-Concepts/scrumlr.io
src/components/AppInfo/index.ts
export * from "./AppInfo";
Accessible-Concepts/scrumlr.io
src/components/NoteDialog/NoteDialogComponents/NoteDialogNoteComponents/NoteDialogOptions/index.ts
export * from "./NoteDialogNoteOptions";
Accessible-Concepts/scrumlr.io
src/types/__tests__/vote.test.ts
import {mapVoteServerToClientModel, VoteClientModel, VoteServerModel} from "../vote"; describe("Vote types", () => { test("mapVoteServerToClientModel", async () => { const map = { board: {id: "5"} as unknown as Parse.Object, note: {id: "5"} as unknown as Parse.Object, user: {id: "5"} as unknown as Parse.Object, votingIteration: 0, }; const serverModel = { id: "test_id", get: (s: string) => map[s], } as unknown as VoteServerModel; const clientModel: VoteClientModel = mapVoteServerToClientModel(serverModel); expect(clientModel.id).toEqual(serverModel.id); expect(clientModel.board).toEqual(serverModel.get("board").id); expect(clientModel.note).toEqual(serverModel.get("note").id); expect(clientModel.user).toEqual(serverModel.get("user").id); expect(clientModel.votingIteration).toEqual(serverModel.get("votingIteration")); }); });
Accessible-Concepts/scrumlr.io
src/store/action/column.ts
import {AddColumnRequest, EditColumnRequest} from "types/column"; /** This object lists column object specific internal Redux Action types. */ export const ColumnActionType = { /* * ATTENTION: * Don't forget the `as` casting for each field, because the type inference * won't work otherwise (e.g. in reducers). */ AddColumn: "@@SCRUMLR/addColumn" as const, EditColumn: "@@SCRUMLR/editColumn" as const, DeleteColumn: "@@SCRUMLR/deleteColumn" as const, }; /** Factory or creator class of internal Redux column object specific actions. */ export const ColumnActionFactory = { /* * ATTENTION: * Each action creator should be also listed in the type `ColumnReduxAction`, because * the type inference won't work otherwise (e.g. in reducers). */ /** * Creates an action which should be dispatched when the user wants to add a column to the current board. * * @param column contains * name: the column name * color: the color of the column * hidden: the flag which indicates whether this column should be visible to all basic users */ addColumn: (column: AddColumnRequest) => ({ type: ColumnActionType.AddColumn, column, }), /** * Creates an action which should be dispatched when the user edits a column. * * @param column contains * columnId: the edited column id * name: the new name * color: the new color of the column * hidden: the new hidden state */ editColumn: (column: EditColumnRequest) => ({ type: ColumnActionType.EditColumn, column, }), /** * Creates an action which should be dispatched when the user wants to delete a column. * * @param columnId the column id */ deleteColumn: (columnId: string) => ({ type: ColumnActionType.DeleteColumn, columnId, }), }; export type ColumnReduxAction = | ReturnType<typeof ColumnActionFactory.addColumn> | ReturnType<typeof ColumnActionFactory.editColumn> | ReturnType<typeof ColumnActionFactory.deleteColumn>;
Accessible-Concepts/scrumlr.io
src/api/board.ts
import {Color} from "constants/colors"; import {EditBoardRequest} from "types/board"; import {callAPI} from "api/callApi"; export const BoardAPI = { /** * Creates a board with the specified parameters and returns the board id. * * @param columns the definition of the columns * @param accessPolicy the access policy configuration of the board * @param name the board name * * @returns the board id of the created board */ createBoard: (name: string | undefined, accessPolicy: {type: string; passphrase?: string}, columns: {name: string; hidden: boolean; color: Color}[]) => callAPI<{columns: {name: string; hidden: boolean}[]; name?: string; accessPolicy: {type: string; passphrase?: string}}, string>("createBoard", {columns, name, accessPolicy}), /** * Edits the board with the specified parameters. * * @param board object with the board attributes that have to be changed * @returns 'true' if the operation succeeded or throws an error otherwise */ editBoard: (board: EditBoardRequest) => callAPI("editBoard", {board}), /** * Create join request for a board session. * The return value might have the status `accepted` (user is permitted to join the board), `rejected` (the join * request of the user was rejected by an admin) or `pending`. If the state is pending the response will include * the reference on the join request state in the attribute `joinRequestReference`. * * @param boardId the board id * @param passphrase optional passphrose for the join request * * @returns `true` if the operation succeeded or throws an error otherwise */ joinBoard: (boardId: string, passphrase?: string) => callAPI<{boardId: string; passphrase?: string}, {status: "accepted" | "rejected" | "pending" | "passphrase_required" | "incorrect_passphrase"; joinRequestReference?: string}>( "joinBoard", {boardId, passphrase} ), acceptJoinRequests: (boardId: string, userIds: string[]) => callAPI<{board: string; users: string[]}, boolean>("acceptUsers", {board: boardId, users: userIds}), rejectJoinRequests: (boardId: string, userIds: string[]) => callAPI<{board: string; users: string[]}, boolean>("rejectUsers", {board: boardId, users: userIds}), /** * Deletes the board with the specified boardId. * * @param boardId identifies the board which will be deleted * @returns 'true' if the operation succeeded or throws an error otherwise */ deleteBoard: (boardId: string) => callAPI("deleteBoard", {boardId}), /** * Cancel the current voting phase. * * @param boardId the board id * @returns a {status, description} object */ cancelVoting: (boardId: string) => callAPI("cancelVoting", {boardId}), /** Sets the date where the timer of the board ends. * * @param endDate the date/time where the timer ends * @param boardId the board identifier * @returns a {status, description} object */ setTimer: (endDate: Date, boardId: string) => callAPI("setTimer", {endDate, boardId}), /** * Cancels the timer of the board. * * @param boardId the board identifier * @returns a {status, description} object */ cancelTimer: (boardId: string) => callAPI("cancelTimer", {boardId}), };
Accessible-Concepts/scrumlr.io
src/routes/__tests__/RequireAuthentication.test.tsx
import {mocked} from "ts-jest/utils"; import {Session} from "parse"; import {getByTestId} from "@testing-library/dom"; import {waitFor} from "@testing-library/react"; import {RequireAuthentication} from "../RequireAuthentication"; import {render} from "../../testUtils"; jest.mock("parse"); const mockSession = mocked(Session, true); jest.mock("react-router-dom", () => ({ Navigate: () => <div>Error</div>, })); describe("RequireAuthentication", () => { test("show loading screen while session is being verified", () => { mockSession.current = (() => new Promise<Session>(() => {})) as never; const {container} = render(<RequireAuthentication />); expect(container.querySelector(".loading-screen")).toBeDefined(); }); test("show children on valid session", async () => { mockSession.current = (() => new Promise<Session>((resolve) => { resolve(new Session()); })) as never; const {container} = render( <RequireAuthentication> <div data-testid="test">Test</div> </RequireAuthentication> ); await waitFor(() => { expect(getByTestId(container, "test")).toBeDefined(); }); }); test("show login screen on invalid session", async () => { mockSession.current = (() => new Promise<Session>((_, reject) => { reject(new Error("Invalid session")); })) as never; const {container} = render(<RequireAuthentication>Should not see this</RequireAuthentication>); await waitFor(() => { expect(container).toHaveTextContent("Error"); }); }); });
Accessible-Concepts/scrumlr.io
src/components/CookieNotice/CookieNotice.tsx
import "./CookieNotice.scss"; import React from "react"; import {Portal} from "components/Portal"; import {useTranslation} from "react-i18next"; import {CookiePolicy} from "./CookiePolicy"; const COOKIE_CONSENT_NAME = "scrumlr_cookieConsent"; export const CookieNotice = () => { const {t} = useTranslation(); const [showCookieNotice, setShowCookieNotice] = React.useState<boolean>(true); const [showCookiePolicy, setShowCookiePolicy] = React.useState<boolean>(false); const toggleShowCookiePolicy = () => { setShowCookiePolicy((currValue) => !currValue); }; // show cookie notice if there's no cookie in local storage const shouldShowCookieNotice = !localStorage.getItem(COOKIE_CONSENT_NAME); /** * Saves cookie consent to storage. * @param value: true or false, depending on given consent for cookies * @param key: scrumlrCookieName, i.e. scrumlr_consent */ const saveToStorage = (key: string, value: string) => { localStorage.setItem(key, value); }; /** * Sets cookie consent value i.e. scrumlrCookieName true. */ const accept = () => { if (shouldShowCookieNotice) { saveToStorage(COOKIE_CONSENT_NAME, "true"); setShowCookieNotice(false); } }; /** * Sets cookie consent value i.e. scrumlrCookieName false. */ const decline = () => { if (shouldShowCookieNotice) { saveToStorage(COOKIE_CONSENT_NAME, "false"); setShowCookieNotice(false); } }; const openPolicy = () => { setShowCookiePolicy(true); }; // prevents cookie notice from being shown if scrumlrCookieName is set in localStorage if (!shouldShowCookieNotice || !showCookieNotice) return null; return ( <Portal onClose={() => { setShowCookieNotice(false); accept(); }} darkBackground={false} > <div className="cookie-notice"> <div className="cookie-notice__header"> <h3>Cookies</h3> </div> <div className="cookie-notice__body"> <p>{t("CookieNotice.description")}</p> </div> <div className="cookie-notice__buttons"> <button className="cookie-notice__button-cookie-policy" type="button" onClick={openPolicy}> {t("CookieNotice.learnMore")} </button> <button className="cookie-notice__button-decline" type="button" onClick={decline}> {t("CookieNotice.decline")} </button> <button className="cookie-notice__button-accept" type="button" color="primary" onClick={accept}> {t("CookieNotice.accept")} </button> </div> <CookiePolicy accept={accept} decline={decline} onClose={toggleShowCookiePolicy} show={showCookiePolicy} darkBackground /> </div> </Portal> ); };
Accessible-Concepts/scrumlr.io
src/components/DotButton/__tests__/DotButton.test.tsx
import {fireEvent} from "@testing-library/react"; import {DotButton} from "components/DotButton"; import {render} from "testUtils"; describe("DotButton", () => { test("should render correctly", () => { const dotButton = render( <DotButton> <span>test-text</span> </DotButton> ); expect(dotButton.container).toMatchSnapshot(); }); test("should render correctly with additional classname", () => { const dotButton = render( <DotButton className="test-classname"> <span>test-text</span> </DotButton> ); expect(dotButton.container).toMatchSnapshot(); }); test("should call 'onClick' if given", () => { const mockOnClick = jest.fn(); const dotButton = render(<DotButton onClick={mockOnClick} />); fireEvent.click(dotButton.container.getElementsByTagName("button")[0]); expect(mockOnClick).toHaveBeenCalled(); }); });
Accessible-Concepts/scrumlr.io
src/routes/Board/index.ts
<filename>src/routes/Board/index.ts export * from "./Board"; export * from "./BoardGuard";
Accessible-Concepts/scrumlr.io
src/components/MenuBars/MenuItem/variants/VoteConfigurationButton.tsx
<reponame>Accessible-Concepts/scrumlr.io import {useState, VFC} from "react"; import {DropdownToggleButton} from "components/MenuBars/MenuItem/DropdownToggleButton"; import {TabIndex} from "constants/tabIndex"; import {ReactComponent as VoteIcon} from "assets/icon-vote.svg"; import store, {useAppSelector} from "store"; import Dropdown from "components/Dropdown"; import "./VoteConfigurationButton.scss"; import {ActionFactory} from "store/action"; import {useTranslation} from "react-i18next"; import {Toggle} from "../../../Toggle"; type VoteConfigurationButtonProps = { tabIndex?: number; }; export const VoteConfigurationButton: VFC<VoteConfigurationButtonProps> = (props) => { const {t} = useTranslation(); const [tabable, setTabable] = useState(false); const [numberOfVotes, setNumberOfVotes] = useState(5); const [allowMultipleVotesPerNote, setAllowMultipleVotesPerNote] = useState(true); const [showVotesOfOthers, setShowVotesOfOthers] = useState(false); const state = useAppSelector((rootState) => ({activeVoting: rootState.board.data?.voting === "active", boardId: rootState.board.data?.id})); const focusOnTab = (tabIndex: number) => { if (tabable) { return props.tabIndex ? props.tabIndex + tabIndex : TabIndex.default; } return TabIndex.disabled; }; const startVoting = () => { store.dispatch( ActionFactory.addVoteConfiguration({ boardId: state.boardId!, voteLimit: numberOfVotes, showVotesOfOtherUsers: showVotesOfOthers, allowMultipleVotesPerNote, }) ); store.dispatch(ActionFactory.editBoard({id: state.boardId!, voting: "active"})); }; const stopVoting = () => { store.dispatch(ActionFactory.editBoard({id: state.boardId!, voting: "disabled"})); }; const cancelVoting = () => { store.dispatch(ActionFactory.cancelVoting(state.boardId!)); }; return ( <DropdownToggleButton active={state.activeVoting} tabIndex={props.tabIndex ?? TabIndex.default} setTabable={setTabable} direction="left" label={t("VoteConfigurationButton.label")} icon={VoteIcon} > {state.activeVoting && ( <Dropdown className="vote-dropdown"> <Dropdown.Main> <Dropdown.ItemButton className="vote-dropdown__item-button" onClick={() => { stopVoting(); }} onTouchEnd={() => { stopVoting(); }} tabIndex={focusOnTab(1)} > <label>{t("VoteConfigurationButton.stopTimer")}</label> </Dropdown.ItemButton> <Dropdown.ItemButton className="vote-dropdown__item-button" onClick={() => { cancelVoting(); }} onTouchEnd={() => { cancelVoting(); }} tabIndex={focusOnTab(2)} > <label>{t("VoteConfigurationButton.cancelTimer")}</label> </Dropdown.ItemButton> </Dropdown.Main> </Dropdown> )} {!state.activeVoting && ( <Dropdown className="vote-dropdown"> <Dropdown.Main> <Dropdown.ItemButton className="vote-dropdown__item-button" onClick={(e) => { e.stopPropagation(); setAllowMultipleVotesPerNote((prev) => !prev); }} onTouchEnd={() => { setAllowMultipleVotesPerNote((prev) => !prev); }} tabIndex={focusOnTab(1)} > <label>{t("VoteConfigurationButton.allowMultipleVotesPerNote")}</label> <Toggle active={allowMultipleVotesPerNote} /> </Dropdown.ItemButton> <Dropdown.ItemButton className="vote-dropdown__item-button" onClick={(e) => { e.stopPropagation(); setShowVotesOfOthers((prev) => !prev); }} onTouchEnd={() => { setShowVotesOfOthers((prev) => !prev); }} tabIndex={focusOnTab(2)} > <label>{t("VoteConfigurationButton.showVotesOfOthers")}</label> <Toggle active={!showVotesOfOthers} /> </Dropdown.ItemButton> <Dropdown.ItemButton tabIndex={focusOnTab(3)} className="vote-dropdown__item-button" onClick={(e) => { e.stopPropagation(); }} > <label>{t("VoteConfigurationButton.numberOfVotes")}</label> <button onClick={(e) => { e.stopPropagation(); setNumberOfVotes((prev) => Math.min(++prev, 99)); }} onTouchEnd={() => { setNumberOfVotes((prev) => Math.min(++prev, 99)); }} tabIndex={focusOnTab(6)} className="vote-dropdown__vote-button" > + </button> <input tabIndex={focusOnTab(5)} value={numberOfVotes} onClick={(e) => e.stopPropagation()} onChange={(e) => setNumberOfVotes(parseInt(e.target.value, 10))} /> <button onClick={(e) => { e.stopPropagation(); setNumberOfVotes((prev) => Math.max(--prev, 0)); }} onTouchEnd={() => { setNumberOfVotes((prev) => Math.max(--prev, 0)); }} tabIndex={focusOnTab(4)} className="vote-dropdown__vote-button" > - </button> </Dropdown.ItemButton> </Dropdown.Main> <Dropdown.Footer> <Dropdown.ItemButton className="vote-dropdown__item-button" onClick={() => { startVoting(); }} onTouchEnd={() => { startVoting(); }} tabIndex={focusOnTab(7)} > <label>{t("VoteConfigurationButton.startTimer")}</label> </Dropdown.ItemButton> </Dropdown.Footer> </Dropdown> )} </DropdownToggleButton> ); };
Accessible-Concepts/scrumlr.io
src/store/middleware/voteConfiguration.ts
<gh_stars>10-100 import {AnyAction, Dispatch, MiddlewareAPI} from "redux"; import {ApplicationState} from "types/store"; import {API} from "api"; import {Toast} from "utils/Toast"; import {ActionType, ReduxAction} from "store/action"; import {StatusResponse} from "types"; export const passVoteConfigurationMiddlware = async (stateAPI: MiddlewareAPI<Dispatch<AnyAction>, ApplicationState>, dispatch: Dispatch, action: ReduxAction) => { /** * New vote configuration added by the moderator/admin */ if (action.type === ActionType.AddVoteConfiguration) { const response = (await API.addVoteConfiguration(action.voteConfiguration)) as StatusResponse; if (response.status === "Error") { Toast.error(response.description); } } };
Accessible-Concepts/scrumlr.io
src/components/MenuBars/index.ts
<gh_stars>10-100 export * from "./MenuBars";
Accessible-Concepts/scrumlr.io
src/components/Column/Column.tsx
<reponame>Accessible-Concepts/scrumlr.io<filename>src/components/Column/Column.tsx import "./Column.scss"; import {Color, getColorClassName} from "constants/colors"; import {NoteInput} from "components/NoteInput"; import {useRef} from "react"; import {useDrop} from "react-dnd"; import classNames from "classnames"; import store, {useAppSelector} from "store"; import {ActionFactory} from "store/action"; import {ReactComponent as visibleIcon} from "assets/icon-visible.svg"; import {ReactComponent as hiddenIcon} from "assets/icon-hidden.svg"; import {TabIndex} from "constants/tabIndex"; import Parse from "parse"; import _ from "underscore"; import {Note} from "../Note"; const MAX_NOTE_LENGTH = 1024; export interface ColumnProps { id: string; name: string; color: Color; hidden: boolean; currentUserIsModerator: boolean; tabIndex?: number; } export const Column = ({id, name, color, hidden, currentUserIsModerator, tabIndex}: ColumnProps) => { const state = useAppSelector( (applicationState) => ({ notes: applicationState.notes.filter( (note) => (applicationState.board.data?.showNotesOfOtherUsers || Parse.User.current()?.id === note.author) && note.columnId === id && note.parentId == null ), votes: applicationState.votes.filter( (vote) => vote.votingIteration === applicationState.board.data?.votingIteration && (applicationState.board.data?.voting === "disabled" || applicationState.voteConfiguration.showVotesOfOtherUsers || vote.user === Parse.User.current()?.id) ), completedVotes: applicationState.votes.filter((vote) => { if (applicationState.board.data?.voting === "disabled") { // map on vote results of the last voting iteration return vote.votingIteration === applicationState.board.data?.votingIteration; } // map on vote results of the previous, completed voting iteration // FIXME we'll have to keep track of cancelled voting iterations here since they'll be included in the results return vote.votingIteration === (applicationState.board.data?.votingIteration || 0) - 1; }), users: applicationState.users, board: { showAuthors: applicationState.board.data?.showAuthors, voting: applicationState.board.data?.voting, moderation: applicationState.board.data?.moderation, }, }), _.isEqual ); const columnRef = useRef<HTMLDivElement>(null); const [{isOver, canDrop}, drop] = useDrop(() => ({ accept: ["NOTE", "STACK"], drop: (item: {id: string; columnId: string}, monitor) => { if (item.columnId !== id && !monitor.didDrop()) { store.dispatch(ActionFactory.dragNote({id: item.id, columnId: id})); } }, collect: (monitor) => ({isOver: monitor.isOver(), canDrop: monitor.canDrop()}), canDrop: (item: {id: string; columnId: string}) => item.columnId !== id, })); if (columnRef.current && isOver) { const rect = columnRef.current.getBoundingClientRect(); if (rect.left <= 0 || rect.right >= document.documentElement.clientWidth) { columnRef.current.scrollIntoView({inline: "start", behavior: "smooth"}); } } const Icon = hidden ? hiddenIcon : visibleIcon; return ( <section className={`column ${getColorClassName(color)}`} ref={columnRef}> <div className="column__content"> <div className="column__header"> <div className="column__header-title"> <h2 className="column__header-text">{name}</h2> <span className="column__header-card-number">{state.notes.length}</span> {currentUserIsModerator && ( <div className="column__header-toggle"> <button tabIndex={TabIndex.disabled} className="column__header-toggle-button" onClick={() => store.dispatch(ActionFactory.editColumn({columnId: id, hidden: !hidden}))} > <Icon className="column__header-toggle-button-icon" /> </button> </div> )} </div> <NoteInput columnId={id} tabIndex={tabIndex} maxNoteLength={MAX_NOTE_LENGTH} /> </div> <div tabIndex={TabIndex.disabled} className={classNames("column__notes-wrapper", {"column__notes-wrapper--isOver": isOver && canDrop})} ref={drop}> <ul className="column__note-list"> {state.notes .filter((note) => note.positionInStack === -1 || note.positionInStack === 0) .map((note) => ({...note, votes: state.completedVotes.filter((vote) => vote.note === note.id).length})) // It seems that Firefox and Chrome have different orders of notes in the array. Therefore, we need to distinguish between the undefined states. .sort((a, b) => { if (a.createdAt === undefined) return -1; if (b.createdAt === undefined) return 1; const voteDiff = b.votes - a.votes; if (voteDiff === 0) { return b.createdAt!.getTime() - a.createdAt!.getTime(); } return voteDiff; }) .map((note, noteIndex) => ( <Note showAuthors={state.board.showAuthors!} currentUserIsModerator={currentUserIsModerator} key={note.id} noteId={note.id} text={note.text} authorId={note.author} authorName={state.users.all.filter((user) => user.id === note.author)[0]?.displayName} columnId={id} columnName={name} columnColor={color} childrenNotes={state.notes .filter((n) => note.id && note.id === n.parentId) .sort((a, b) => a.positionInStack - b.positionInStack) .map((n) => ({...n, authorName: state.users.all.filter((user) => user.id === n.author)[0]?.displayName})) .map((n) => ({...n, votes: state.votes.filter((vote) => vote.note === n.id)}))} votes={state.votes.filter((vote) => vote.note === note.id)} allVotesOfUser={state.votes.filter((vote) => vote.user === Parse.User.current()?.id)} activeVoting={state.board.voting! === "active"} activeModeration={{userId: state.board.moderation!.userId, status: state.board.moderation!.status === "active"}} focus={note.focus} tabIndex={TabIndex.Note + (tabIndex! - TabIndex.Column) * TabIndex.Note + noteIndex * 3} /> ))} </ul> </div> </div> </section> ); };
Accessible-Concepts/scrumlr.io
src/components/Infobar/Infobar.tsx
<reponame>Accessible-Concepts/scrumlr.io import {Timer} from "components/Timer"; import {VoteDisplay} from "components/Votes/VoteDisplay"; import ReactDOM from "react-dom"; import "./Infobar.scss"; import _ from "underscore"; import {useAppSelector} from "store"; import Parse from "parse"; export const InfoBar = () => { const state = useAppSelector( (applicationState) => ({ endTime: applicationState.board.data?.timerUTCEndTime, activeVoting: applicationState.board.data?.voting === "active", possibleVotes: applicationState.voteConfiguration.voteLimit, usedVotes: applicationState.votes.filter((vote) => vote.votingIteration === applicationState.voteConfiguration.votingIteration && vote.user === Parse.User.current()?.id) .length, }), _.isEqual ); return ReactDOM.createPortal( <aside className="info-bar"> {state.endTime && <Timer endTime={state.endTime} />} {state.activeVoting && <VoteDisplay usedVotes={state.usedVotes} possibleVotes={state.possibleVotes} />} </aside>, document.getElementById("root")! ); };
Accessible-Concepts/scrumlr.io
src/components/ToggleButton/ToggleButton.tsx
<reponame>Accessible-Concepts/scrumlr.io<filename>src/components/ToggleButton/ToggleButton.tsx import classNames from "classnames"; import {TabIndex} from "constants/tabIndex"; import "./ToggleButton.scss"; import {Toggle} from "../Toggle"; type ToggleButtonProps<T> = { /** * Additional CSS classes. */ className?: string; /** * The values between which is toggled. * If the current value of the toggle equals the first value, the toggle will be on the left. * If the current value of the toggle equals the second value, the toggle will be on the right. */ values: [T, T]; /** * Current value of the toggle. */ value: T; /** * Triggered when the toggle changes. * The callback will return the new value of the toggle. */ onToggle?: (value: T) => void; /** * Disable the toggle. */ disabled?: boolean; /** * Triggered if the toggle changes to the left. */ onLeft?: () => void; /** * Triggered if the toggle changes to the right. */ onRight?: () => void; /** * Allows tabIndex */ tabIndex?: number; }; export const ToggleButton = <T extends unknown>(props: ToggleButtonProps<T>) => { const onClick = () => { const newValue = props.value === props.values[0] ? props.values[1] : props.values[0]; props.onToggle?.(newValue); if (newValue === props.values[0]) { props.onLeft?.(); } else { props.onRight?.(); } }; const isActive = props.value === props.values[1]; return ( <button disabled={props.disabled} onClick={onClick} className={classNames("toggle-button", props.className)} aria-pressed={isActive} tabIndex={props.tabIndex ?? TabIndex.disabled} > <Toggle active={isActive} disabled={props.disabled} /> </button> ); };
Accessible-Concepts/scrumlr.io
src/components/BoardHeader/HeaderMenu/BoardOptions/ShowOtherUsersNotesOption.tsx
import store, {useAppSelector} from "store"; import {ApplicationState} from "types/store"; import {ActionFactory} from "store/action"; import "../BoardSettings/BoardSettings.scss"; import {useTranslation} from "react-i18next"; import {BoardOption} from "./BoardOption"; import {BoardOptionButton} from "./BoardOptionButton"; import {BoardOptionToggle} from "./BoardOptionToggle"; export const ShowOtherUsersNotesOption = () => { const {t} = useTranslation(); const state = useAppSelector((applicationState: ApplicationState) => ({ board: applicationState.board.data!, })); return ( <BoardOption data-testid="note"> <BoardOptionButton label={state.board!.showNotesOfOtherUsers ? t("ShowOtherUsersNotesOption.hide") : t("ShowOtherUsersNotesOption.show")} onClick={() => { store.dispatch(ActionFactory.editBoard({id: state.board!.id, showNotesOfOtherUsers: !state.board!.showNotesOfOtherUsers})); }} > <BoardOptionToggle active={state.board.showNotesOfOtherUsers} /> </BoardOptionButton> </BoardOption> ); };
Accessible-Concepts/scrumlr.io
src/types/voteConfiguration.ts
import Parse from "parse"; /** * The representation of a vote configuration on the server. */ export interface VoteConfigurationServerModel extends Parse.Object { board: Parse.Object; votingIteration: number; voteLimit: number; allowMultipleVotesPerNote: boolean; showVotesOfOtherUsers: boolean; } /** * The representation of a vote configuration on the client. */ export interface VoteConfigurationClientModel { boardId: string; votingIteration: number; voteLimit: number; allowMultipleVotesPerNote: boolean; showVotesOfOtherUsers: boolean; } type EditableVoteConfigurationAttributes = { voteLimit: number; allowMultipleVotesPerNote: boolean; showVotesOfOtherUsers: boolean; }; export type VoteConfiguration = {boardId: string} & EditableVoteConfigurationAttributes; export const mapVoteConfigurationServerToClientModel = (voteConfiguration: VoteConfigurationServerModel): VoteConfigurationClientModel => ({ boardId: voteConfiguration.get("board").id, votingIteration: voteConfiguration.get("votingIteration"), voteLimit: voteConfiguration.get("voteLimit"), allowMultipleVotesPerNote: voteConfiguration.get("allowMultipleVotesPerNote"), showVotesOfOtherUsers: voteConfiguration.get("showVotesOfOtherUsers"), });
Accessible-Concepts/scrumlr.io
src/components/Infobar/__tests__/Infobar.test.tsx
<gh_stars>0 import {render} from "@testing-library/react"; import configureStore from "redux-mock-store"; import {Provider} from "react-redux"; import {InfoBar} from "../Infobar"; const mockStore = configureStore(); const createInfoBar = (activeVoting: boolean, activeTimer: boolean) => { const initialState = { board: { data: { timerUTCEndTime: activeTimer ? new Date(12345) : undefined, voting: activeVoting ? "active" : "disabled", }, }, voteConfiguration: { voteLimit: 5, }, votes: [], users: { admins: [], basic: [], all: [], }, }; return ( <Provider store={mockStore(initialState)}> <InfoBar /> </Provider> ); }; describe("InfoBar", () => { beforeEach(() => { const root = global.document.createElement("div"); root.setAttribute("id", "root"); global.document.body.appendChild(root); }); describe("should render correctly", () => { test("with disabled voting and timer", () => { const {container} = render(createInfoBar(false, false), {container: document.getElementById("root")!}); expect(container).toMatchSnapshot(); }); test("with disabled voting and active timer", () => { const {container} = render(createInfoBar(false, true), {container: document.getElementById("root")!}); expect(container).toMatchSnapshot(); }); test("with active voting and disabled timer", () => { const {container} = render(createInfoBar(true, false), {container: document.getElementById("root")!}); expect(container).toMatchSnapshot(); }); test("with active voting and timer", () => { const {container} = render(createInfoBar(true, true), {container: document.getElementById("root")!}); expect(container).toMatchSnapshot(); }); }); });
Accessible-Concepts/scrumlr.io
server/src/cloud/column.ts
<filename>server/src/cloud/column.ts import {newObjectId} from "parse-server/lib/cryptoUtils"; import {StatusResponse} from "types"; import {requireValidBoardAdmin} from "./permission"; import {api} from "./util"; import {serverConfig} from "../index"; import Color, {isOfTypeColor} from "../util/Color"; export interface AddColumnRequest { boardId: string; column: { name: string; color: Color; hidden: boolean; }; } export interface DeleteColumnRequest { boardId: string; columnId: string; } export interface EditColumnRequest { boardId: string; column: { columnId: string; name?: string; color?: Color; hidden?: boolean; }; } export const initializeColumnFunctions = () => { api<AddColumnRequest, StatusResponse>("addColumn", async (user, request) => { await requireValidBoardAdmin(user, request.boardId); const board = await new Parse.Query("Board").get(request.boardId, {useMasterKey: true}); // Check if the board exists if (!board) { return {status: "Error", description: `Board '${request.boardId}' does not exist`}; } const columns = board.get("columns"); if (!isOfTypeColor(request.column.color)) { throw new Error(`color ${request.column.color} is not allowed for columns`); } columns[newObjectId(serverConfig.objectIdSize)] = { name: request.column.name, color: request.column.color, hidden: request.column.hidden, }; await board.save(null, {useMasterKey: true}); return {status: "Success", description: `New column added`}; }); api<DeleteColumnRequest, StatusResponse>("deleteColumn", async (user, request) => { await requireValidBoardAdmin(user, request.boardId); // TODO delete notes & votes const board = await new Parse.Query("Board").get(request.boardId, {useMasterKey: true}); // Check if the board exists if (!board) { return {status: "Error", description: `Board '${request.boardId}' does not exist`}; } const columns = board.get("columns"); delete columns[request.columnId]; await board.save(null, {useMasterKey: true}); return {status: "Success", description: `Column ${request.columnId} deleted`}; }); api<EditColumnRequest, StatusResponse>("editColumn", async (user, request) => { await requireValidBoardAdmin(user, request.boardId); const board = await new Parse.Query("Board").get(request.boardId, {useMasterKey: true}); // Check if the board exists if (!board) { return {status: "Error", description: `Board '${request.boardId}' does not exist`}; } const columns = board.get("columns"); if (request.column.name) { columns[request.column.columnId].name = request.column.name; } if (request.column.color) { if (isOfTypeColor(request.column.color)) { columns[request.column.columnId].color = request.column.color; } else { throw new Error(`specified column color '${request.column.color}' is not allowed`); } } if (request.column.hidden != undefined) { columns[request.column.columnId].hidden = request.column.hidden; } await board.save(null, {useMasterKey: true}); return {status: "Success", description: `Column ${request.column.columnId} edited`}; }); };
Accessible-Concepts/scrumlr.io
src/components/HeroIllustration/HeroIllustration.tsx
<filename>src/components/HeroIllustration/HeroIllustration.tsx import Panel01 from "assets/hero/scrumlr-lp-01.svg"; import Panel02 from "assets/hero/scrumlr-lp-02.svg"; import Panel03 from "assets/hero/scrumlr-lp-03.svg"; import Panel04 from "assets/hero/scrumlr-lp-04.svg"; import Panel05 from "assets/hero/scrumlr-lp-05.svg"; import Panel06 from "assets/hero/scrumlr-lp-06.svg"; import Panel07 from "assets/hero/scrumlr-lp-07.svg"; import Panel08 from "assets/hero/scrumlr-lp-08.svg"; import Panel09 from "assets/hero/scrumlr-lp-09.svg"; import Panel10 from "assets/hero/scrumlr-lp-10.svg"; import Panel11 from "assets/hero/scrumlr-lp-11.svg"; import Panel12 from "assets/hero/scrumlr-lp-12.svg"; import ActionbarUser from "assets/hero/scrumlr_actionbar_user.svg"; import ActionbarModerator from "assets/hero/scrumlr_actionbar_mod.svg"; import {FC} from "react"; import classNames from "classnames"; import "./HeroIllustration.scss"; export interface HeroIllustrationProps { className?: string; } export const HeroIllustration: FC<HeroIllustrationProps> = ({className}) => ( <aside className={classNames("hero-illustration", className)} aria-hidden> <div className="hero-illustration__position-anchor"> <div className="hero-illustration__grid"> <img src={ActionbarUser} className="hero-illustration__actionbar-user" alt="" /> <img src={ActionbarModerator} className="hero-illustration__actionbar-moderator" alt="" /> <div className="hero-illustration__tile"> <img src={Panel01} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel02} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel03} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel04} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel05} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel06} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel07} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel08} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel09} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel10} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel11} className="hero-illustration__tile-image" alt="" /> </div> <div className="hero-illustration__tile"> <img src={Panel12} className="hero-illustration__tile-image" alt="" /> </div> </div> </div> </aside> );
Accessible-Concepts/scrumlr.io
src/components/Timer/index.ts
<gh_stars>10-100 export * from "./Timer";
Accessible-Concepts/scrumlr.io
src/utils/__tests__/timer.test.ts
<reponame>Accessible-Concepts/scrumlr.io import {mocked} from "ts-jest/utils"; import {callAPI} from "api/callApi"; import {getBrowserServerTimeDifference} from "../timer"; jest.mock("api/callApi"); const mockedCallApi = mocked(callAPI); describe("Timer", () => { test("getBrowserServerTimeDifference", async () => { mockedCallApi.mockImplementation( () => new Promise((resolve) => { resolve(new Date(1234).toUTCString()); }) ); const value = await getBrowserServerTimeDifference(); expect(value).toBe(Date.parse(new Date().toUTCString()) - Date.parse(new Date(1234).toUTCString())); }); });
Accessible-Concepts/scrumlr.io
src/components/Avatar/__tests__/Avatar.test.tsx
<reponame>Accessible-Concepts/scrumlr.io<gh_stars>10-100 import {render} from "testUtils"; import {Avatar} from "../Avatar"; describe("Avatar", () => { test("properties will be generated by the seed", () => { const {container} = render(<Avatar seed="2" />); expect(container).toMatchSnapshot(); }); test("if seed is set properties will be overwritten", () => { const {container} = render(<Avatar seed="1" clotheType="BlazerSweater" />); expect(container.querySelector("#Clothing\\/Hoodie")).toBeInTheDocument(); expect(container.querySelector("#Clothing\\/BlazerSweater")).not.toBeInTheDocument(); }); test("seed will generate facial hair", () => { const {container} = render(<Avatar seed="1" />); expect(container.querySelector("[id^=Facial]")).toBeInTheDocument(); }); test("seed will leave out facial hair", () => { const {container} = render(<Avatar seed="0" />); expect(container.querySelector("[id^=Facial]")).not.toBeInTheDocument(); }); test("seed will generate accessories", () => { const {container} = render(<Avatar seed="2" />); expect(container.querySelector("[id^=Top\\/_Resources]")).toBeInTheDocument(); }); test("seed will leave out accessories", () => { const {container} = render(<Avatar seed="0" />); expect(container.querySelector("[id^=Top\\/_Resources]")).not.toBeInTheDocument(); }); test("seed will generate facial hair and accessories", () => { const {container} = render(<Avatar seed="2" />); expect(container.querySelector("[id^=Facial]")).toBeInTheDocument(); expect(container.querySelector("[id^=Top\\/_Resources]")).toBeInTheDocument(); }); test("seed will generate facial hair but leave out accessories", () => { const {container} = render(<Avatar seed="1" />); expect(container.querySelector("[id^=Facial]")).toBeInTheDocument(); expect(container.querySelector("[id^=Top\\/_Resources]")).not.toBeInTheDocument(); }); test("seed will leave out facial hair but generate accessories", () => { const {container} = render(<Avatar seed="3" />); expect(container.querySelector("[id^=Facial]")).not.toBeInTheDocument(); expect(container.querySelector("[id^=Top\\/_Resources]")).toBeInTheDocument(); }); test("seed will leave out facial hair and accessories", () => { const {container} = render(<Avatar seed="0" />); expect(container.querySelector("[id^=Facial]")).not.toBeInTheDocument(); expect(container.querySelector("[id^=Top\\/_Resources]")).not.toBeInTheDocument(); }); test("seed will define an accent color class", () => { const {container} = render(<Avatar seed="2" />); expect(container.firstChild).toHaveClass("accent-color__lean-lilac"); }); });
Accessible-Concepts/scrumlr.io
src/components/Votes/Votes.tsx
<reponame>Accessible-Concepts/scrumlr.io<gh_stars>0 import {useAppSelector} from "store"; import "./Votes.scss"; import classNames from "classnames"; import {VoteClientModel} from "types/vote"; import Parse from "parse"; import {FC} from "react"; import {TabIndex} from "constants/tabIndex"; import {VoteButtons} from "./VoteButtons"; type VotesProps = { className?: string; noteId: string; votes: VoteClientModel[]; activeVoting: boolean; tabIndex?: number; usedVotesAsUser: number; }; export const Votes: FC<VotesProps> = (props) => { const voteConfiguration = useAppSelector((state) => state.voteConfiguration); const ownNoteVotes = props.votes.filter((vote) => vote.user === Parse.User.current()?.id); const showAddVoteButton = props.activeVoting && (voteConfiguration?.allowMultipleVotesPerNote || (!voteConfiguration?.allowMultipleVotesPerNote && ownNoteVotes.length === 0)); return ( <div className={classNames("votes", props.className)}> {props.votes.length > 0 && <VoteButtons.Remove {...props} tabIndex={props.tabIndex ? props.tabIndex + 1 : TabIndex.default} ownVotes={ownNoteVotes} />} {showAddVoteButton && ( <VoteButtons.Add {...props} tabIndex={props.tabIndex ? props.tabIndex + 2 : TabIndex.default} disabled={props.usedVotesAsUser === voteConfiguration.voteLimit} /> )} </div> ); };
Accessible-Concepts/scrumlr.io
src/store/reducer/users.ts
<reponame>Accessible-Concepts/scrumlr.io import {UsersState} from "types/store"; import Parse from "parse"; import union from "lodash/union"; import without from "lodash/without"; import {ActionType, ReduxAction} from "../action"; const mapReadyState = (state: Omit<UsersState, "usersMarkedReady">, readyUsers: string[] = []) => ({ admins: state.admins.map((current) => ({...current, ready: Boolean(readyUsers.find((user) => user === current.id))})), basic: state.basic.map((current) => ({...current, ready: Boolean(readyUsers.find((user) => user === current.id))})), all: state.all.map((current) => ({...current, ready: Boolean(readyUsers.find((user) => user === current.id))})), usersMarkedReady: readyUsers, usersRaisedHands: state.usersRaisedHands, }); const mapRaisedHandState = (state: Omit<UsersState, "usersRaisedHands">, raisedHandUsers: string[] = []) => ({ admins: state.admins.map((current) => ({...current, raisedHand: Boolean(raisedHandUsers.find((user) => user === current.id))})), basic: state.basic.map((current) => ({...current, raisedHand: Boolean(raisedHandUsers.find((user) => user === current.id))})), all: state.all.map((current) => ({...current, raisedHand: Boolean(raisedHandUsers.find((user) => user === current.id))})), usersRaisedHands: raisedHandUsers, usersMarkedReady: state.usersMarkedReady, }); // eslint-disable-next-line default-param-last export const usersReducer = (state: UsersState = {usersRaisedHands: [], usersMarkedReady: [], admins: [], basic: [], all: []}, action: ReduxAction): UsersState => { switch (action.type) { case ActionType.SetUserReadyStatus: { let {usersMarkedReady} = state; if (usersMarkedReady !== undefined) { const userId = Parse.User.current()!.id; if (action.ready) { usersMarkedReady = union(usersMarkedReady, [userId]); } else { usersMarkedReady = without(usersMarkedReady, userId); } return mapReadyState(state, usersMarkedReady); } return state; } case ActionType.SetRaisedHandStatus: { let {usersRaisedHands} = state; if (usersRaisedHands !== undefined) { if (action.configuration.raisedHand) { usersRaisedHands = union(usersRaisedHands, action.configuration.userId); } else { usersRaisedHands = usersRaisedHands.filter((id) => action.configuration.userId.find((user) => user === id) === undefined); } return mapRaisedHandState(state, usersRaisedHands); } return state; } case ActionType.InitializeBoard: case ActionType.UpdatedBoard: { const newState = mapReadyState(state, action.board.usersMarkedReady); return mapRaisedHandState(newState, action.board.usersRaisedHands); } case ActionType.SetUsers: { const newState = { admins: state.admins, basic: state.basic, all: state.all, usersMarkedReady: state.usersMarkedReady, usersRaisedHands: state.usersRaisedHands, }; if (action.admin) { newState.admins = action.users; } else { newState.basic = action.users; } // Update state and keep order newState.basic.forEach((member) => { if (newState.all.find((user) => user.id === member.id)) { newState.all.find((user) => user.id === member.id)!.admin = false; } else { newState.all.push(member); } }); // Update state and keep order newState.admins.forEach((member) => { if (newState.all.find((admin) => admin.id === member.id)) { newState.all.find((admin) => admin.id === member.id)!.admin = true; } else { newState.all.push(member); } }); // Remove outdated user newState.all = newState.all.filter((member) => newState.admins.find((admin) => admin.id === member.id) || newState.basic.find((user) => user.id === member.id)); return mapRaisedHandState(mapReadyState(newState, state.usersMarkedReady), state.usersRaisedHands); } case ActionType.SetUserStatus: { const newState = { admins: state.admins, basic: state.basic, all: state.all, usersMarkedReady: state.usersMarkedReady, usersRaisedHands: state.usersRaisedHands, }; const user = newState.all.find((member) => member.id === action.userId); if (user) { user.online = action.status; } return mapRaisedHandState(mapReadyState(newState, state.usersMarkedReady), state.usersRaisedHands); } case ActionType.UpdateUser: { const newState = { admins: state.admins, basic: state.basic, all: state.all, usersMarkedReady: state.usersMarkedReady, usersRaisedHands: state.usersRaisedHands, }; return mapRaisedHandState(mapReadyState(newState, state.usersMarkedReady), state.usersRaisedHands); } default: { return state; } } };
Accessible-Concepts/scrumlr.io
server/src/util/Color.ts
const colors = ["backlog-blue", "grooming-green", "lean-lilac", "online-orange", "planning-pink", "poker-purple", "retro-red"] as const; export type Color = typeof colors[number]; export function isOfTypeColor(input: string): input is Color { return (colors as readonly string[]).includes(input); } export default Color;
Accessible-Concepts/scrumlr.io
src/store/action/__tests__/column.test.ts
import {AddColumnRequest} from "types/column"; import {AssertTypeEqual} from "testUtils"; import {ColumnActionFactory, ColumnActionType, ColumnReduxAction} from "store/action/column"; import {ReduxAction} from "store/action"; describe("column actions", () => { test("equal number of action types and factory functions", () => { expect(Object.keys(ColumnActionType).length).toEqual(Object.keys(ColumnActionFactory).length); }); describe("add column", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof ColumnActionFactory.addColumn>, ColumnReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof ColumnActionFactory.addColumn>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = ColumnActionFactory.addColumn({name: "Name", color: "planning-pink", hidden: false}); expect(action).toEqual({ column: { color: "planning-pink", hidden: false, name: "Name", } as AddColumnRequest, type: "@@SCRUMLR/addColumn", }); }); }); describe("edit column", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof ColumnActionFactory.editColumn>, ColumnReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof ColumnActionFactory.editColumn>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = ColumnActionFactory.editColumn({columnId: "columnId", name: "<NAME>"}); expect(action).toEqual({ type: "@@SCRUMLR/editColumn", column: { columnId: "columnId", name: "<NAME>", }, }); }); }); describe("delete column", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof ColumnActionFactory.deleteColumn>, ColumnReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof ColumnActionFactory.deleteColumn>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = ColumnActionFactory.deleteColumn("columnId"); expect(action).toEqual({ type: "@@SCRUMLR/deleteColumn", columnId: "columnId", }); }); }); });
Accessible-Concepts/scrumlr.io
server/src/cloud/userOnlineStatus.ts
export const initializeUserOnlineStatus = () => { (Parse.Cloud as any).onLiveQueryEvent(({event, sessionToken}) => { if (event === "ws_disconnect") { const query = new Parse.Query<Parse.Object>("_Session"); query.equalTo("sessionToken", sessionToken); query.first({useMasterKey: true}).then((session) => { if (session) { const user = session.get("user"); user.remove("boards", session.id); user.save(null, {useMasterKey: true}); } }); } }); };
Accessible-Concepts/scrumlr.io
src/i18n.ts
<gh_stars>0 import i18n from "i18next"; import {initReactI18next} from "react-i18next"; import Backend from "i18next-http-backend"; import LanguageDetector from "i18next-browser-languagedetector"; i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) .init({ backend: { queryStringParams: {v: "1.0.0"}, }, detection: { lookupLocalStorage: "Scrumlr/locale", order: ["localStorage"], caches: ["localStorage"], }, fallbackLng: "en", react: { useSuspense: false, wait: false, }, }); export default i18n;
Accessible-Concepts/scrumlr.io
src/components/MenuBars/MenuItem/DropdownToggleButton.tsx
import React, {useEffect, useState} from "react"; import classNames from "classnames"; import "./MenuItem.scss"; import "./DropdownToggleButton.scss"; import {TabIndex} from "constants/tabIndex"; type DropdownButtonProps = { direction: "left" | "right"; label: string; icon: React.FunctionComponent<React.SVGProps<SVGSVGElement>>; disabled?: boolean; setTabable: React.Dispatch<React.SetStateAction<boolean>>; tabIndex?: number; active?: boolean; }; export const DropdownToggleButton: React.FC<DropdownButtonProps> = (props) => { const [touchHover, setTouchHover] = useState(false); const [showDropdown, setShowDropdown] = useState(false); const Icon = props.icon; useEffect(() => { if (showDropdown) { window.addEventListener("click", () => setShowDropdown(false), {once: true}); } props.setTabable(showDropdown); // eslint-disable-next-line react-hooks/exhaustive-deps }, [showDropdown]); return ( <button className={classNames("menu-item", `menu-item--${props.direction}`, {"dropdown-item--open": showDropdown}, {"menu-item--touch-hover": touchHover})} onClick={() => { setShowDropdown((prev) => !prev); }} onTouchEnd={(e) => { if (!touchHover && document.getElementsByClassName("menu-item--touch-hover").length === 0) { e.preventDefault(); window.addEventListener("click", () => setTouchHover(false), {once: true}); setTouchHover(true); } if (touchHover) { e.preventDefault(); setTouchHover(false); setShowDropdown(true); } }} tabIndex={props.tabIndex ?? TabIndex.default} disabled={props.disabled} > <div className="menu-item__tooltip"> <span className="tooltip__text">{props.label}</span> </div> <Icon className={classNames("menu-item__icon", "menu-item__icon--start", {"menu-item-active": props.active})} /> {props.children} </button> ); };
Accessible-Concepts/scrumlr.io
src/components/TextInputAdornment/TextInputAdornment.tsx
<gh_stars>10-100 import classNames from "classnames"; import {ButtonHTMLAttributes, DetailedHTMLProps, FC} from "react"; import "./TextInputAdornment.scss"; export interface TextInputAdornmentProps extends DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> { title: string; } export const TextInputAdornment: FC<TextInputAdornmentProps> = ({title, className, children, ...other}) => ( <button type="button" className={classNames("text-input-adornment", className)} aria-label={title} title={title} {...other}> {children} </button> );
Accessible-Concepts/scrumlr.io
src/components/Board/Board.tsx
import React, {useEffect, useRef, useState} from "react"; import {getColorClassName} from "constants/colors"; import {ColumnProps} from "components/Column"; import {ReactComponent as RightArrowIcon} from "assets/icon-arrow-next.svg"; import {ReactComponent as LeftArrowIcon} from "assets/icon-arrow-previous.svg"; import {MenuBars} from "components/MenuBars"; import {BoardHeader} from "components/BoardHeader"; import "./Board.scss"; export interface BoardProps { children: React.ReactElement<ColumnProps> | React.ReactElement<ColumnProps>[]; currentUserIsModerator: boolean; } export interface BoardState { showNextButton: boolean; showPreviousButton: boolean; } export interface ColumnState { firstVisibleColumnIndex: number; lastVisibleColumnIndex: number; } export const BoardComponent = ({children, currentUserIsModerator}: BoardProps) => { const [state, setState] = useState<BoardState & ColumnState>({ firstVisibleColumnIndex: 0, lastVisibleColumnIndex: React.Children.count(children), showNextButton: false, showPreviousButton: false, }); const [columnState, setColumnState] = useState<ColumnState>({ firstVisibleColumnIndex: 0, lastVisibleColumnIndex: React.Children.count(children), }); const boardRef = useRef<HTMLDivElement>(null); const columnVisibilityStatesRef = useRef<boolean[]>([]); const intersectionObserverRef = useRef<IntersectionObserver | null>(null); const columnsCount = React.Children.count(children); useEffect(() => { const board = boardRef.current; // disconnect the previous observer, if there is one if (intersectionObserverRef.current !== null) { intersectionObserverRef.current.disconnect(); } if (board) { // initialize column visibility states columnVisibilityStatesRef.current = new Array(React.Children.count(children)); const columnVisibilityStates = columnVisibilityStatesRef.current; columnVisibilityStates.fill(false); // initialize intersection observer const observerOptions = { root: board, rootMargin: "0px", threshold: 1.0, }; const observerCallback: IntersectionObserverCallback = (entries) => { entries.forEach((entry) => { const index = Array.prototype.indexOf.call(board.children, entry.target) - 1; columnVisibilityStates[index] = entry.isIntersecting; }); const firstVisibleColumnIndex = columnVisibilityStates.findIndex((value) => value); const lastVisibleColumnIndex = columnVisibilityStates.lastIndexOf(true); document.getElementById("root")!.setAttribute("column-visibility", lastVisibleColumnIndex < columnsCount - 1 || firstVisibleColumnIndex > 0 ? "collapsed" : "visible"); setColumnState({ firstVisibleColumnIndex, lastVisibleColumnIndex, }); }; const observer = new IntersectionObserver(observerCallback, observerOptions); // observe children const domChildren = board.children; for (let i = 1; i < domChildren.length - 1; i += 1) { observer.observe(domChildren[i]); } // return callback handler that will disconnect the observer on unmount return () => { observer.disconnect(); }; } return undefined; // eslint-disable-next-line react-hooks/exhaustive-deps }, [children]); useEffect(() => { let firstVisibleColumnIndex; let lastVisibleColumnIndex; if (columnState.firstVisibleColumnIndex === -1 && columnState.lastVisibleColumnIndex === -1) { firstVisibleColumnIndex = state.firstVisibleColumnIndex; lastVisibleColumnIndex = state.firstVisibleColumnIndex - 1; } else { firstVisibleColumnIndex = columnState.firstVisibleColumnIndex; lastVisibleColumnIndex = columnState.lastVisibleColumnIndex; } setState({ firstVisibleColumnIndex, lastVisibleColumnIndex, showNextButton: lastVisibleColumnIndex < columnsCount - 1, showPreviousButton: firstVisibleColumnIndex > 0, }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [columnState]); if (!children || columnsCount === 0) { document.getElementById("root")?.setAttribute("column-visibility", "visible"); // Empty board return ( <div className="board--empty"> <style>{`.board { --board__columns: ${columnsCount} }`}</style> <BoardHeader currentUserIsModerator={currentUserIsModerator} /> <MenuBars /> <main className="board" ref={boardRef}> {/* Fixed color - can also be dynamic */} <div className={`board__spacer-left ${getColorClassName("backlog-blue")}`} /> <div className={`board__spacer-right ${getColorClassName("backlog-blue")}`} /> </main> </div> ); } const {firstVisibleColumnIndex, lastVisibleColumnIndex} = state; const columnColors = React.Children.map(children, (child) => child.props.color); const previousColumnIndex = firstVisibleColumnIndex > 0 ? firstVisibleColumnIndex - 1 : columnsCount - 1; const nextColumnIndex = lastVisibleColumnIndex === columnsCount - 1 ? 0 : firstVisibleColumnIndex + 1; const handlePreviousClick = () => { boardRef.current!.children[previousColumnIndex + 1].scrollIntoView({inline: "start", behavior: "smooth"}); }; const handleNextClick = () => { boardRef.current!.children[nextColumnIndex + 1].scrollIntoView({inline: "start", behavior: "smooth"}); }; return ( <> <style>{`.board { --board__columns: ${columnsCount} }`}</style> <BoardHeader currentUserIsModerator={currentUserIsModerator} /> <MenuBars /> {state.showPreviousButton && ( <button className={`board__navigation board__navigation-prev ${getColorClassName(columnColors[previousColumnIndex])}`} onClick={handlePreviousClick} aria-hidden> <LeftArrowIcon className="board__navigation-arrow board__navigation-arrow-prev" /> </button> )} <main className="board" ref={boardRef}> <div className={`board__spacer-left ${getColorClassName(columnColors[0])}`} /> {children} <div className={`board__spacer-right ${getColorClassName(columnColors[columnColors.length - 1])}`} /> </main> {state.showNextButton && ( <button className={`board__navigation board__navigation-next ${getColorClassName(columnColors[Math.min(nextColumnIndex, columnColors.length - 1)])}`} onClick={handleNextClick} aria-hidden > <RightArrowIcon className="board__navigation-arrow board__navigation-arrow-next" /> </button> )} </> ); };
Accessible-Concepts/scrumlr.io
server/src/cloud/auth.ts
<gh_stars>10-100 import {google} from "googleapis"; import axios, {AxiosResponse} from "axios"; import qs from "qs"; import jwt from "jsonwebtoken"; import fs from "fs"; import {publicApi} from "./util"; const { GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, MICROSOFT_CLIENT_ID, MICROSOFT_CLIENT_SECRET, APPLE_CLIENT_ID, APPLE_CLIENT_SECRET, APPLE_PRIVATE_KEY_FILE_PATH, APPLE_KEY_ID, APPLE_TEAM_ID, AUTH_REDIRECT_URI, } = process.env; const getGoogleOAuth2Client = () => { const {OAuth2} = google.auth; return new OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, AUTH_REDIRECT_URI); }; export interface UserInformation { id: string; name: string; idToken?: string; accessToken: string; photoURL: string; } type AccessTokenResponse = AxiosResponse<{ access_token: string; id_token?: string; }>; type GitHubUserInformationResponse = AxiosResponse<{ id: string; login: string; avatar_url: string; }>; type MicrosoftUserInformationResponse = AxiosResponse<{ id: string; displayName: string; }>; export const initializeAuthFunctions = (): void => { if (GOOGLE_CLIENT_ID && GOOGLE_CLIENT_SECRET && AUTH_REDIRECT_URI) { /** * Function generates consent page URL where the code is retrieved * github.com/autodidaktum/google-oauth2-parse-react/blob/master/deploy/cloud/main.js * https://www.npmjs.com/package/googleapis#oauth2-client */ publicApi<{state: string}, string>("googleSignIn", async ({state}) => { const oauth2Client = getGoogleOAuth2Client(); return oauth2Client.generateAuthUrl({ access_type: "offline", // gets refresh_token scope: ["openid", "profile"], state, }); }); /** * 1) Function exchanges the code for access token. * 2) Access token is used to retrieve user information. */ publicApi<{code: string}, UserInformation>("googleVerifySignIn", async ({code}) => { const oauth2Client = getGoogleOAuth2Client(); const {tokens} = await oauth2Client.getToken(code); oauth2Client.setCredentials(tokens); const oauth2 = google.oauth2({ auth: oauth2Client, version: "v2", }); const user = await oauth2.userinfo.get(); return { id: user.data.id, name: user.data.name, idToken: tokens.id_token, accessToken: tokens.access_token, photoURL: user.data.picture, }; }); } if (GITHUB_CLIENT_ID && GITHUB_CLIENT_SECRET && AUTH_REDIRECT_URI) { /** * Function generates consent page URL where the code is retrieved * https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps */ publicApi<{state: string}, string>("githubSignIn", async ({state}) => { const url = new URL("/login/oauth/authorize", "https://github.com"); url.searchParams.append("client_id", GITHUB_CLIENT_ID); url.searchParams.append("scope", "user"); url.searchParams.append("state", state); url.searchParams.append("redirect_uri", AUTH_REDIRECT_URI); return url.toString(); }); /** * 1) Function exchanges code for access token. * 2) Access token is used to retrieve user information. */ publicApi<{code: string}, UserInformation>("githubVerifySignIn", async ({code}) => { const accessTokenRequest = await axios.post<any, AccessTokenResponse>( "https://github.com/login/oauth/access_token", { client_id: GITHUB_CLIENT_ID, client_secret: GITHUB_CLIENT_SECRET, code, }, {headers: {Accept: "application/json"}} ); const accessToken = accessTokenRequest.data.access_token; const user = await axios.get<any, GitHubUserInformationResponse>("https://api.github.com/user", { headers: {Authorization: `token ${accessToken}`, Accept: "application/json"}, }); return { id: user.data.id, name: user.data.login, accessToken, photoURL: user.data.avatar_url, }; }); } if (MICROSOFT_CLIENT_ID && MICROSOFT_CLIENT_SECRET && AUTH_REDIRECT_URI) { /** * Function generates consent page URL where the code is retrieved * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow */ publicApi<{state: string}, string>("microsoftSignIn", async ({state}) => { const url = new URL("/common/oauth2/v2.0/authorize", "https://login.microsoftonline.com"); url.searchParams.append("client_id", MICROSOFT_CLIENT_ID); url.searchParams.append("response_type", "code"); url.searchParams.append("state", state); url.searchParams.append("scope", "User.Read"); url.searchParams.append("response_mode", "query"); url.searchParams.append("redirect_uri", AUTH_REDIRECT_URI); return url.toString(); }); /** * 1) Function exchanges code for access token. * 2) Access token is used to retrieve user information. */ publicApi<{code: string}, UserInformation>("microsoftVerifySignIn", async ({code}) => { const postData = { client_id: MICROSOFT_CLIENT_ID, scope: "User.Read", client_secret: MICROSOFT_CLIENT_SECRET, grant_type: "authorization_code", redirect_uri: AUTH_REDIRECT_URI, code, }; const config = { headers: { "Content-Type": "application/x-www-form-urlencoded", }, }; const accessTokenRequest = await axios.post<any, AccessTokenResponse>(`https://login.microsoftonline.com/common/oauth2/v2.0/token`, qs.stringify(postData), config); const accessToken = accessTokenRequest.data.access_token; const user = await axios.get<any, MicrosoftUserInformationResponse>("https://graph.microsoft.com/v1.0/me", { headers: {Authorization: `Bearer ${accessToken}`, Accept: "application/json"}, }); // https://docs.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0 -> photo retrieval not supported for personal account | otherwise admin rigths needed return { id: user.data.id, name: user.data.displayName, accessToken, photoURL: undefined, }; }); } // TODO: Test in deployed scrumlr, because the following code can not be used/tested with localhost and is only preparatory if (APPLE_CLIENT_ID && APPLE_CLIENT_SECRET && AUTH_REDIRECT_URI) { /** * Function generates consent page URL where the code is retrieved * https://medium.com/identity-beyond-borders/sign-in-with-apple-a-zero-code-change-approach-54b44d59f60c */ publicApi<{state: string}, string>("appleSignIn", async ({state}) => { const url = new URL("/auth/authorize", "https://appleid.apple.com"); url.searchParams.append("response_type", "code"); url.searchParams.append("redirect_uri", AUTH_REDIRECT_URI); url.searchParams.append("state", state); url.searchParams.append("client_id", APPLE_CLIENT_ID); url.searchParams.append("scope", "name email"); url.searchParams.append("response_mode", "form_post"); // response_mode must be form_post when name or email scope is requested. return url.toString(); }); /** * 0) JWT Generation as client_secret * 1) Function exchanges code for access_token and id_token (holds user id) * https://developer.okta.com/blog/2019/06/04/what-the-heck-is-sign-in-with-apple * https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens * https://medium.com/techulus/how-to-setup-sign-in-with-apple-9e142ce498d4 * https://sarunw.com/posts/sign-in-with-apple-4/ * user information is only available on first contact: https://developer.apple.com/forums/thread/127677 */ publicApi<{code: string; appleUser: string}, UserInformation>("appleVerifySignIn", async ({code, appleUser}) => { const getClientSecret = async (): Promise<string> => { const privateKey = fs.readFileSync(APPLE_PRIVATE_KEY_FILE_PATH); // TODO: Download and include private key: https://help.apple.com/developer-account/#/devcdfbb56a3 // 0) JWT Generation as client_secret const headers: jwt.JwtHeader = { kid: APPLE_KEY_ID, alg: "ES256", }; const claims = { iss: APPLE_TEAM_ID, aud: "https://appleid.apple.com", sub: APPLE_CLIENT_ID, }; const options: jwt.SignOptions = { algorithm: "ES256", header: headers, expiresIn: "24h", }; return jwt.sign(claims, privateKey, options); }; const clientSecret: string = await getClientSecret(); // 1) Function exchanges code for access token. const postData = { client_id: APPLE_CLIENT_ID, client_secret: clientSecret, grant_type: "authorization_code", code, redirect_uri: AUTH_REDIRECT_URI, }; const config = { headers: { "Content-Type": "application/x-www-form-urlencoded", }, }; const accessTokenRequest = await axios.post<any, AccessTokenResponse>("https://appleid.apple.com/auth/token", qs.stringify(postData), config); const accessToken = accessTokenRequest.data.access_token; const idToken = accessTokenRequest.data.id_token; const user = JSON.parse(atob((idToken as string).split(".")[1])); // TODO: Find out if user name is only included in the same response that contains code as described here // https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_js/incorporating_sign_in_with_apple_into_other_platforms // https://developer.apple.com/forums/thread/127677 // maybe other information is sent and can be used as name (e.g. email) let name; if (appleUser) { name = `${JSON.parse(appleUser).name.firstName} ${JSON.parse(appleUser).name.lastName}`; } else { const userNameQuery = new Parse.Query(Parse.User); userNameQuery.equalTo("username", user.sub); } return { id: user.sub, name, accessToken, photoURL: undefined, }; }); } };
Accessible-Concepts/scrumlr.io
src/components/Board/__tests__/Board.test.tsx
import {act, fireEvent} from "@testing-library/react"; import {wrapWithTestBackend} from "react-dnd-test-utils"; import {Column} from "components/Column"; import {Color} from "constants/colors"; import configureStore from "redux-mock-store"; import {Provider} from "react-redux"; import Parse, {User} from "parse"; import {BoardComponent} from "components/Board"; import {render} from "testUtils"; import {mocked} from "ts-jest/utils"; const mockStore = configureStore(); const mockedUser = mocked(User, true); const createBoardWithColumns = (...colors: Color[]) => { const initialState = { board: { data: { columns: [ {id: "GG0fWzyCwd", name: "Positive", hidden: false, color: colors[0]}, {id: "RN1VQn6StI", name: "Negative", hidden: false, color: colors[1]}, {id: "YwPiaNxejW", name: "Actions", hidden: true, color: colors[2]}, ], moderation: {userId: "", status: "active"}, userConfigurations: [{id: "testId", showHiddenColumns: true}], }, }, notes: [], users: { admins: [], basic: [], all: [], }, votes: [], }; const store = mockStore(initialState); const [BoardContext] = wrapWithTestBackend(BoardComponent); return ( <Provider store={store}> <BoardContext currentUserIsModerator> {colors.map((color, index) => ( <Column key={color} id="GG0fWzyCwd" color={colors[index]} name="Positive" hidden={false} currentUserIsModerator={false} /> ))} </BoardContext> </Provider> ); }; describe("basic", () => { beforeEach(() => { mockedUser.current = jest.fn(() => ({id: "testId"} as never)); window.IntersectionObserver = jest.fn( () => ({ observe: jest.fn(), disconnect: jest.fn(), } as unknown as IntersectionObserver) ); }); test("show empty board", () => { const {container} = render(createBoardWithColumns()); expect(container.firstChild).toHaveClass("board--empty"); }); test("correct number of columns is set in inner styles", () => { const {container} = render(createBoardWithColumns("lean-lilac", "planning-pink", "backlog-blue", "poker-purple")); expect(container.querySelector("style")).toHaveTextContent(".board { --board__columns: 4 }"); }); describe("side-panels", () => { test("left side-panel is present", () => { const {container} = render(createBoardWithColumns("backlog-blue", "planning-pink")); expect(container.querySelector(".board")?.firstChild).toHaveClass("board__spacer-left"); }); test("right side-panel is present", () => { const {container} = render(createBoardWithColumns("backlog-blue", "planning-pink")); expect(container.querySelector(".board")?.lastChild).toHaveClass("board__spacer-right"); }); test("left side-panel has correct accent color", () => { const {container} = render(createBoardWithColumns("backlog-blue", "planning-pink")); expect(container.querySelector(".board")?.firstChild).toHaveClass("accent-color__backlog-blue"); }); test("right side-panel has correct accent color", () => { const {container} = render(createBoardWithColumns("backlog-blue", "planning-pink")); expect(container.querySelector(".board")?.lastChild).toHaveClass("accent-color__planning-pink"); }); describe("side-panels", () => { test("left side-panel is present", () => { const {container} = render(createBoardWithColumns("backlog-blue", "planning-pink")); expect(container.querySelector(".board")?.firstChild).toHaveClass("board__spacer-left"); }); test("right side-panel is present", () => { const {container} = render(createBoardWithColumns("backlog-blue", "planning-pink")); expect(container.querySelector(".board")?.lastChild).toHaveClass("board__spacer-right"); }); test("left side-panel has correct accent color", () => { const {container} = render(createBoardWithColumns("backlog-blue", "planning-pink")); expect(container.querySelector(".board")?.firstChild).toHaveClass("accent-color__backlog-blue"); }); test("right side-panel has correct accent color", () => { const {container} = render(createBoardWithColumns("backlog-blue", "planning-pink")); expect(container.querySelector(".board")?.lastChild).toHaveClass("accent-color__planning-pink"); }); test("side-panels have correct accent color with single column", () => { const {container} = render(createBoardWithColumns("lean-lilac")); const board = container.querySelector(".board"); expect(board?.childNodes[1]).toHaveClass("accent-color__lean-lilac"); expect(board?.lastChild).toHaveClass("accent-color__lean-lilac"); }); }); }); }); describe("navigation", () => { beforeEach(() => { Parse.User.current = jest.fn(() => ({id: "testId"})); window.IntersectionObserver = jest.fn( () => ({ observe: jest.fn(), disconnect: jest.fn(), } as unknown as IntersectionObserver) ); const root = global.document.createElement("div"); root.setAttribute("id", "root"); global.document.querySelector("body")!.appendChild(root); }); let intersectionObserver: IntersectionObserver; beforeEach(() => { intersectionObserver = { observe: jest.fn(), disconnect: jest.fn(), } as unknown as IntersectionObserver; window.IntersectionObserver = jest.fn(() => intersectionObserver); }); test("intersection observer is registered on mount", () => { render(createBoardWithColumns("lean-lilac", "backlog-blue")); expect(window.IntersectionObserver).toHaveBeenCalled(); expect(intersectionObserver.observe).toHaveBeenCalledTimes(2); }); test("intersection observer is disconnected on unmount", () => { render(createBoardWithColumns("planning-pink")).unmount(); expect(intersectionObserver.disconnect).toHaveBeenCalledTimes(1); }); test("intersection observer is re-initialized on change of children", () => { const {rerender} = render(createBoardWithColumns("planning-pink")); expect(window.IntersectionObserver).toHaveBeenCalledTimes(1); expect(intersectionObserver.disconnect).toHaveBeenCalledTimes(0); rerender(createBoardWithColumns("planning-pink", "backlog-blue")); expect(window.IntersectionObserver).toHaveBeenCalledTimes(2); expect(intersectionObserver.disconnect).toHaveBeenCalledTimes(1); }); describe("buttons visibility and functionality", () => { let container: HTMLElement; beforeEach(() => { container = render(createBoardWithColumns("planning-pink", "backlog-blue", "poker-purple")).container; }); const showColumns = (first: boolean, second: boolean, third: boolean) => { const columns = container.querySelectorAll(".column"); act(() => { const firstMethodCall = 0; const firstMethodParameter = 0; const intersectionObserverCallback = (window.IntersectionObserver as unknown as IntersectionObserver).mock.calls[firstMethodCall][firstMethodParameter]; intersectionObserverCallback([ {isIntersecting: first, target: columns[0]}, {isIntersecting: second, target: columns[1]}, {isIntersecting: third, target: columns[2]}, ]); }); return columns; }; test("navigation is hidden when all columns are visible", () => { showColumns(true, true, true); expect(container.querySelector(".board__navigation")).not.toBeInTheDocument(); }); test("navigation is shown when some columns are outside of the viewport", () => { showColumns(false, true, false); expect(container.querySelector(".board__navigation")).toBeInTheDocument(); }); test("column-visibility attribute is set correctly on fully visible columns", () => { const rootContainer = render(createBoardWithColumns("planning-pink", "backlog-blue", "poker-purple"), {container: global.document.querySelector("#root")!}); showColumns(true, true, true); expect(rootContainer.container.getAttribute("column-visibility")).toBe("visible"); }); test("column-visibility attribute is set correctly on partly visible columns", () => { const rootContainer = render(createBoardWithColumns("planning-pink", "backlog-blue", "poker-purple"), {container: global.document.querySelector("#root")!}); showColumns(true, true, false); expect(rootContainer.container.getAttribute("column-visibility")).toBe("collapsed"); }); test("correct scroll of previous button", () => { const columns = showColumns(false, true, false); const scrollIntoView = jest.fn(); columns[0].scrollIntoView = scrollIntoView; fireEvent.click(container.querySelector(".board__navigation-prev") as HTMLElement); expect(scrollIntoView).toHaveBeenCalled(); }); test("correct scroll of next button", () => { const columns = showColumns(false, true, false); const scrollIntoView = jest.fn(); columns[2].scrollIntoView = scrollIntoView; fireEvent.click(container.querySelector(".board__navigation-next") as HTMLElement); expect(scrollIntoView).toHaveBeenCalled(); }); test("previous button has color of previous column", () => { showColumns(false, true, false); expect(container.querySelector(".board__navigation-prev")).toHaveClass("accent-color__planning-pink"); }); test("next button has color of next column", () => { showColumns(false, true, false); expect(container.querySelector(".board__navigation-next")).toHaveClass("accent-color__poker-purple"); }); }); });
Accessible-Concepts/scrumlr.io
src/components/AccessPolicySelection/index.ts
export * from "./AccessPolicySelection";
Accessible-Concepts/scrumlr.io
src/components/BoardHeader/HeaderMenu/BoardOptions/ShareQrCodeOption.tsx
<filename>src/components/BoardHeader/HeaderMenu/BoardOptions/ShareQrCodeOption.tsx<gh_stars>0 import {ReactComponent as ShareIcon} from "assets/icon-share.svg"; import "../BoardSettings/BoardSettings.scss"; import classNames from "classnames"; import QRCode from "qrcode.react"; import {useTranslation} from "react-i18next"; import {TabIndex} from "constants/tabIndex"; import {BoardOption} from "./BoardOption"; import {BoardOptionButton} from "./BoardOptionButton"; import "./ShareQrCodeOption.scss"; export type QRCodeProps = { onClick: () => void; expand: boolean; }; export const ShareQrCodeOption = (props: QRCodeProps) => { const {t} = useTranslation(); return ( <BoardOption data-testid="qrcode"> <BoardOptionButton label={t("ShareQrCodeOption.button")} icon={ShareIcon} isExpandable onClick={props.onClick} /> <div className={classNames("share-qr-code-option__container", {"share-qr-code-option__container--visible": props.expand})}> <QRCode value={document.location.href} size={260} className="share-qr-code-option__qrcode" /> <button className="share-qr-code-option__copy-to-clipboard" onClick={() => navigator.clipboard.writeText(document.location.href)} tabIndex={props.expand ? TabIndex.default : TabIndex.disabled} > {t("ShareQrCodeOption.copyInviteURL")} </button> </div> </BoardOption> ); };
Accessible-Concepts/scrumlr.io
src/components/BoardHeader/ParticipantsList/Participant.tsx
<filename>src/components/BoardHeader/ParticipantsList/Participant.tsx import {UserClientModel} from "types/user"; import {UserAvatar} from "components/BoardUsers"; import {ToggleButton} from "components/ToggleButton"; import Parse from "parse"; import store, {useAppSelector} from "store"; import {ActionFactory} from "store/action"; import "./Participant.scss"; import {TabIndex} from "constants/tabIndex"; interface ParticipantProps { participant: UserClientModel; currentUserIsModerator: boolean; boardOwner: string; } export const Participant = ({participant, currentUserIsModerator, boardOwner}: ParticipantProps) => { const state = useAppSelector((applicationState) => ({ users: applicationState.users, })); let badgeText = ""; if (Parse.User.current()?.id === participant!.id) { badgeText = "me"; } else if (participant!.id === boardOwner) { badgeText = "owner"; } else if (state.users.admins.find((user) => user.id === participant!.id) !== undefined) { badgeText = "admin"; } else { badgeText = "user"; } return ( <li tabIndex={TabIndex.default} className="participant"> <figure className="participant__avatar-and-name" aria-roledescription="participant"> <UserAvatar ready={participant.ready} id={participant.id} name={participant.displayName} className="participant__user-avatar-wrapper" avatarClassName="participant__user-avatar" badgeText={badgeText} /> <figcaption className="participant__name">{participant.displayName}</figcaption> </figure> {currentUserIsModerator && ( <ToggleButton className="participant__permission-toggle" disabled={Parse.User.current()?.id === participant!.id || participant!.id === boardOwner} values={["participant", "moderator"]} value={participant!.admin ? "moderator" : "participant"} onToggle={(val: "participant" | "moderator") => { store.dispatch(ActionFactory.changePermission(participant!.id, val === "moderator")); }} tabIndex={TabIndex.default} /> )} </li> ); };
Accessible-Concepts/scrumlr.io
src/components/CookieNotice/index.ts
<reponame>Accessible-Concepts/scrumlr.io<gh_stars>10-100 export * from "./CookieNotice"; export * from "./CookiePolicy";
Accessible-Concepts/scrumlr.io
src/store/middleware/__tests__/board.test.ts
<gh_stars>10-100 import {passBoardMiddleware} from "store/middleware/board"; import {ActionFactory} from "store/action"; import {API} from "api"; import {MiddlewareAPI} from "redux"; jest.mock("api", () => ({ API: { editBoard: jest.fn(), }, })); beforeEach(() => { (API.editBoard as jest.Mock).mockClear(); }); const stateAPI = { getState: () => ({ board: { data: { id: "boardId", }, }, }), }; describe("board middleware", () => { test("Set moderation", () => { passBoardMiddleware(stateAPI as MiddlewareAPI, jest.fn(), ActionFactory.editBoard({id: "test_board", name: "Name", moderation: {userId: "test_user", status: "active"}})); expect(API.editBoard).toHaveBeenCalledWith({id: "test_board", name: "Name", moderation: {userId: "test_user", status: "active"}}); }); });
Accessible-Concepts/scrumlr.io
src/types/__tests__/board.test.ts
<reponame>Accessible-Concepts/scrumlr.io<gh_stars>0 import {mocked} from "ts-jest/utils"; import {getBrowserServerTimeDifference} from "utils/timer"; import {mapBoardServerToClientModel, BoardServerModel, BoardClientModel} from "../board"; jest.mock("utils/timer"); const mockedTimer = mocked(getBrowserServerTimeDifference); const getServerModel = async (timerUTCEndTimeNotNull: boolean): Promise<BoardServerModel> => { mockedTimer.mockImplementation( () => new Promise((resolve) => { resolve(0); }) ); return { objectId: "test_objectId", name: "test_name", columns: { test_id: { name: "test_name", color: "backlog-blue", hidden: false, }, }, userConfigurations: { test_id: { showHiddenColumns: true, }, }, accessCode: "test_accessCode", accessPolicy: { type: "Public", salt: "test_salt", passphrase: "<PASSWORD>", }, encryptedContent: false, showAuthors: false, timerUTCEndTime: timerUTCEndTimeNotNull ? { iso: new Date(0).toString(), } : undefined, voting: "active", moderation: { userId: "test_userId", status: "active", }, votingIteration: 0, showNotesOfOtherUsers: false, createdAt: new Date(1234).toUTCString(), updatedAt: new Date(1234).toUTCString(), owner: { objectId: "test_objectId", }, usersMarkedReady: ["test"], usersRaisedHands: ["test"], }; }; describe("Board types", () => { test("mapping of attributes except timer", async () => { const serverModel: BoardServerModel = await getServerModel(true); const clientModel: BoardClientModel = await mapBoardServerToClientModel(serverModel); expect(clientModel.id).toEqual(serverModel.objectId); expect(clientModel.name).toEqual(serverModel.name); expect(clientModel.columns).toEqual([{columnId: "test_id", name: "test_name", color: "backlog-blue", hidden: false}]); expect(clientModel.userConfigurations).toEqual([{id: "test_id", showHiddenColumns: true}]); expect(clientModel.accessCode).toEqual(serverModel.accessCode); expect(clientModel.accessPolicy).toEqual(serverModel.accessPolicy.type); expect(clientModel.encryptedContent).toEqual(serverModel.encryptedContent); expect(clientModel.voting).toEqual(serverModel.voting); expect(clientModel.votingIteration).toEqual(serverModel.votingIteration); expect(clientModel.showNotesOfOtherUsers).toEqual(serverModel.showNotesOfOtherUsers); expect(clientModel.createdAt).toEqual(new Date(serverModel.createdAt)); expect(clientModel.updatedAt).toEqual(new Date(serverModel.updatedAt)); expect(clientModel.dirty).toEqual(false); expect(clientModel.owner).toEqual(serverModel.owner.objectId); expect(clientModel.moderation).toEqual(serverModel.moderation); expect(clientModel.usersMarkedReady).toEqual(serverModel.usersMarkedReady); expect(clientModel.usersRaisedHands).toEqual(serverModel.usersRaisedHands); }); test("timerUTCEndTime is available", async () => { const serverModel: BoardServerModel = await getServerModel(true); const clientModel: BoardClientModel = await mapBoardServerToClientModel(serverModel); expect(clientModel.timerUTCEndTime).toEqual(new Date(0)); }); test("timerUTCEndTime isn't available", async () => { const serverModel: BoardServerModel = await getServerModel(false); const clientModel: BoardClientModel = await mapBoardServerToClientModel(serverModel); expect(clientModel.timerUTCEndTime).toEqual(undefined); }); });
Accessible-Concepts/scrumlr.io
src/store/action/__tests__/note.test.ts
<gh_stars>0 import {AssertTypeEqual} from "testUtils"; import {NoteClientModel} from "types/note"; import {ReduxAction} from "../index"; import {NoteActionFactory, NoteActionType, NoteReduxAction} from "../note"; describe("note actions", () => { test("equal number of action types and factory functions", () => { expect(Object.keys(NoteActionType).length).toEqual(Object.keys(NoteActionFactory).length); }); describe("add note", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.addNote>, NoteReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.addNote>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = NoteActionFactory.addNote("columnId", "Text"); expect(action).toEqual({ type: "@@SCRUMLR/addNote", columnId: "columnId", text: "Text", }); }); }); describe("edit note", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.editNote>, NoteReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.editNote>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = NoteActionFactory.editNote({id: "noteId", text: "New text"}); expect(action).toEqual({ type: "@@SCRUMLR/editNote", note: {id: "noteId", text: "New text"}, }); }); }); describe("unstack note", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.unstackNote>, NoteReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.unstackNote>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = NoteActionFactory.unstackNote({id: "noteId", parentId: "parentId"}); expect(action).toEqual({ type: "@@SCRUMLR/unstackNote", note: {id: "noteId", parentId: "parentId"}, }); }); }); describe("drag note", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.dragNote>, NoteReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.dragNote>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = NoteActionFactory.dragNote({id: "noteId", dragOnId: "parentId"}); expect(action).toEqual({ type: "@@SCRUMLR/dragNote", note: {id: "noteId", dragOnId: "parentId"}, }); }); }); describe("created note", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.createdNote>, NoteReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.createdNote>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = NoteActionFactory.createdNote({test: true} as unknown as NoteClientModel); expect(action).toEqual({ type: "@@SCRUMLR/createdNote", note: {test: true}, }); }); }); describe("updated note", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.updatedNote>, NoteReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.updatedNote>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = NoteActionFactory.updatedNote({test: true} as unknown as NoteClientModel); expect(action).toEqual({ type: "@@SCRUMLR/updatedNote", note: {test: true}, }); }); }); describe("delete note", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.deleteNote>, NoteReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.deleteNote>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = NoteActionFactory.deleteNote("noteId"); expect(action).toEqual({ type: "@@SCRUMLR/deleteNote", noteId: "noteId", }); }); }); describe("initialize notes", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.initializeNotes>, NoteReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof NoteActionFactory.initializeNotes>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = NoteActionFactory.initializeNotes([{test: true}] as unknown as NoteClientModel[]); expect(action).toEqual({ type: "@@SCRUMLR/initNotes", notes: [{test: true}], }); }); }); });
Accessible-Concepts/scrumlr.io
src/types/vote.ts
export interface VoteServerModel extends Parse.Object { board: Parse.Object; note: Parse.Object; user: Parse.Object; votingIteration: number; } export interface VoteClientModel { /** The id of the note or `undefined` if yet to be persisted. */ id?: string; board: string; note: string; user: string; votingIteration: number; } export const mapVoteServerToClientModel = (vote: VoteServerModel): VoteClientModel => ({ id: vote.id, board: vote.get("board").id, note: vote.get("note").id, user: vote.get("user").id, votingIteration: vote.get("votingIteration"), });
Accessible-Concepts/scrumlr.io
src/components/ScrumlrLogo/index.ts
export * from "./ScrumlrLogo";
Accessible-Concepts/scrumlr.io
src/components/BoardHeader/HeaderMenu/HeaderMenu.tsx
<filename>src/components/BoardHeader/HeaderMenu/HeaderMenu.tsx<gh_stars>0 import {Portal} from "components/Portal"; import Parse from "parse"; import {useState} from "react"; import {useSelector} from "react-redux"; import {ApplicationState} from "types/store"; import "./HeaderMenu.scss"; import {BoardOption} from "./BoardOptions"; import {BoardSettings} from "./BoardSettings"; type HeaderMenuProps = { open: boolean; onClose: () => void; currentUserIsModerator: boolean; }; type ExpandableOptions = "share" | "delete" | "export"; const HeaderMenu = (props: HeaderMenuProps) => { const state = useSelector((applicationState: ApplicationState) => ({ board: applicationState.board.data, user: applicationState.users.all.find((user) => user.id === Parse.User.current()!.id), userConfiguration: applicationState.board.data?.userConfigurations.find((configuration) => configuration.id === Parse.User.current()!.id), })); const [activeEditMode, setActiveEditMode] = useState(false); const [accessPolicy, setAccessPolicy] = useState(state.board!.accessPolicy); const [expandedOption, setExpandedOption] = useState<ExpandableOptions | undefined>(); if (!props.open) { return null; } const onExpand = (option: ExpandableOptions) => () => { if (option === expandedOption) { setExpandedOption(undefined); } else { setExpandedOption(option); } }; return ( <Portal onClose={() => { setActiveEditMode(false); setExpandedOption(undefined); setAccessPolicy(state.board!.accessPolicy); props.onClose(); }} darkBackground={false} > <ul className="header-menu"> <BoardSettings activeEditMode={activeEditMode} accessPolicy={accessPolicy} currentUserIsModerator={props.currentUserIsModerator} setActiveEditMode={setActiveEditMode} setAccessPolicy={setAccessPolicy} /> {props.currentUserIsModerator && ( <> <BoardOption.ShowAuthorOption /> <BoardOption.ShowOtherUsersNotesOption /> <BoardOption.ShowHiddenColumnsOption /> <BoardOption.DeleteBoardOption expand={expandedOption === "delete"} onClick={onExpand("delete")} /> </> )} <BoardOption.ShareQrCodeOption expand={expandedOption === "share"} onClick={onExpand("share")} /> <BoardOption.ExportBoardOption expand={expandedOption === "export"} onClose={props.onClose} onClick={onExpand("export")} /> </ul> </Portal> ); }; export {HeaderMenu};
Accessible-Concepts/scrumlr.io
src/routes/Legal/index.ts
<filename>src/routes/Legal/index.ts export * from "./Legal";
Accessible-Concepts/scrumlr.io
src/components/NoteDialog/NoteDialogComponents/NoteDialogNote.tsx
import classNames from "classnames"; import Parse from "parse"; import {FC} from "react"; import {VoteClientModel} from "types/vote"; import {NoteDialogNoteComponents} from "./NoteDialogNoteComponents"; import "./NoteDialogNote.scss"; export type NoteDialogNoteProps = { noteId?: string; parentId?: string; text: string; authorId: string; authorName: string; showAuthors: boolean; onClose: () => void; onDeleteOfParent: () => void; votes: VoteClientModel[]; allVotesOfUser: VoteClientModel[]; activeVoting: boolean; activeModeration: {userId?: string; status: boolean}; currentUserIsModerator: boolean; showUnstackButton: boolean; }; export const NoteDialogNote: FC<NoteDialogNoteProps> = (props: NoteDialogNoteProps) => ( <div className={classNames("note-dialog__note", {"note-dialog__note--own-card": Parse.User.current()?.id === props.authorId})}> <NoteDialogNoteComponents.Content {...props} /> <NoteDialogNoteComponents.Footer {...props} /> </div> );
Accessible-Concepts/scrumlr.io
src/api/vote.ts
import {callAPI} from "api/callApi"; export const VoteAPI = { /** * Add a vote to a note. * * @param boardId the identifier of the board * @param noteId the note id * @returns a {status, description} object */ addVote: (boardId: string, noteId: string) => callAPI("addVote", {boardId, noteId}), /** * Removes/Deletes a vote from a note. * * @param boardId the identifier of the board * @param noteId the note id * @returns a {status, description} object */ deleteVote: (boardId: string, noteId: string) => callAPI("removeVote", {boardId, noteId}), };
Accessible-Concepts/scrumlr.io
src/store/middleware/joinRequest.ts
<filename>src/store/middleware/joinRequest.ts import {AnyAction, Dispatch, MiddlewareAPI} from "redux"; import {ApplicationState} from "types/store"; import {API} from "api"; import {ActionType, ReduxAction} from "store/action"; export const passJoinRequestMiddleware = (stateAPI: MiddlewareAPI<Dispatch<AnyAction>, ApplicationState>, dispatch: Dispatch, action: ReduxAction) => { switch (action.type) { case ActionType.AcceptJoinRequests: API.acceptJoinRequests(action.boardId, action.userIds); break; case ActionType.RejectJoinRequests: API.rejectJoinRequests(action.boardId, action.userIds); break; default: break; } };
Accessible-Concepts/scrumlr.io
src/components/BoardHeader/HeaderMenu/BoardOptions/BoardOption.tsx
import {FC} from "react"; import "./BoardOption.scss"; import classNames from "classnames"; export interface BoardOptionProps { className?: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; } export const BoardOption: FC<BoardOptionProps> = ({className, children, ...other}) => ( <li className={classNames("board-option", className)} {...other}> {children} </li> );
Accessible-Concepts/scrumlr.io
src/api/auth.ts
import {v4 as uuidv4} from "uuid"; import {callAPI} from "api/callApi"; const generateState = (prefix: string, originURL: string) => { // generate random state id and store origin into the session storage const state = `${prefix}-${uuidv4()}`; sessionStorage.setItem(state, originURL); return state; }; /* TODO: use or delete after deployment * this is how user looks like in first apple response export interface IAppleUser { name: { firstName: string; lastName: string; }; email: string; } */ export const AuthAPI = { /** * Sign in with authentication provider: google, github, microsoft or apple. * * @returns the redirection URL */ signIn: (authProvider: string, originURL: string) => callAPI<{state: string}, string>(`${authProvider}SignIn`, {state: generateState(authProvider, originURL)}), /** * Verify the sign in with the OAuth provider by the specified code. * * @param code the verification code returned by the authentication provider * @param state the state passed by the authentication provider (see https://auth0.com/docs/protocols/state-parameters) * @param authProvider name of the chosen OAuth provider. Used for adressing the correct endpoint * @returns user information and redirect URL */ // @param appleUser only given when signing in with apple for the first time // after deployment for apple user name handling: verifySignIn: async (code: string, state: string, authProvider: string, appleUser: string) => { verifySignIn: async (code: string, state: string, authProvider: string) => { // check if state is available in storage and execute call on match const redirectURL = sessionStorage.getItem(state); if (redirectURL) { // after deployment for apple user name handling: const user = // await callAPI<{code: string; appleUser: string}, {id: string; name: string; accessToken: string; idToken: string}>(`${authProvider}VerifySignIn`, {code,appleUser}); const user = await callAPI<{code: string}, {id: string; name: string; accessToken: string; idToken: string}>(`${authProvider}VerifySignIn`, { code, }); return { user, redirectURL, }; } throw new Error("state does not match"); }, };
Accessible-Concepts/scrumlr.io
src/routes/Homepage/InovexAnchor/index.ts
export * from "./InovexAnchor";
Accessible-Concepts/scrumlr.io
src/components/BoardHeader/HeaderMenu/BoardOptions/BoardOptionButton.tsx
import {FC, ReactNode, ElementType} from "react"; import "./BoardOptionButton.scss"; import classNames from "classnames"; export interface BoardOptionButtonProps { label: string; icon?: ElementType; // eslint-disable-next-line @typescript-eslint/no-explicit-any onClick: (...args: any) => any; className?: string; isExpandable?: boolean; children?: ReactNode; // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; } export const BoardOptionButton: FC<BoardOptionButtonProps> = ({label, icon, onClick, isExpandable = false, className, children, ...other}) => { const Icon = icon!; return ( <button className={classNames("board-option-button", {"board-option-button--expandable": isExpandable})} onClick={onClick} {...other}> {icon && <Icon className="board-option-button__icon" />} {children} <span className="board-option-button__label">{label}</span> </button> ); };
Accessible-Concepts/scrumlr.io
src/routes/AuthRedirect/__tests__/AuthRedirect.test.tsx
<filename>src/routes/AuthRedirect/__tests__/AuthRedirect.test.tsx import {API} from "api"; import {Attributes, User} from "parse"; import {waitFor} from "@testing-library/react"; import {MemoryRouter} from "react-router"; import {AuthRedirect} from "routes/AuthRedirect"; import {render, renderWithoutRouter} from "testUtils"; import {mocked} from "ts-jest/utils"; jest.mock("api"); jest.mock("parse"); const mockedVerifySignIn = mocked(API.verifySignIn); const mockedUser = mocked(User, true); describe("routing tests", () => { test("missing params on page visit -> ErrorPage", () => { const {container} = render(<AuthRedirect />); expect(container.firstChild).toHaveClass("error-page"); }); test("error in params -> ErrorPage", () => { const {container} = renderWithoutRouter( <MemoryRouter initialEntries={["?error=params_error"]}> <AuthRedirect /> </MemoryRouter> ); expect(container.firstChild).toHaveClass("error-page"); }); test("correct params are set -> LoadingScreen", () => { const {container} = renderWithoutRouter( <MemoryRouter initialEntries={["?code=test_code&state=test_state"]}> <AuthRedirect /> </MemoryRouter> ); expect(container.firstChild).toHaveClass("loading-screen"); }); describe("successful sign-in", () => { beforeEach(() => { global.window = Object.create(window); const url = "http://test-root.com"; Object.defineProperty(window, "location", { value: { href: url, }, writable: true, }); }); test("redirect user on successful sign in", async () => { const targetURLAfterSuccessfulSignIn = "http://destiny.com"; mockedVerifySignIn.mockResolvedValue( new Promise((resolve) => { resolve({ user: { id: "123", accessToken: "access_token", idToken: "token", name: "<NAME>", }, redirectURL: targetURLAfterSuccessfulSignIn, }); }) ); const user = { linkWith: jest.fn().mockReturnValue(Promise.resolve(true)), set: jest.fn(), save: jest.fn().mockReturnValue(Promise.resolve(true)), }; mockedUser.mockImplementation(() => user as unknown as User<Attributes>); renderWithoutRouter( <MemoryRouter initialEntries={["?code=test_code&state=google-test"]}> <AuthRedirect /> </MemoryRouter> ); await waitFor(() => expect(window.location.href).toEqual(targetURLAfterSuccessfulSignIn)); }); }); });
Accessible-Concepts/scrumlr.io
src/components/BoardHeader/HeaderMenu/BoardOptions/ExportBoardOption.tsx
import {useAppSelector} from "store"; import {exportAsCSV, exportAsJSON} from "utils/export"; import {ApplicationState} from "types/store"; import {ReactComponent as ExportIcon} from "assets/icon-export.svg"; import {ReactComponent as ExportCSV} from "assets/icon-export-csv.svg"; import {ReactComponent as ExportJSON} from "assets/icon-export-json.svg"; // import {ReactComponent as ExportPDF} from "assets/icon-export.svg"; import "../BoardSettings/BoardSettings.scss"; import classNames from "classnames"; import {TabIndex} from "constants/tabIndex"; import {useTranslation} from "react-i18next"; import {BoardOption} from "./BoardOption"; import {BoardOptionButton} from "./BoardOptionButton"; import "./ExportBoardOption.scss"; export type ExportProps = { onClick: () => void; onClose: () => void; expand: boolean; }; export const ExportBoardOption = (props: ExportProps) => { const {t} = useTranslation(); const state = useAppSelector((applicationState: ApplicationState) => ({ board: applicationState.board.data!, notes: applicationState.notes, users: applicationState.users, votes: applicationState.votes, })); return ( <BoardOption data-testid="export"> <BoardOptionButton label={t("ExportBoardOption.button")} icon={ExportIcon} isExpandable onClick={props.onClick} /> <div className={classNames("export-board-option__container", {"export-board-option__container--visible": props.expand})}> <BoardOptionButton label={t("ExportBoardOption.exportAsJson")} icon={ExportJSON} onClick={() => { exportAsJSON(state); props.onClose(); }} data-testid="export-json" tabIndex={props.expand ? TabIndex.default : TabIndex.disabled} /> <BoardOptionButton label={t("ExportBoardOption.exportAsCSV")} icon={ExportCSV} onClick={() => { exportAsCSV(state); props.onClose(); }} data-testid="export-csv" tabIndex={props.expand ? TabIndex.default : TabIndex.disabled} /> </div> </BoardOption> ); };
Accessible-Concepts/scrumlr.io
src/utils/__tests__/export.test.ts
import {waitFor} from "@testing-library/react"; import {exportAsCSV, exportAsJSON, ExportProps, fileName, generateCSV, mapToExport} from "utils/export"; jest.mock("file-saver", () => ({saveAs: jest.fn()})); type TestProps = { userAvaiable?: boolean; parentAvailable?: boolean; noteIdAvailable?: boolean; timestampAvailable?: boolean; }; const createState = ( {userAvaiable = true, parentAvailable = true, noteIdAvailable = true, timestampAvailable = true}: TestProps = { userAvaiable: true, parentAvailable: true, noteIdAvailable: true, timestampAvailable: true, } ) => ({ board: { name: "board", columns: [{columnId: "test-column", name: "Positive", hidden: false, color: "retro-red"}], votingIteration: 1, }, notes: [ { id: noteIdAvailable ? "test-note" : undefined, columnId: "test-column", text: "test-text", author: "test-user-id", parentId: parentAvailable ? "note-parent" : undefined, dirty: true, focus: false, createdAt: timestampAvailable ? new Date(12345) : undefined, }, ], votes: [ { id: "test-vote-0", board: "test-board", note: "test-note", user: "test-user-1", votingIteration: 1, }, ], users: { admins: [], basic: [], all: userAvaiable ? [ { displayName: "Test user", id: "test-user-id", createdAt: new Date(123456), updatedAt: new Date(123456), admin: false, online: true, ready: true, }, ] : [], usersMarkedReady: [], }, } as ExportProps); const exportFormat = ( {userAvaiable = true, parentAvailable = true, noteIdAvailable = true, timestampAvailable = true}: TestProps = { userAvaiable: true, parentAvailable: true, noteIdAvailable: true, timestampAvailable: true, } ) => [ { noteId: noteIdAvailable ? "test-note" : "-", author: userAvaiable ? "Test user" : "test-user-id", text: "test-text", column: "Positive", timestamp: timestampAvailable ? new Date(12345).toUTCString().replace(",", "") : "-", parent: parentAvailable ? "note-parent" : "-", votes: noteIdAvailable ? 1 : 0, voting_iteration_1: noteIdAvailable ? 1 : 0, }, ]; describe("Export", () => { test("json function called", async () => { const state = createState(); const json = JSON.stringify(mapToExport(state), null, 2); const blob = new Blob([json], {type: "application/json"}); const blobSpy = jest.spyOn(global, "Blob").mockImplementationOnce(() => blob); exportAsJSON(state); await waitFor(() => { expect(blobSpy).toHaveBeenCalledWith([json], {type: "application/json"}); }); }); test("csv function called", async () => { const state = createState(); const csv = generateCSV(state); const blob = new Blob([csv], {type: "text/csv"}); const blobSpy = jest.spyOn(global, "Blob").mockImplementationOnce(() => blob); exportAsCSV(state); await waitFor(() => { expect(blobSpy).toHaveBeenCalledWith([csv], {type: "text/csv"}); }); }); test("correct file name", () => { const state = createState(); const mockDate = new Date(12345678); const dateSpy = jest.spyOn(global, "Date").mockImplementationOnce(() => mockDate as unknown as string); const name = fileName(state); expect(name).toEqual("1970-01-01_board"); dateSpy.mockRestore(); }); test("correct export mapping with available user", () => { const state = createState(); const mappedExport = mapToExport(state); expect(mappedExport).toEqual(exportFormat()); }); test("correct export mapping without available user", () => { const props = {userAvaiable: false}; const state = createState(props); const mappedExport = mapToExport(state); expect(mappedExport).toEqual(exportFormat(props)); }); test("correct export mapping without noteId", () => { const props = {noteIdAvailable: false}; const state = createState(props); const mappedExport = mapToExport(state); expect(mappedExport).toEqual(exportFormat(props)); }); test("correct export mapping without parent", () => { const props = {parentAvailable: false}; const state = createState(props); const mappedExport = mapToExport(state); expect(mappedExport).toEqual(exportFormat(props)); }); test("correct export mapping without timestamp", () => { const props = {timestampAvailable: false}; const state = createState(props); const mappedExport = mapToExport(state); expect(mappedExport).toEqual(exportFormat(props)); }); });
Accessible-Concepts/scrumlr.io
src/components/LoadingScreen/LoadingScreen.tsx
<gh_stars>10-100 import "./LoadingScreen.scss"; import {LoadingIndicator} from "components/LoadingIndicator"; export const LoadingScreen = () => ( <div className="loading-screen"> <LoadingIndicator /> </div> );
Accessible-Concepts/scrumlr.io
src/components/TextInputLabel/TextInputLabel.tsx
<reponame>Accessible-Concepts/scrumlr.io import {FC, ReactElement, ReactNode} from "react"; import classNames from "classnames"; import {TextInput} from "../TextInput"; import "./TextInputLabel.scss"; export interface TextInputLabelProps { className?: string; htmlFor?: string; label: ReactNode; children?: ReactElement<typeof TextInput>; } export const TextInputLabel: FC<TextInputLabelProps> = ({className, label, htmlFor, children}) => ( <label className={classNames("text-input-label", className)} htmlFor={htmlFor}> <span className="text-input-label__label">{label}</span> {children} </label> );
Accessible-Concepts/scrumlr.io
src/components/Votes/VoteDisplay/VoteDisplay.tsx
<filename>src/components/Votes/VoteDisplay/VoteDisplay.tsx<gh_stars>10-100 import "./VoteDisplay.scss"; import {useTranslation} from "react-i18next"; import {FC} from "react"; type VoteDisplayProps = { usedVotes: number; possibleVotes: number; }; export const VoteDisplay: FC<VoteDisplayProps> = ({usedVotes, possibleVotes}) => { const {t} = useTranslation(); return ( <div className="vote-display"> <span title={t("VoteDisplay.tooltip", {remaining: possibleVotes - usedVotes, total: possibleVotes})}> {usedVotes} / {possibleVotes} </span> </div> ); };
Accessible-Concepts/scrumlr.io
src/routes/Router.tsx
<reponame>Accessible-Concepts/scrumlr.io import {BrowserRouter, Routes} from "react-router-dom"; import {LoginBoard} from "routes/LoginBoard"; import {NewBoard} from "routes/NewBoard"; import {BoardGuard} from "routes/Board"; import {RequireAuthentication} from "routes/RequireAuthentication"; import {AuthRedirect} from "routes/AuthRedirect"; import {Route} from "react-router"; import {Homepage} from "./Homepage"; import {Legal} from "./Legal"; import ScrollToTop from "./ScrollToTop"; const Router = () => ( <BrowserRouter> <ScrollToTop /> <Routes> <Route path="/" element={<Homepage />} /> <Route path="/legal/termsAndConditions" element={<Legal document="termsAndConditions" />} /> <Route path="/legal/privacyPolicy" element={<Legal document="privacyPolicy" />} /> <Route path="/legal/cookiePolicy" element={<Legal document="cookiePolicy" />} /> <Route path="/new" element={ <RequireAuthentication> <NewBoard /> </RequireAuthentication> } /> <Route path="/login" element={<LoginBoard />} /> <Route path="/auth/redirect" element={<AuthRedirect />} /> <Route path="/board/:boardId" element={ <RequireAuthentication> <BoardGuard /> </RequireAuthentication> } /> </Routes> </BrowserRouter> ); export default Router;
Accessible-Concepts/scrumlr.io
src/routes/Board/Board.tsx
import {LoadingScreen} from "components/LoadingScreen"; import {BoardComponent} from "components/Board"; import {Column} from "components/Column"; import {Request} from "components/Request"; import store, {useAppSelector} from "store"; import {InfoBar} from "components/Infobar"; import {TabIndex} from "constants/tabIndex"; import Parse from "parse"; import {useEffect} from "react"; import {toast} from "react-toastify"; import {ActionFactory} from "store/action"; import _ from "underscore"; export const Board = () => { useEffect( () => () => { toast.clearWaitingQueue(); toast.dismiss(); }, [] ); useEffect(() => { window.addEventListener( "beforeunload", () => { store.dispatch(ActionFactory.leaveBoard()); }, false ); window.addEventListener( "onunload", () => { store.dispatch(ActionFactory.leaveBoard()); }, false ); }, []); const state = useAppSelector( (applicationState) => ({ board: { id: applicationState.board.data?.id, columns: applicationState.board.data?.columns, status: applicationState.board.status, }, joinRequests: applicationState.joinRequests, users: applicationState.users, userConfiguration: applicationState.board.data?.userConfigurations.find((configuration) => configuration.id === Parse.User.current()!.id), }), _.isEqual ); const currentUserIsModerator = state.users.admins.find((user) => user.id === Parse.User.current()!.id) !== undefined; if (state.board.status === "pending") { return <LoadingScreen />; } if (state.board.status === "ready") { return ( <> {currentUserIsModerator && ( <Request joinRequests={state.joinRequests.filter((joinRequest) => joinRequest.status === "pending")} users={state.users.all} raisedHands={state.users.usersRaisedHands.filter((id) => id !== Parse.User.current()?.id)} boardId={state.board.id!} /> )} <InfoBar /> <BoardComponent currentUserIsModerator={currentUserIsModerator}> {state.board .columns!.filter((column) => !column.hidden || (currentUserIsModerator && state.userConfiguration?.showHiddenColumns)) .map((column, columnIndex) => ( <Column tabIndex={TabIndex.Column + columnIndex} key={column.columnId} id={column.columnId!} name={column.name} hidden={column.hidden} currentUserIsModerator={currentUserIsModerator} color={column.color} /> ))} </BoardComponent> </> ); } return <LoadingScreen />; };
Accessible-Concepts/scrumlr.io
server/src/model/init.ts
import Parse from "parse/node"; const addInitialBoardSchema = async () => { const schema = new Parse.Schema("Board"); schema.addString("name"); schema.addPointer("owner", "_User", {required: true}); schema.addPointer("template", "Template"); schema.addObject("columns", {defaultValue: {}}); schema.addBoolean("encryptedContent", {defaultValue: false}); schema.addObject("accessPolicy", {defaultValue: {type: "Public"}}); schema.addBoolean("showAuthors", {defaultValue: true}); schema.addDate("timerUTCEndTime"); schema.addString("voting", {defaultValue: "disabled"}); schema.addObject("moderation", {defaultValue: {}}); schema.addNumber("votingIteration", {required: true, defaultValue: 0}); schema.addBoolean("showNotesOfOtherUsers", {defaultValue: true}); schema.addObject("userConfigurations", {defaultValue: {}}); schema.addArray("usersMarkedReady", {required: false, defaultValue: []}); schema.addArray("usersRaisedHands", {required: false, defaultValue: []}); schema.addNumber("schemaVersion", {required: true, defaultValue: 1}); return schema.save(); }; const addInitialNoteSchema = async () => { const schema = new Parse.Schema("Note"); schema.addPointer("board", "Board", {required: true}); schema.addPointer("parent", "Note", {required: false}); schema.addString("columnId", {required: true}); schema.addNumber("positionInStack", {required: true, defaultValue: -1}); schema.addPointer("author", "_User", {required: true}); schema.addBoolean("focus", {required: true, defaultValue: false}); schema.addString("text", {required: true}); schema.addNumber("schemaVersion", {required: true, defaultValue: 1}); return schema.save(); }; const addInitialVoteSchema = async () => { const schema = new Parse.Schema("Vote"); schema.addPointer("board", "Board", {required: true}); schema.addPointer("note", "Note", {required: true}); schema.addPointer("user", "_User", {required: true}); schema.addNumber("votingIteration", {required: true, defaultValue: 0}); schema.addNumber("schemaVersion", {required: true, defaultValue: 1}); return schema.save(); }; const addInitialVoteConfigurationSchema = async () => { const schema = new Parse.Schema("VoteConfiguration"); schema.addPointer("board", "Board", {required: true}); schema.addNumber("votingIteration", {required: true, defaultValue: 0}); schema.addNumber("voteLimit", {required: true, defaultValue: 10}); schema.addBoolean("allowMultipleVotesPerNote", {required: true, defaultValue: true}); schema.addBoolean("showVotesOfOtherUsers", {required: true, defaultValue: false}); schema.addNumber("schemaVersion", {required: true, defaultValue: 1}); return schema.save(); }; const addInitialJoinRequestSchema = async () => { const schema = new Parse.Schema("JoinRequest"); schema.addPointer("user", "_User", {required: true}); schema.addPointer("board", "Board", {required: true}); schema.addString("status", {required: true, defaultValue: "pending"}); schema.addString("accessKey"); schema.addNumber("schemaVersion", {required: true, defaultValue: 1}); return schema.save(); }; export const initServer = async (appId: string, serverUrl: string, masterKey: string) => { Parse.initialize(appId); Parse.serverURL = serverUrl; Parse.masterKey = masterKey; const config = await Parse.Config.get({useMasterKey: true}); const versions = config.get("versions"); if (!versions) { await addInitialBoardSchema(); await addInitialNoteSchema(); await addInitialJoinRequestSchema(); await addInitialVoteSchema(); await addInitialVoteConfigurationSchema(); console.log("Initialized schema"); await Parse.Config.save({ versions: { Board: 1, Note: 1, JoinRequest: 1, Vote: 1, }, }); } // check for schema versions and migrate schemes here // if (versions.Board === 1) { ... } };
Accessible-Concepts/scrumlr.io
src/store/action/__tests__/index.test.ts
<filename>src/store/action/__tests__/index.test.ts import {UsersActionFactory} from "../users"; import {ActionFactory} from "../index"; import {NoteActionFactory} from "../note"; import {ColumnActionFactory} from "../column"; import {BoardActionFactory} from "../board"; describe("actions", () => { test("all board actions are listen in action factory", () => { Object.keys(BoardActionFactory).forEach((actionGenerator) => { expect(ActionFactory[actionGenerator]).not.toBeUndefined(); }); }); test("all column actions are listen in action factory", () => { Object.keys(ColumnActionFactory).forEach((actionGenerator) => { expect(ActionFactory[actionGenerator]).not.toBeUndefined(); }); }); test("all note actions are listen in action factory", () => { Object.keys(NoteActionFactory).forEach((actionGenerator) => { expect(ActionFactory[actionGenerator]).not.toBeUndefined(); }); }); test("all users actions are listen in action factory", () => { Object.keys(UsersActionFactory).forEach((actionGenerator) => { expect(ActionFactory[actionGenerator]).not.toBeUndefined(); }); }); });
Accessible-Concepts/scrumlr.io
src/components/BoardHeader/HeaderMenu/index.ts
<reponame>Accessible-Concepts/scrumlr.io export * from "./HeaderMenu";
Accessible-Concepts/scrumlr.io
src/components/BoardHeader/HeaderMenu/BoardSettings/index.ts
<reponame>Accessible-Concepts/scrumlr.io export * from "./BoardSettings";
Accessible-Concepts/scrumlr.io
src/components/TextInputAdornment/index.ts
export * from "./TextInputAdornment";
Accessible-Concepts/scrumlr.io
src/types/column.ts
import {Color} from "constants/colors"; export type EditableColumnAttributes = { name: string; color: Color; hidden: boolean; }; export type EditColumnRequest = {columnId: string} & Partial<EditableColumnAttributes>; export type AddColumnRequest = EditableColumnAttributes; export interface ColumnServerModel { [columnId: string]: { name: string; color: string; hidden: boolean; }; } export interface ColumnClientModel { columnId?: string; name: string; color: Color; hidden: boolean; }
Accessible-Concepts/scrumlr.io
src/store/middleware/note.ts
import {AnyAction, Dispatch, MiddlewareAPI} from "redux"; import {ApplicationState} from "types/store"; import {API} from "api"; import {ActionType, ReduxAction} from "../action"; export const passNoteMiddleware = (stateAPI: MiddlewareAPI<Dispatch<AnyAction>, ApplicationState>, dispatch: Dispatch, action: ReduxAction) => { if (action.type === ActionType.AddNote) { const boardId = stateAPI.getState().board.data!.id; // TODO retry mechanism API.addNote(boardId, action.columnId, action.text); } if (action.type === ActionType.DeleteNote) { // TODO retry mechanism API.deleteNote(action.noteId); } if (action.type === ActionType.EditNote) { // TODO retry mechanism API.editNote(action.note); } if (action.type === ActionType.UnstackNote) { // TODO retry mechanism const boardId = stateAPI.getState().board.data!.id; API.unstackNote(action.note, boardId); } if (action.type === ActionType.DragNote) { // TODO retry mechanism const boardId = stateAPI.getState().board.data!.id; API.dragNote(action.note, boardId); } };
Accessible-Concepts/scrumlr.io
src/components/Request/Request.tsx
<reponame>Accessible-Concepts/scrumlr.io<gh_stars>0 import store from "store"; import {ActionFactory} from "store/action"; import {JoinRequestClientModel} from "types/joinRequest"; import "./Request.scss"; import {useTranslation} from "react-i18next"; import {UserClientModel} from "types/user"; import {UserAvatar} from "../BoardUsers"; export const Request = ({ joinRequests, users, raisedHands, boardId, }: { joinRequests: JoinRequestClientModel[]; users: UserClientModel[]; raisedHands: string[]; boardId: string; }) => { const {t} = useTranslation(); const handleAccept = (requestedBoardId: string, userIds: string[]) => () => { store.dispatch(ActionFactory.acceptJoinRequests(requestedBoardId, userIds)); }; const handleReject = (requestedBoardId: string, userIds: string[]) => () => { store.dispatch(ActionFactory.rejectJoinRequests(requestedBoardId, userIds)); }; const lowerHand = (userId: string[]) => { store.dispatch(ActionFactory.setRaisedHandStatus({userId, raisedHand: false})); }; let title = ""; if (joinRequests.length !== 0 && raisedHands.length !== 0) title = t("Request.title"); else if (joinRequests.length === 0) title = t("RaiseRequest.title"); else if (raisedHands.length === 0) title = t("JoinRequest.title"); return ( <div> {(joinRequests.length !== 0 || raisedHands.length !== 0) && ( <div className="join-request"> <div className="request__header">{title}</div> <div className="request__main"> <ul className="request__requests"> {joinRequests.map((joinRequest) => ( <li key={joinRequest.id} className="join-request__unique-request-container"> <figure className="join-request__request-figure"> <UserAvatar id={joinRequest.userId} name={joinRequest.displayName} /> <figcaption className="join-request__request-display-name">{joinRequest.displayName}</figcaption> </figure> <div> <button className="request__button" onClick={handleReject(boardId, [joinRequest.userId])}> {t("JoinRequest.reject")} </button> <button className="request__button" onClick={handleAccept(boardId, [joinRequest.userId])}> {t("JoinRequest.accept")} </button> </div> </li> ))} {raisedHands.map((userId) => ( <li key={userId} className="join-request__unique-request-container"> <figure className="join-request__request-figure"> <UserAvatar id={userId} name={users.find((user) => user.id === userId)!.displayName} /> <figcaption className="join-request__request-display-name">{users.find((user) => user.id === userId)!.displayName}</figcaption> </figure> <div> <button className="request__button" onClick={() => lowerHand([userId])}> {t("RaiseRequest.lower")} </button> </div> </li> ))} </ul> </div> {(joinRequests.length > 1 || raisedHands.length > 1) && ( <div className="request__footer"> {raisedHands.length > 1 && ( <button className="request__button" onClick={() => lowerHand(raisedHands)}> {t("RaiseRequest.lowerAll")} </button> )} {joinRequests.length > 1 && ( <> <button className="request__button" onClick={handleReject( joinRequests[0].boardId, joinRequests.map((joinRequest) => joinRequest.userId) )} > {t("JoinRequest.rejectAll")} </button> <button className="request__button" onClick={handleAccept( joinRequests[0].boardId, joinRequests.map((joinRequest) => joinRequest.userId) )} > {t("JoinRequest.acceptAll")} </button>{" "} </> )} </div> )} </div> )} </div> ); };
Accessible-Concepts/scrumlr.io
src/components/AccessPolicySelection/AccessPolicySelection.tsx
import {FC, useState} from "react"; import "./AccessPolicySelection.scss"; import {AccessPolicy} from "types/board"; import {generateRandomString} from "utils/random"; import {useTranslation} from "react-i18next"; import {ReactComponent as IconRefresh} from "assets/icon-refresh.svg"; import {ReactComponent as IconClipboard} from "assets/icon-clipboard.svg"; import {TextInputAdornment} from "components/TextInputAdornment"; import {ReactComponent as VisibleIcon} from "assets/icon-visible.svg"; import {ReactComponent as HiddenIcon} from "assets/icon-hidden.svg"; import {TextInputLabel} from "../TextInputLabel"; import {TextInput} from "../TextInput"; import {Button} from "../Button"; import {ValidationError} from "../ValidationError"; import {TextInputAction} from "../TextInputAction"; export interface AccessPolicySelectionProps { accessPolicy: AccessPolicy; onAccessPolicyChange: (accessPolicy: AccessPolicy) => void; passphrase: string; onPassphraseChange: (passphrase: string) => void; } export const AccessPolicySelection: FC<AccessPolicySelectionProps> = ({accessPolicy, onAccessPolicyChange, passphrase, onPassphraseChange}) => { const {t} = useTranslation(); const [visiblePassphrase, setVisiblePassphrase] = useState(true); const handlePolicyChange = (newAccessPolicy: AccessPolicy) => { if (newAccessPolicy >= 0 && newAccessPolicy <= 2) { onAccessPolicyChange(newAccessPolicy); } }; let AccessPolicyDescription; let AdditionalAccessPolicySettings; switch (accessPolicy) { case AccessPolicy.ByPassphrase: AccessPolicyDescription = <span>{t("AccessPolicySelection.byPassphrase")}</span>; AdditionalAccessPolicySettings = ( <> <TextInputLabel label={t("AccessPolicySelection.passphrase")} htmlFor="access-policy-selection__password" /> <TextInput id="access-policy-selection__password" data-testid="passphrase-input" type={visiblePassphrase ? "text" : "password"} value={passphrase} onChange={(e) => onPassphraseChange(e.target.value)} rightAdornment={ <TextInputAdornment title={t("AccessPolicySelection.togglePassphraseVisibility")} onClick={() => setVisiblePassphrase(!visiblePassphrase)}> {visiblePassphrase && <VisibleIcon />} {!visiblePassphrase && <HiddenIcon />} </TextInputAdornment> } actions={ <> <TextInputAction data-testid="random-passwort-generator" onClick={() => onPassphraseChange(generateRandomString())} title={t("AccessPolicySelection.generatePassphrase")} > <IconRefresh /> </TextInputAction> <TextInputAction onClick={() => navigator.clipboard.writeText(passphrase)} disabled={!passphrase} title={t("AccessPolicySelection.copyPassphraseToClipboard")}> <IconClipboard /> </TextInputAction> </> } /> {!passphrase && <ValidationError>{t("AccessPolicySelection.passphraseValidationError")}</ValidationError>} </> ); break; case AccessPolicy.ManualVerification: AccessPolicyDescription = <span>{t("AccessPolicySelection.manualVerification")}</span>; break; case AccessPolicy.Public: default: AccessPolicyDescription = <span>{t("AccessPolicySelection.public")}</span>; break; } return ( <div className="access-policy-selection"> <h2 className="access-policy-selection__title">{t("AccessPolicySelection.title")}</h2> <div className="access-policy-selection__tabs"> <Button className="access-policy-selection__access-policy" variant={accessPolicy === AccessPolicy.Public ? "contained" : "outlined"} onClick={() => handlePolicyChange(AccessPolicy.Public)} > {t("AccessPolicySelection.publicTitle")} </Button> <Button className="access-policy-selection__access-policy" variant={accessPolicy === AccessPolicy.ByPassphrase ? "contained" : "outlined"} onClick={() => handlePolicyChange(AccessPolicy.ByPassphrase)} > {t("AccessPolicySelection.byPassphraseTitle")} </Button> <Button className="access-policy-selection__access-policy" variant={accessPolicy === AccessPolicy.ManualVerification ? "contained" : "outlined"} onClick={() => handlePolicyChange(AccessPolicy.ManualVerification)} > {t("AccessPolicySelection.manualVerificationTitle")} </Button> </div> <div className="access-policy__details"> {AccessPolicyDescription} {AdditionalAccessPolicySettings && <div className="access-policy-selection__additional-settings">{AdditionalAccessPolicySettings}</div>} </div> </div> ); };
Accessible-Concepts/scrumlr.io
src/store/index.ts
import {createStore, applyMiddleware, combineReducers, Dispatch, MiddlewareAPI, AnyAction} from "redux"; import {TypedUseSelectorHook, useSelector} from "react-redux"; import thunk from "redux-thunk"; import {composeWithDevTools} from "redux-devtools-extension"; import {ApplicationState} from "types/store"; import {ReduxAction} from "./action"; import {boardReducer} from "./reducer/board"; import {noteReducer} from "./reducer/note"; import {voteReducer} from "./reducer/vote"; import {usersReducer} from "./reducer/users"; import {voteConfigurationReducer} from "./reducer/voteConfiguration"; import {passNoteMiddleware} from "./middleware/note"; import {passVoteMiddlware} from "./middleware/vote"; import {passBoardMiddleware} from "./middleware/board"; import {passBoardJoinConfirmationMiddleware} from "./middleware/boardJoinConfirmation"; import {passColumnMiddleware} from "./middleware/column"; import {passJoinRequestMiddleware} from "./middleware/joinRequest"; import {passUsersMiddleware} from "./middleware/users"; import {joinRequestReducer} from "./reducer/joinRequest"; import {passVoteConfigurationMiddlware} from "./middleware/voteConfiguration"; const parseMiddleware = (stateAPI: MiddlewareAPI<Dispatch<AnyAction>, ApplicationState>) => (dispatch: Dispatch) => (action: ReduxAction) => { try { return dispatch(action); } finally { passBoardJoinConfirmationMiddleware(stateAPI, dispatch, action); passBoardMiddleware(stateAPI, dispatch, action); passColumnMiddleware(stateAPI, dispatch, action); passVoteConfigurationMiddlware(stateAPI, dispatch, action); passNoteMiddleware(stateAPI, dispatch, action); passVoteMiddlware(stateAPI, dispatch, action); passJoinRequestMiddleware(stateAPI, dispatch, action); passUsersMiddleware(stateAPI, dispatch, action); } }; const rootReducer = combineReducers<ApplicationState>({ board: boardReducer, notes: noteReducer, users: usersReducer, joinRequests: joinRequestReducer, votes: voteReducer, voteConfiguration: voteConfigurationReducer, }); const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk), applyMiddleware(parseMiddleware))); export default store; type RootState = ReturnType<typeof store.getState>; export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
Accessible-Concepts/scrumlr.io
src/components/NoteDialog/NoteDialogComponents/index.ts
<gh_stars>10-100 import {NoteDialogNote as Note} from "./NoteDialogNote"; import {NoteDialogHeader as Header} from "./NoteDialogHeader"; import {NoteDialogNoteWrapper as Wrapper} from "./NoteDialogNoteWrapper"; export const NoteDialogComponents = { Header, Note, Wrapper, };
Accessible-Concepts/scrumlr.io
src/types/__tests__/user.test.ts
<filename>src/types/__tests__/user.test.ts import {mapUserServerToClientModel, UserClientModel, UserServerModel} from "../user"; describe("User types", () => { test("mapVoteServerToClientModel", async () => { const serverModel: UserServerModel = { objectId: "test_objectId", displayName: "test_displayName", createdAt: new Date(1234), updatedAt: new Date(1234), }; const clientModel: UserClientModel = mapUserServerToClientModel(serverModel, {admin: false, online: false}); expect(clientModel.id).toEqual(serverModel.objectId); expect(clientModel.displayName).toEqual(serverModel.displayName); expect(clientModel.createdAt).toEqual(serverModel.createdAt); expect(clientModel.updatedAt).toEqual(serverModel.updatedAt); expect(clientModel.ready).toEqual(false); expect(clientModel.online).toEqual(false); expect(clientModel.admin).toEqual(false); }); });
Accessible-Concepts/scrumlr.io
src/components/MenuBars/MenuBars.tsx
import React, {useState} from "react"; import {ActionFactory} from "store/action"; import store, {useAppSelector} from "store"; import Parse from "parse"; import _ from "underscore"; import classNames from "classnames"; import {MenuToggle} from "components/MenuBars/MenuItem"; import {ReactComponent as RaiseHand} from "assets/icon-hand.svg"; import {ReactComponent as CheckIcon} from "assets/icon-check.svg"; import {ReactComponent as FocusIcon} from "assets/icon-focus.svg"; import {ReactComponent as ToggleSettingsMenuIcon} from "assets/icon-toggle-settings-menu.svg"; import {ReactComponent as ToggleAddMenuIcon} from "assets/icon-toggle-add-menu.svg"; import {TabIndex} from "constants/tabIndex"; import {useTranslation} from "react-i18next"; import {TimerToggleButton} from "./MenuItem/variants/TimerToggleButton"; import {VoteConfigurationButton} from "./MenuItem/variants/VoteConfigurationButton"; import {ThemeToggleButton} from "./MenuItem/variants/ThemeToggleButton"; import "./MenuBars.scss"; export const MenuBars = () => { const {t} = useTranslation(); const [showAdminMenu, toggleMenus] = useState(false); const [animate, setAnimate] = useState(false); const currentUser = Parse.User.current(); const state = useAppSelector( (rootState) => ({ admins: rootState.users.admins, allUsers: rootState.users.all, boardId: rootState.board.data!.id, timer: rootState.board.data?.timerUTCEndTime, voting: rootState.board.data?.voting, moderation: rootState.board.data?.moderation.status, }), _.isEqual ); const isAdmin = state.admins.map((admin) => admin.id).indexOf(currentUser!.id) !== -1; const isReady = state.allUsers.find((user) => user.id === currentUser!.id)?.ready; const raisedHand = state.allUsers.find((user) => user.id === currentUser!.id)?.raisedHand; const toggleModeration = (active: boolean) => { store.dispatch(ActionFactory.editBoard({id: state.boardId, moderation: {userId: Parse.User.current()?.id, status: active ? "active" : "disabled"}})); }; const toggleReadyState = () => { store.dispatch(ActionFactory.setUserReadyStatus(!isReady)); }; const handleAnimate = (event: React.TransitionEvent<HTMLElement>) => { if (event.currentTarget.attributes.getNamedItem("class")?.nodeValue?.includes("menu-animation")) { setAnimate(false); } }; const toggleRaiseHand = (active: boolean) => { store.dispatch(ActionFactory.setRaisedHandStatus({userId: [Parse.User.current()!.id], raisedHand: active})); }; return ( <aside id="menu-bars" className={classNames("menu-bars", {"menu-bars--admin": showAdminMenu, "menu-bars--user": !showAdminMenu}, {"menu-bars--isAdmin": isAdmin})}> <section className={classNames("menu", "user-menu", {"menu-animation": animate})} onTransitionEnd={(event) => handleAnimate(event)}> <div className="menu__items"> <MenuToggle direction="right" value={isReady} toggleStartLabel={t("MenuBars.markAsDone")} toggleStopLabel={t("MenuBars.unmarkAsDone")} icon={CheckIcon} onToggle={toggleReadyState} tabIndex={TabIndex.UserMenu} /> <MenuToggle tabIndex={TabIndex.UserMenu + 1} direction="right" toggleStartLabel={t("MenuBars.raiseHand")} toggleStopLabel={t("MenuBars.lowerHand")} icon={RaiseHand} onToggle={toggleRaiseHand} value={raisedHand} /> <ThemeToggleButton tabIndex={TabIndex.UserMenu + 2} direction="right" /> </div> </section> {isAdmin && ( <section className={classNames("menu", "admin-menu", {"menu-animation": animate})} onTransitionEnd={(event) => handleAnimate(event)}> <div className="menu__items"> <TimerToggleButton tabIndex={TabIndex.AdminMenu} /> <VoteConfigurationButton tabIndex={TabIndex.AdminMenu + 8} /> <MenuToggle value={state.moderation === "active"} direction="left" toggleStartLabel={t("MenuBars.startFocusMode")} toggleStopLabel={t("MenuBars.stopFocusMode")} icon={FocusIcon} onToggle={toggleModeration} tabIndex={TabIndex.AdminMenu + 15} /> </div> </section> )} {isAdmin && ( <button className="menu-bars__switch" onClick={() => { setAnimate(true); toggleMenus((prevState) => !prevState); }} > <ToggleAddMenuIcon className="switch__icon switch__icon--add" /> <ToggleSettingsMenuIcon className="switch__icon switch__icon--settings" /> </button> )} </aside> ); };
Accessible-Concepts/scrumlr.io
src/types/index.ts
export type StatusResponse = {status: string; description: string};
Accessible-Concepts/scrumlr.io
src/components/PassphraseDialog/index.ts
<filename>src/components/PassphraseDialog/index.ts export * from "./PassphraseDialog";
Accessible-Concepts/scrumlr.io
src/components/Dropdown/DropdownItem.tsx
<reponame>Accessible-Concepts/scrumlr.io import React from "react"; import classNames from "classnames"; import {DropdownProps} from "./DropdownProps"; export const DropdownItem: React.FC<DropdownProps> = ({className, children, ...other}) => ( <li className={classNames("dropdown__item", className)} {...other}> {children} </li> );
Accessible-Concepts/scrumlr.io
src/store/action/__tests__/voteConfiguration.test.ts
<reponame>Accessible-Concepts/scrumlr.io<gh_stars>10-100 import {AssertTypeEqual} from "testUtils"; import {VoteConfigurationClientModel} from "types/voteConfiguration"; import {ReduxAction} from "store/action"; import {VoteConfigurationActionFactory, VoteConfigurationActionType, VoteConfigurationReduxAction} from "store/action/voteConfiguration"; describe("vote comfiguration actions", () => { test("equal number of action types and factory functions", () => { expect(Object.keys(VoteConfigurationActionType).length).toEqual(Object.keys(VoteConfigurationActionFactory).length); }); describe("add vote configuration", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof VoteConfigurationActionFactory.addVoteConfiguration>, VoteConfigurationReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof VoteConfigurationActionFactory.addVoteConfiguration>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = VoteConfigurationActionFactory.addVoteConfiguration({boardId: "test_board", voteLimit: 5, allowMultipleVotesPerNote: true, showVotesOfOtherUsers: true}); expect(action).toEqual({ type: "@@SCRUMLR/addVoteConfiguration", voteConfiguration: { boardId: "test_board", voteLimit: 5, allowMultipleVotesPerNote: true, showVotesOfOtherUsers: true, }, }); }); }); describe("initialize vote configuration", () => { test("type is listed in users redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof VoteConfigurationActionFactory.initializeVoteConfiguration>, VoteConfigurationReduxAction> = true; expect(assertion).toBe(true); }); test("type is listed in general redux actions", () => { // testing type equality here will not report an error at runtime but cause problems with typescript const assertion: AssertTypeEqual<ReturnType<typeof VoteConfigurationActionFactory.initializeVoteConfiguration>, ReduxAction> = true; expect(assertion).toBe(true); }); test("created action", () => { const action = VoteConfigurationActionFactory.initializeVoteConfiguration({ boardId: "test_board", votingIteration: 1, voteLimit: 5, allowMultipleVotesPerNote: true, showVotesOfOtherUsers: true, } as unknown as VoteConfigurationClientModel); expect(action).toEqual({ type: "@@SCRUMLR/initializeVoteConfiguration", voteConfiguration: { boardId: "test_board", votingIteration: 1, voteLimit: 5, allowMultipleVotesPerNote: true, showVotesOfOtherUsers: true, }, }); }); }); });
Accessible-Concepts/scrumlr.io
src/components/BoardUsers/index.ts
export * from "./BoardUsers"; export * from "./UserAvatar";
Accessible-Concepts/scrumlr.io
src/store/reducer/__tests__/voteConfiguration.test.ts
import {ApplicationState} from "types/store"; import {VoteConfigurationClientModel} from "types/voteConfiguration"; import {voteConfigurationReducer} from "store/reducer/voteConfiguration"; import {ActionFactory} from "store/action"; describe("vote configuration reducer", () => { let initialState: ApplicationState; beforeEach(() => { initialState = { voteConfiguration: {boardId: "test_board", votingIteration: 0, voteLimit: 0, allowMultipleVotesPerNote: false, showVotesOfOtherUsers: true}, board: {status: "unknown"}, users: {admins: [], basic: [], all: [], usersMarkedReady: [], usersRaisedHands: []}, notes: [], votes: [], joinRequests: [], }; }); test("add vote configuration", () => { const voteConfiguration = { boardId: "test_board", votingIteration: 1, voteLimit: 5, allowMultipleVotesPerNote: false, showVotesOfOtherUsers: true, } as VoteConfigurationClientModel; const newState = voteConfigurationReducer(initialState.voteConfiguration, ActionFactory.addedVoteConfiguration(voteConfiguration)); expect(newState).toEqual(voteConfiguration); }); });
Accessible-Concepts/scrumlr.io
src/components/Avatar/Avatar.tsx
import Avataar from "avataaars"; import React from "react"; import "./Avatar.scss"; import classNames from "classnames"; import {getColorClassName, getColorForIndex} from "../../constants/colors"; import { AVATAR_ACCESSORIES_TYPES, AVATAR_CLOTHE_COLORS, AVATAR_CLOTHE_TYPES, AVATAR_EYE_TYPES, AVATAR_EYEBROW_TYPES, AVATAR_FACIAL_HAIR_COLORS, AVATAR_FACIAL_HAIR_TYPES, AVATAR_GRAPHIC_TYPES, AVATAR_HAIR_COLORS, AVATAR_MOUTH_TYPES, AVATAR_SKIN_COLORS, AVATAR_TOP_TYPES, AvatarAccessoriesType, AvatarClotheColor, AvatarClotheType, AvatarEyebrowType, AvatarEyeType, AvatarFacialHairColor, AvatarFacialHairType, AvatarGraphicType, AvatarHairColor, AvatarMouthType, AvatarSkinColor, AvatarTopType, } from "./types"; export interface AvatarProps { seed?: string; className?: string; skinColor?: AvatarSkinColor; topType?: AvatarTopType; clotheColor?: AvatarClotheColor; graphicType?: AvatarGraphicType; clotheType?: AvatarClotheType; hairColor?: AvatarHairColor; facialHairColor?: AvatarFacialHairColor; facialHairType?: AvatarFacialHairType; accessoriesType?: AvatarAccessoriesType; eyeType?: AvatarEyeType; eyebrowType?: AvatarEyebrowType; mouthType?: AvatarMouthType; } /** * Generates a fixed hash number for any given string. * * @param s the string to hash * @returns the hash code */ const hashCode = (s: string) => { let hash = 0; const stringLength = s.length; let i = 0; if (stringLength > 0) { while (i < stringLength) { // eslint-disable-next-line no-bitwise hash = ((hash << 5) - hash + s.charCodeAt(i++)) | 0; } } return Math.abs(hash); }; /** * Generates a set of properties by the specified seed. * * @param seed the seed will be hashed by the `hashCode` function and define the outcome * @returns a set of properties for the `<Avatar />` component */ const generateRandomProps = (seed: string) => { const hash = hashCode(seed); const props: AvatarProps = {}; props.skinColor = AVATAR_SKIN_COLORS[hash % AVATAR_SKIN_COLORS.length]; props.topType = AVATAR_TOP_TYPES[hash % AVATAR_TOP_TYPES.length]; props.clotheType = AVATAR_CLOTHE_TYPES[hash % AVATAR_CLOTHE_TYPES.length]; props.clotheColor = AVATAR_CLOTHE_COLORS[hash % AVATAR_CLOTHE_COLORS.length]; props.graphicType = AVATAR_GRAPHIC_TYPES[hash % AVATAR_GRAPHIC_TYPES.length]; props.hairColor = AVATAR_HAIR_COLORS[hash % AVATAR_HAIR_COLORS.length]; const hasFacialHair = hash % 4 === 1 || hash % 4 === 2; if (hasFacialHair) { props.facialHairColor = AVATAR_FACIAL_HAIR_COLORS[hash % AVATAR_FACIAL_HAIR_COLORS.length]; props.facialHairType = AVATAR_FACIAL_HAIR_TYPES[hash % AVATAR_FACIAL_HAIR_TYPES.length]; } const hasAccessories = hash % 4 === 2 || hash % 4 === 3; if (hasAccessories) { props.accessoriesType = AVATAR_ACCESSORIES_TYPES[hash % AVATAR_ACCESSORIES_TYPES.length]; } props.eyebrowType = AVATAR_EYEBROW_TYPES[hash % AVATAR_EYEBROW_TYPES.length]; props.eyeType = AVATAR_EYE_TYPES[hash % AVATAR_EYE_TYPES.length]; props.mouthType = AVATAR_MOUTH_TYPES[hash % AVATAR_MOUTH_TYPES.length]; props.className = getColorClassName(getColorForIndex(hash)); return props; }; /** * This components renders an avatar of a person. If the prop `seed` is set the * properties for the look will be generated. * * @param seed The seed will define the define the set of properties if define. * @param className Additional CSS classes * @param skinColor the skin color * @param topType the style for the top of the head (e.g. a hat or hair) * @param clotheColor the clothe color * @param graphicType the graphic if the clothe is a graphic shirt * @param clotheType the clothe type * @param hairColor the hair color * @param facialHairColor the facial hair color * @param facialHairType the facial hair type * @param accessoriesType optional accessories the avatars can have * @param eyebrowType the eyebrow type * @param eyeType the eye type * @param mouthType the mouth type */ export const Avatar = React.memo( ({ seed, className, skinColor, topType, clotheColor, graphicType, clotheType, hairColor, facialHairColor, facialHairType, accessoriesType, eyebrowType, eyeType, mouthType, }: AvatarProps) => { if (seed) { const {className: accentColorClass, ...avatarProps} = generateRandomProps(seed); return <Avataar className={classNames("avatar", className, accentColorClass)} avatarStyle="Circle" {...avatarProps} />; } return ( <Avataar className={classNames("avatar", className)} avatarStyle="Circle" topType={topType} accessoriesType={accessoriesType} hairColor={hairColor} facialHairType={facialHairType} facialHairColor={facialHairColor} clotheType={clotheType} clotheColor={clotheColor} graphicType={graphicType} eyeType={eyeType} eyebrowType={eyebrowType} mouthType={mouthType} skinColor={skinColor} /> ); }, (prev, next) => prev.seed === next.seed );
Accessible-Concepts/scrumlr.io
src/store/middleware/column.ts
import {AnyAction, Dispatch, MiddlewareAPI} from "redux"; import {ApplicationState} from "types/store"; import {ActionType, ReduxAction} from "store/action"; import {API} from "api"; export const passColumnMiddleware = (stateAPI: MiddlewareAPI<Dispatch<AnyAction>, ApplicationState>, dispatch: Dispatch, action: ReduxAction) => { if (action.type === ActionType.AddColumn) { const boardId = stateAPI.getState().board.data!.id; // TODO retry mechanism API.addColumn(boardId, action.column); } if (action.type === ActionType.DeleteColumn) { const boardId = stateAPI.getState().board.data!.id; // TODO retry mechanism API.deleteColumn(boardId, action.columnId); } if (action.type === ActionType.EditColumn) { const boardId = stateAPI.getState().board.data!.id; // TODO retry mechanism API.editColumn(boardId, action.column); } };
Accessible-Concepts/scrumlr.io
src/components/Dropdown/__tests__/Dropdown.test.tsx
<filename>src/components/Dropdown/__tests__/Dropdown.test.tsx import {fireEvent} from "@testing-library/react"; import {render} from "testUtils"; import Dropdown from "../Dropdown"; describe("Dropdown", () => { const onClickMock = jest.fn(); const dropdownComponent = ( <Dropdown> <Dropdown.Main> <Dropdown.Item>Item</Dropdown.Item> <Dropdown.ItemButton onClick={onClickMock}>Item Button</Dropdown.ItemButton> </Dropdown.Main> <Dropdown.Footer> <Dropdown.Item>Item</Dropdown.Item> </Dropdown.Footer> </Dropdown> ); test("should render correctly", () => { const {container} = render(dropdownComponent); expect(container.firstChild).toMatchSnapshot(); }); test("item button should call callback on click event", () => { const {container} = render(dropdownComponent); const itemButton = container.getElementsByTagName("button")[0]; fireEvent.click(itemButton); expect(onClickMock).toHaveBeenCalled(); }); });
Accessible-Concepts/scrumlr.io
src/store/action/joinRequest.ts
<reponame>Accessible-Concepts/scrumlr.io import {JoinRequestClientModel} from "types/joinRequest"; export const JoinRequestActionType = { AcceptJoinRequests: "@@scrumlr/acceptJoinRequests" as const, RejectJoinRequests: "@@scrumlr/rejectJoinRequests" as const, InitializeJoinRequests: "@@scrumlr/initializeJoinRequests" as const, CreateJoinRequest: "@@scrumlr/createJoinRequest" as const, UpdateJoinRequest: "@@scrumlr/updateJoinRequest" as const, }; export const JoinRequestActionFactory = { acceptJoinRequests: (boardId: string, userIds: string[]) => ({ type: JoinRequestActionType.AcceptJoinRequests, boardId, userIds, }), rejectJoinRequests: (boardId: string, userIds: string[]) => ({ type: JoinRequestActionType.RejectJoinRequests, boardId, userIds, }), initializeJoinRequests: (joinRequests: JoinRequestClientModel[]) => ({ type: JoinRequestActionType.InitializeJoinRequests, joinRequests, }), createJoinRequest: (joinRequest: JoinRequestClientModel) => ({ type: JoinRequestActionType.CreateJoinRequest, joinRequest, }), updateJoinRequest: (joinRequest: JoinRequestClientModel) => ({ type: JoinRequestActionType.UpdateJoinRequest, joinRequest, }), }; export type JoinRequestReduxAction = | ReturnType<typeof JoinRequestActionFactory.acceptJoinRequests> | ReturnType<typeof JoinRequestActionFactory.rejectJoinRequests> | ReturnType<typeof JoinRequestActionFactory.initializeJoinRequests> | ReturnType<typeof JoinRequestActionFactory.createJoinRequest> | ReturnType<typeof JoinRequestActionFactory.updateJoinRequest>;
Accessible-Concepts/scrumlr.io
src/components/TextInputLabel/index.ts
<reponame>Accessible-Concepts/scrumlr.io export * from "./TextInputLabel";
Accessible-Concepts/scrumlr.io
src/components/NoteDialog/__tests__/NoteDialog.test.tsx
<filename>src/components/NoteDialog/__tests__/NoteDialog.test.tsx<gh_stars>0 import {fireEvent, waitFor} from "@testing-library/react"; import configureStore from "redux-mock-store"; import {Provider} from "react-redux"; import {wrapWithTestBackend} from "react-dnd-test-utils"; import {User} from "parse"; import {NoteDialog} from "components/NoteDialog"; import {mocked} from "ts-jest/utils"; import store from "store"; import {ActionFactory} from "store/action"; import {render} from "testUtils"; const mockStore = configureStore(); const mockedUser = mocked(User, true); jest.mock("store", () => ({ ...jest.requireActual("store"), dispatch: jest.fn(), })); type NoteDialogTestProps = { text?: string; authorId?: string; showAuthors?: boolean; activeModeration?: {userId: string; status: boolean}; currentUserIsModerator?: boolean; }; const createNoteDialog = ( {text = "Test Text", authorId = "Test Author", showAuthors = true, activeModeration = {userId: authorId, status: false}, currentUserIsModerator = false}: NoteDialogTestProps = { text: "Test Text", authorId: "Test Author", showAuthors: true, activeModeration: {userId: "Test Author", status: false}, currentUserIsModerator: false, } ) => { const initialState = { board: { data: { columns: [{id: "test_column", name: "test_header", hidden: false}], }, }, notes: [], users: { admins: [ { id: "jkKqOUgt3hEDvl7CWcBokVOGs6AzINon", displayName: "<NAME>", admin: true, createdAt: "2021-08-11T10:45:41.640Z", updatedAt: "2021-08-11T10:52:21.558Z", online: true, }, ], basic: [], all: [], }, voteConfiguration: { voteLimit: 10, }, }; const mockedStore = mockStore(initialState); const [NoteDialogContext] = wrapWithTestBackend(NoteDialog); return ( <Provider store={mockedStore}> <NoteDialogContext noteId="0" text={text} authorId={authorId} columnName="" columnColor="" show activeVoting authorName="" showAuthors={showAuthors} votes={[ { id: "test-id", board: "test-board", note: "0", user: "test-user", votingIteration: 1, }, ]} allVotesOfUser={[]} childrenNotes={[ {id: "1", columnId: "test_column", text: "", author: "", parentId: "0", dirty: true, authorName: "", votes: [], focus: false}, {id: "2", columnId: "test_column", text: "", author: "", parentId: "0", dirty: true, authorName: "", votes: [], focus: false}, ]} onClose={() => {}} activeModeration={activeModeration} currentUserIsModerator={currentUserIsModerator} onDeleteOfParent={() => {}} /> </Provider> ); }; describe("<NoteDialog/>", () => { beforeEach(() => { window.IntersectionObserver = jest.fn( () => ({ observe: jest.fn(), disconnect: jest.fn(), } as unknown as IntersectionObserver) ); const portal = global.document.createElement("div"); portal.setAttribute("id", "portal"); global.document.querySelector("body")!.appendChild(portal); }); describe("should render correctly", () => { test("portal--darkBackground is present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); expect(container.firstChild).toHaveClass("portal--darkBackground"); }); test("note-dialog is present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); expect(container.querySelector(".portal__content")?.firstChild).toHaveClass("note-dialog"); }); test("note-dialog__note-header is present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); expect(container.querySelector(".note-dialog")?.firstChild).toHaveClass("note-dialog__header"); }); test("three note-dialog__note present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes.length).toEqual(3); }); test("note-dialog__note one is present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes[0]).toHaveClass("note-dialog__note"); }); test("note-dialog__note two is present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes[1]).toHaveClass("note-dialog__note"); }); test("note-dialog__note three is present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes[2]).toHaveClass("note-dialog__note"); }); test("note-dialog__note-options note two is present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes[1].querySelector(".note-dialog__options")).toBeDefined(); }); test("note-dialog__note-options note three is present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes[2].querySelector(".note-dialog__options")).toBeDefined(); }); describe("NoteDialogNoteContent", () => { test("note-dialog__note-content is present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); expect(container.querySelector(".note-dialog__note")!.querySelector(".note-dialog__note-content")).toBeDefined(); }); test("click on NoteContent as author", async () => { mockedUser.current = jest.fn(() => ({id: "test-user-2"} as never)); const {container} = render(createNoteDialog({authorId: "test-user-2"}), {container: global.document.querySelector("#portal")!}); const noteContentText = container.querySelector(".note-dialog__note-content__text")!; fireEvent.blur(noteContentText, {target: {textContent: "Changed Text"}}); await waitFor(() => { expect(store.dispatch).toHaveBeenCalledWith(ActionFactory.editNote({id: "0", text: "Changed Text"})); }); }); test("click on NoteContent as moderator", async () => { mockedUser.current = jest.fn(() => ({id: "test-user-2"} as never)); const {container} = render(createNoteDialog({currentUserIsModerator: true}), {container: global.document.querySelector("#portal")!}); const noteContentText = container.querySelector(".note-dialog__note-content__text")!; fireEvent.blur(noteContentText, {target: {textContent: "Changed Text"}}); await waitFor(() => { expect(store.dispatch).toHaveBeenCalledWith(ActionFactory.editNote({id: "0", text: "Changed Text"})); }); }); test("click on NoteContent as other user", async () => { mockedUser.current = jest.fn(() => ({id: "test-user-2"} as never)); const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); const noteContentText = container.querySelector(".note-dialog__note-content__text")!; fireEvent.blur(noteContentText, {target: {textContent: "Changed Text"}}); await waitFor(() => { expect(store.dispatch).not.toHaveBeenCalled(); }); }); }); test("note-dialog__note-footer is present", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); expect(container.querySelector(".note-dialog__note")!.querySelector(".note-dialog__note-footer")).toBeDefined(); }); test("note-dialog match snapshot", () => { const {container} = render(createNoteDialog(), {container: global.document.querySelector("#portal")!}); expect(container.querySelector(".note-dialog")).toMatchSnapshot(); }); describe("Moderation phase", () => { beforeEach(() => { mockedUser.current = jest.fn(() => ({id: "test-user-2"} as never)); }); test("three note-dialog__note present during moderation phase", () => { const {container} = render(createNoteDialog({activeModeration: {userId: "test-user-1", status: true}, authorId: "test-user-1"}), { container: global.document.querySelector("#portal")!, }); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes.length).toEqual(3); }); test("moderation: last note-dialog__options note isn't present", () => { const {container} = render(createNoteDialog({activeModeration: {userId: "test-user-1", status: true}, authorId: "test-user-1"}), { container: global.document.querySelector("#portal")!, }); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes[noteDialogNotes.length - 1].children.length).toEqual(2); expect(noteDialogNotes[noteDialogNotes.length - 1].querySelector(".note-dialog__note-content")).not.toBeNull(); expect(noteDialogNotes[noteDialogNotes.length - 1].querySelector(".note-dialog__note-footer")).not.toBeNull(); expect(noteDialogNotes[noteDialogNotes.length - 1].querySelector(".note-dialog__note-options")).toBeNull(); }); test("moderation: last note-dialog__notes has two children", () => { const {container} = render(createNoteDialog({activeModeration: {userId: "test-user-1", status: true}, authorId: "test-user-1"}), { container: global.document.querySelector("#portal")!, }); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes[noteDialogNotes.length - 1].children.length).toEqual(2); }); test("moderation: last note-dialog__options note is present", () => { mockedUser.current = jest.fn(() => ({id: "test-user-1"} as never)); const {container} = render(createNoteDialog({activeModeration: {userId: "test-user-1", status: true}, authorId: "test-user-1", currentUserIsModerator: true}), { container: global.document.querySelector("#portal")!, }); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes[noteDialogNotes.length - 1].querySelector(".note-dialog__note-content")).not.toBeNull(); expect(noteDialogNotes[noteDialogNotes.length - 1].querySelector(".note-dialog__note-footer")).not.toBeNull(); expect(noteDialogNotes[noteDialogNotes.length - 1].querySelector(".note-dialog__note-options")).not.toBeNull(); }); test("moderation: last note-dialog__notes has three children", () => { const {container} = render(createNoteDialog({activeModeration: {userId: "test-user-1", status: true}, authorId: "test-user-1", currentUserIsModerator: true}), { container: global.document.querySelector("#portal")!, }); const noteDialogNotes = container.querySelectorAll(".note-dialog__note"); expect(noteDialogNotes[noteDialogNotes.length - 1].children.length).toEqual(2); }); }); }); });
Accessible-Concepts/scrumlr.io
src/components/NoteDialog/NoteDialogComponents/NoteDialogNoteComponents/NoteDialogOptions/NoteDialogUnstackNoteButton.tsx
<gh_stars>0 import {FC} from "react"; import store from "store"; import {ActionFactory} from "store/action"; import {ReactComponent as UnstackIcon} from "assets/icon-unstack.svg"; import {DotButton} from "components/DotButton"; import "./NoteDialogUnstackNoteButton.scss"; import {TabIndex} from "constants/tabIndex"; import {useTranslation} from "react-i18next"; type NoteDialogUnstackNoteProps = { noteId?: string; parentId?: string; onClose: () => void; }; export const NoteDialogUnstackNoteButton: FC<NoteDialogUnstackNoteProps> = ({noteId, parentId, onClose}: NoteDialogUnstackNoteProps) => { const {t} = useTranslation(); const onUnstack = (id: string, parentNoteId: string) => { store.dispatch(ActionFactory.unstackNote({id, parentId: parentNoteId})); }; return ( <DotButton onClick={() => { onUnstack(noteId!, parentId!); onClose(); }} className="note-dialog__note-option__unstack" tabIndex={TabIndex.default} title={t("NoteDialogUnstackNoteButton.title")} > <UnstackIcon className="note-dialog__note-option__unstack-icon" /> </DotButton> ); };
Accessible-Concepts/scrumlr.io
src/components/LoadingIndicator/LoadingIndicator.tsx
<gh_stars>10-100 import "./LoadingIndicator.scss"; export const LoadingIndicator = () => ( <div className="loading-indicator"> <div className="bounce1" /> <div className="bounce2" /> <div className="bounce3" /> </div> );
Accessible-Concepts/scrumlr.io
src/components/NoteDialog/index.ts
export * from "./NoteDialog";
Accessible-Concepts/scrumlr.io
src/routes/LoginBoard/index.ts
export * from "./LoginBoard";
Accessible-Concepts/scrumlr.io
src/components/CookieNotice/__tests__/CookiePolicy.test.tsx
<filename>src/components/CookieNotice/__tests__/CookiePolicy.test.tsx import {render} from "testUtils"; import configureStore from "redux-mock-store"; import {Provider} from "react-redux"; import {CookiePolicy} from "components/CookieNotice"; describe("Cookie Policy should be rendered with:", () => { const mockStore = configureStore(); const store = mockStore({ name: "test", value: null, }); test("cookie policy: title", () => { const portal = global.document.createElement("div"); portal.setAttribute("id", "portal"); global.document.querySelector("body")!.appendChild(portal); const {container} = render( <Provider store={store}> <CookiePolicy accept={() => {}} decline={() => {}} onClose={() => {}} show darkBackground /> </Provider>, {container: global.document.querySelector("#portal")!} ); expect(container.querySelector(".cookie-policy")!.childNodes[0]).toHaveClass("cookie-policy__title"); }); test("cookie policy: body", () => { const portal = global.document.createElement("div"); portal.setAttribute("id", "portal"); global.document.querySelector("body")!.appendChild(portal); const {container} = render( <Provider store={store}> <CookiePolicy accept={() => {}} decline={() => {}} onClose={() => {}} show darkBackground /> </Provider>, {container: global.document.querySelector("#portal")!} ); expect(container.querySelector(".cookie-policy")!.childNodes[1]).toHaveClass("cookie-policy__body"); }); test("cookie policy: footer", () => { const portal = global.document.createElement("div"); portal.setAttribute("id", "portal"); global.document.querySelector("body")!.appendChild(portal); const {container} = render( <Provider store={store}> <CookiePolicy accept={() => {}} decline={() => {}} onClose={() => {}} show darkBackground /> </Provider>, {container: global.document.querySelector("#portal")!} ); expect(container.querySelector(".cookie-policy")!.childNodes[2]).toHaveClass("cookie-policy__footer"); }); test("cookie policy: decline button", () => { const portal = global.document.createElement("div"); portal.setAttribute("id", "portal"); global.document.querySelector("body")!.appendChild(portal); const {container} = render( <Provider store={store}> <CookiePolicy accept={() => {}} decline={() => {}} onClose={() => {}} show darkBackground /> </Provider>, {container: global.document.querySelector("#portal")!} ); expect(container.querySelector(".cookie-policy__footer")!.childNodes[0]).toHaveClass("cookie-policy__button-decline"); }); test("cookie policy: accept button", () => { const portal = global.document.createElement("div"); portal.setAttribute("id", "portal"); global.document.querySelector("body")!.appendChild(portal); const {container} = render( <Provider store={store}> <CookiePolicy accept={() => {}} decline={() => {}} onClose={() => {}} show darkBackground /> </Provider>, {container: global.document.querySelector("#portal")!} ); expect(container.querySelector(".cookie-policy__footer")!.childNodes[1]).toHaveClass("cookie-policy__button-accept"); }); });
Accessible-Concepts/scrumlr.io
src/components/NoteDialog/NoteDialogComponents/NoteDialogNoteWrapper.tsx
<reponame>Accessible-Concepts/scrumlr.io import classNames from "classnames"; import {FC, useEffect} from "react"; import "./NoteDialogNoteWrapper.scss"; export const NoteDialogNoteWrapper: FC = ({children}) => { const handleScroll = (scrollbar: Element) => { const notes = scrollbar.querySelectorAll(".note-dialog__note"); const scrollbarHeight = scrollbar.clientHeight; notes.forEach((note) => { // Top is the div which contains all the notes (.note-dialog__scrollbar) const distanceToTop = note.getBoundingClientRect().top - scrollbar.getBoundingClientRect().top; const noteHeight = note.scrollHeight; let opacity = 1; // Note comes from the top and scrolls in the view (only the lower part is visible) if (distanceToTop < 0) { opacity = (noteHeight + distanceToTop) / noteHeight; } // Is the complete note visible or only the upper part? const remainingSpace = scrollbarHeight - (distanceToTop + noteHeight); if (remainingSpace < 0) { opacity = (scrollbarHeight - distanceToTop) / noteHeight; } // If the card is bigger than our NoteDialog (we don't want to have opacity effects here) if (distanceToTop < 0 && remainingSpace <= 0) { opacity = 1; } if (opacity >= 0) { (note as HTMLElement).style.opacity = opacity.toString(); } }); }; useEffect(() => { const scrollbar = document.querySelector(".note-dialog__scrollbar")!; scrollbar.addEventListener("scroll", () => handleScroll(scrollbar)); }, [children]); return ( <div className={classNames("note-dialog__scrollbar")}> <div className={classNames("note-dialog__note-wrapper")}>{children}</div> </div> ); };
Accessible-Concepts/scrumlr.io
src/store/middleware/__tests__/column.test.ts
<reponame>Accessible-Concepts/scrumlr.io<filename>src/store/middleware/__tests__/column.test.ts import {passColumnMiddleware} from "store/middleware/column"; import {ActionFactory} from "store/action"; import {API} from "api"; import {MiddlewareAPI} from "redux"; jest.mock("api", () => ({ API: { addColumn: jest.fn(), editColumn: jest.fn(), deleteColumn: jest.fn(), }, })); beforeEach(() => { (API.addColumn as jest.Mock).mockClear(); (API.editColumn as jest.Mock).mockClear(); (API.deleteColumn as jest.Mock).mockClear(); }); const stateAPI = { getState: () => ({ board: { data: { id: "boardId", }, }, }), }; describe("column middleware", () => { test("add column", () => { passColumnMiddleware(stateAPI as MiddlewareAPI, jest.fn(), ActionFactory.addColumn({name: "Column", color: "planning-pink", hidden: false})); expect(API.addColumn).toHaveBeenCalledWith("boardId", {name: "Column", color: "planning-pink", hidden: false}); }); test("edit column", () => { passColumnMiddleware(stateAPI as MiddlewareAPI, jest.fn(), ActionFactory.editColumn({columnId: "columnId", name: "New name", color: "planning-pink", hidden: true})); expect(API.editColumn).toHaveBeenCalledWith("boardId", {columnId: "columnId", name: "New name", color: "planning-pink", hidden: true}); }); test("delete column", () => { passColumnMiddleware(stateAPI as MiddlewareAPI, jest.fn(), ActionFactory.deleteColumn("columnId")); expect(API.deleteColumn).toHaveBeenCalledWith("boardId", "columnId"); }); });
Accessible-Concepts/scrumlr.io
src/components/Toggle/Toggle.tsx
<reponame>Accessible-Concepts/scrumlr.io import classNames from "classnames"; import "./Toggle.scss"; import {FC} from "react"; type ToggleProps = { /** * Additional CSS classes. */ className?: string; /** * Disable the toggle. */ disabled?: boolean; active: boolean; }; export const Toggle: FC<ToggleProps> = (props) => <div className={classNames("toggle", {"toggle--active": props.active, "toggle--disabled": props.disabled}, props.className)} />;
Accessible-Concepts/scrumlr.io
src/store/action/users.ts
/** This object lists board users object specific internal Redux Action types. */ import {UserClientModel, EditUserConfigurationRequest, UserServerModel, RaisedHandRequest} from "types/user"; /** This object lists board users object specific internal Redux Action types. */ export const UsersActionType = { /* * ATTENTION: * Don't forget the `as` casting for each field, because the type inference * won't work otherwise (e.g. in reducers). */ SetUsers: "@@SCRUMLR/setUsers" as const, SetUserStatus: "@@SCRUMLR/setUserStatus" as const, SetUserReadyStatus: "@@SCRUMLR/setUserReadyStatus" as const, SetRaisedHandStatus: "@@SCRUMLR/setRaisedHandStatus" as const, UpdateUser: "@@SCRUMLR/updateUser" as const, ChangePermission: "@@SCRUMLR/changePermission" as const, EditUserConfiguration: "@@SCRUMLR/editUserConfiguration" as const, }; /** Factory or creator class of internal Redux board users object specific actions. */ export const UsersActionFactory = { /* * ATTENTION: * Each action creator should be also listed in the type `UsersReduxAction`, because * the type inference won't work otherwise (e.g. in reducers). */ /** * Creates an action which should be dispatched when the server notifies about a changed list of users * for the current board. * * @param users the list of users * @param admin flag which indicates whether the list of users contains all admins or basic users */ setUsers: (users: UserClientModel[], admin: boolean) => ({ type: UsersActionType.SetUsers, users, admin, }), /** * Creates an action that should be dispatched when the server notifies about a changed status (online/offline) of * a user * * @param userId the user identifier * @param status flag which indicates whether the user is online or went offline */ setUserStatus: (userId: string, status: boolean) => ({ type: UsersActionType.SetUserStatus, userId, status, }), /** * Sets the ready status of a user by the given value. It will be applied immediately on the local * client and send to the server via the middleware and an API request. * * @param ready the ready state to set */ setUserReadyStatus: (ready: boolean) => ({ type: UsersActionType.SetUserReadyStatus, ready, }), /** * Sets the raised hand status of a user by the given value. It will be applied immediately on the local * client and send to the server via the middleware and an API request. * * @param configuration contains the user list and the raised hand status */ setRaisedHandStatus: (configuration: RaisedHandRequest) => ({ type: UsersActionType.SetRaisedHandStatus, configuration, }), /** * Creates an action that should be dispatched when the server notifies about a changed user configuration * * @param user the updated user */ updateUser: (user: UserServerModel) => ({ type: UsersActionType.UpdateUser, user, }), /** * Creates an action that should be dispatch when a moderator changes the permissions of a participant * * @param userId the identifier of the user whose permissions are being changed * @param moderator the flag whether the user receives or loses moderator permissions */ changePermission: (userId: string, moderator: boolean) => ({ type: UsersActionType.ChangePermission, userId, moderator, }), /** * Creates an action that should be dispatch when a user change configurations * * @param userConfigurationRequest contains configurations changed by user */ editUserConfiguration: (userConfigurationRequest: EditUserConfigurationRequest) => ({ type: UsersActionType.EditUserConfiguration, userConfigurationRequest, }), }; export type UsersReduxAction = | ReturnType<typeof UsersActionFactory.setUsers> | ReturnType<typeof UsersActionFactory.setUserStatus> | ReturnType<typeof UsersActionFactory.setUserReadyStatus> | ReturnType<typeof UsersActionFactory.setRaisedHandStatus> | ReturnType<typeof UsersActionFactory.changePermission> | ReturnType<typeof UsersActionFactory.editUserConfiguration> | ReturnType<typeof UsersActionFactory.updateUser>;
Accessible-Concepts/scrumlr.io
src/components/BoardHeader/index.ts
export * from "./BoardHeader";
Accessible-Concepts/scrumlr.io
src/types/joinRequest.ts
export type JoinRequestStatus = "pending" | "accepted" | "rejected"; export interface JoinRequestServerModel extends Parse.Object { objectId: string; board: Parse.Object; user: Parse.Object; status: JoinRequestStatus; updatedAt: Date; createdAt: Date; } export interface JoinRequestClientModel { id: string; userId: string; displayName: string; boardId: string; status: JoinRequestStatus; } export const mapJoinRequestServerToClientModel = (joinRequest: JoinRequestServerModel) => ({ id: joinRequest.id, userId: joinRequest.get("user").id, displayName: joinRequest.get("user").get("displayName"), boardId: joinRequest.get("board").id, status: joinRequest.get("status"), });
Accessible-Concepts/scrumlr.io
src/components/Votes/VoteButtons/index.ts
import {AddVoteButton as Add} from "./AddVoteButton"; import {RemoveVoteButton as Remove} from "./RemoveVoteButton"; export const VoteButtons = { Add, Remove, };