react#ReactChild TypeScript Examples

The following examples show how to use react#ReactChild. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestContext.tsx    From longwave with MIT License 6 votes vote down vote up
export function TestContext(props: {
  gameState: GameState;
  playerId: string;
  children: ReactChild;
  setState?: (newState: Partial<GameState>) => void;
}) {
  return (
    <GameModelContext.Provider
      value={BuildGameModel(
        props.gameState,
        props.setState || jest.fn(),
        props.playerId,
        () => ["left", "right"],
        () => {}
      )}
    >
      <Suspense fallback={<div>Loading...</div>}>
        <I18nextProvider i18n={i18n}>{props.children}</I18nextProvider>
      </Suspense>
    </GameModelContext.Provider>
  );
}
Example #2
Source File: flattenChildren.ts    From splitter with MIT License 6 votes vote down vote up
export default function flattenChildren(
  children: ReactNode,
  depth: number = 0,
  keys: (string | number)[] = []
): ReactChild[] {
  return Children.toArray(children).reduce(
    (acc: ReactChild[], node, nodeIndex) => {
      if (isFragment(node)) {
        acc.push.apply(
          acc,
          flattenChildren(
            node.props.children,
            depth + 1,
            keys.concat(node.key || nodeIndex)
          )
        );
      } else {
        if (isValidElement(node)) {
          acc.push(
            cloneElement(node, {
              key: keys.concat(String(node.key)).join('.')
            })
          );
        } else if (typeof node === 'string' || typeof node === 'number') {
          acc.push(node);
        }
      }
      return acc;
    },
    []
  );
}
Example #3
Source File: App.tsx    From CrewLink with GNU General Public License v3.0 6 votes vote down vote up
render(): ReactChild {
		if (this.state.error) {
			return (
				<div style={{ paddingTop: 16 }}>
					<Typography align="center" variant="h6" color="error">
						REACT ERROR
					</Typography>
					<Typography
						align="center"
						style={{
							whiteSpace: 'pre-wrap',
							fontSize: 12,
							maxHeight: 200,
							overflowY: 'auto',
						}}
					>
						{this.state.error.stack}
					</Typography>
					<SupportLink />
					<Button
						style={{ margin: '10px auto', display: 'block' }}
						variant="contained"
						color="secondary"
						onClick={() => window.location.reload()}
					>
						Reload App
					</Button>
				</div>
			);
		}

		return this.props.children;
	}
Example #4
Source File: Information.tsx    From phonepare with MIT License 6 votes vote down vote up
Information: FC<{ name: string, data: ReactChild, icon?: IconType }> = ({
  name, data, icon: Icon
}) => {
  return <Box textAlign='center' mx='auto' >
    {
      Icon && <Icon size={70} style={{ margin: 'auto' }} />
    }
    <Heading fontSize='xl' my={1}>{name}</Heading>
    <Text fontSize='lg'>{data}</Text>
  </Box>
}
Example #5
Source File: listurls.tsx    From Uptimo with MIT License 5 votes vote down vote up
ListUrls = ({ urls }: any) => {
  const { data, error } = useSWR(`http://localhost:3000/api/v1/urls`, fetcher);
  const [infoAlert, setInfoAlert]: any = useState({ nothing: true });

  const deleteUrl = async(url: string) => {
    const test = await hyttpo.request({
      method: 'DELETE',
      url: `${window.location.origin}/api/v1/delete`,
      body: JSON.stringify({
        url
      })
    }).catch(e => e);

    setInfoAlert({ message: `URL ${url} has been deleted!` })
  }

  return (
    <div>
        { !infoAlert.nothing ? <div className="notification is-primary is-light">
        { infoAlert.message }
        </div> : '' } 
      { data ? <>
        <table className="table">
          <thead>
            <tr>
              <th>URL</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            { data.message.map((url: boolean | ReactChild | ReactFragment | ReactPortal | null | undefined, index: number) => <>
              <tr key={`a${index}`}>
                <td key={`b${index}`}><a href={url as string} key={`d${index}`}>{url}</a></td>
                <td key={`c${index}`}>
                  <button className="button is-small is-danger is-light" onClick={() => deleteUrl(url as string)} key={`e${index}`}>DELETE</button>
                </td>
              </tr>
            </>) }
          </tbody>
        </table>
      </> : 'Loading...' }
    </div>
  )
}
Example #6
Source File: calendar.tsx    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
Calendar: React.FC<CalendarProps> = React.memo(
  ({
    dateSetup,
    locale,
    viewMode,
    rtl,
    width,
    height,
    columnWidth,
    horizontalRange,
    fontFamily,
    fontSize,
    highlightRange,
    displayWidth,
    scrollX,
    setScrollX,
    svgWidth,
    mousePos,
  }) => {
    const today = new Date();
    const getCalendarValuesForMonth = () => {
      const topValues: ReactChild[] = [];
      const bottomValues: ReactChild[] = [];
      const topDefaultHeight = height * 0.5;
      for (let i = 0; i < dateSetup.dates.length; i++) {
        const date = dateSetup.dates[i];
        const bottomValue = getLocaleMonth(date, locale);
        bottomValues.push(
          <text
            key={bottomValue + date.getFullYear()}
            y={height * 0.8}
            x={columnWidth * i + columnWidth * 0.5}
            className={'erda-gantt-calendar-bottom-text'}
          >
            {bottomValue}
          </text>,
        );
        if (i === 0 || date.getFullYear() !== dateSetup.dates[i - 1].getFullYear()) {
          const topValue = date.getFullYear().toString();
          let xText: number;
          if (rtl) {
            xText = (6 + i + date.getMonth() + 1) * columnWidth;
          } else {
            xText = (6 + i - date.getMonth()) * columnWidth;
          }
          topValues.push(
            <TopPartOfCalendar
              key={topValue}
              value={topValue}
              x1Line={columnWidth * i}
              y1Line={0}
              y2Line={topDefaultHeight}
              xText={xText}
              yText={topDefaultHeight * 0.9}
            />,
          );
        }
      }

      return [topValues, bottomValues];
    };

    const getCalendarValuesForWeek = () => {
      const topValues: ReactChild[] = [];
      const bottomValues: ReactChild[] = [];
      let weeksCount = 1;
      const topDefaultHeight = height * 0.5;
      const { dates } = dateSetup;
      for (let i = dates.length - 1; i >= 0; i--) {
        const date = dates[i];
        let topValue = '';
        if (i === 0 || date.getMonth() !== dates[i - 1].getMonth()) {
          // top
          topValue = `${getLocaleMonth(date, locale)}, ${date.getFullYear()}`;
        }
        // bottom
        const bottomValue = `W${getWeekNumberISO8601(date)}`;

        bottomValues.push(
          <text
            key={date.getTime()}
            y={height * 0.8}
            x={columnWidth * (i + +rtl)}
            className={'erda-gantt-calendar-bottom-text'}
          >
            {bottomValue}
          </text>,
        );

        if (topValue) {
          // if last day is new month
          if (i !== dates.length - 1) {
            topValues.push(
              <TopPartOfCalendar
                key={topValue}
                value={topValue}
                x1Line={columnWidth * i + weeksCount * columnWidth}
                y1Line={0}
                y2Line={topDefaultHeight}
                xText={columnWidth * i + columnWidth * weeksCount * 0.5}
                yText={topDefaultHeight * 0.9}
              />,
            );
          }
          weeksCount = 0;
        }
        weeksCount++;
      }
      return [topValues, bottomValues];
    };
    const reHighlightRange = {
      ...highlightRange,
      ...(highlightRange?.id && !highlightRange.start && !highlightRange.end ? { x1: -1, x2: -1 } : {}),
    };
    const HoverBar = ({ style }: { style: Obj }) =>
      highlightRange ? (
        <div
          className="absolute rounded bg-black-06"
          style={{
            width: Math.abs(reHighlightRange.x2 - reHighlightRange.x1),
            height: 40,
            left: min([reHighlightRange.x1, reHighlightRange.x2]),
            top: 26,
            ...style,
          }}
        />
      ) : null;

    const HoverTime = ({ style }: { style: Obj }) =>
      mousePos ? (
        <div
          className="absolute rounded bg-black-06"
          style={{
            width: columnWidth,
            height: 40,
            left: mousePos[0] * columnWidth,
            top: 26,
            ...style,
          }}
        />
      ) : null;

    const onChangeScrollX = (direction: number) => {
      const moveLen = Math.floor(displayWidth / columnWidth) - 4; // less then display count;
      const moveX = moveLen > 0 ? moveLen * columnWidth : columnWidth;
      if (direction === -1) {
        setScrollX((prevX) => (moveX >= prevX ? -1 : prevX - moveX));
      } else if (direction === 1) {
        setScrollX((prevX) => (moveX + prevX + displayWidth >= svgWidth ? svgWidth - displayWidth : prevX + moveX));
      }
    };

    const getCalendarValuesForDay = () => {
      let bottomValues: React.ReactNode = null;
      const dates = dateSetup.dates.slice(...horizontalRange);
      const dateInWeeks = [];
      // append date when screen have more space
      if (!dates.length) return null;
      let appendDateLength = Math.max(0, horizontalRange[1] - horizontalRange[0] - dates.length);
      while (appendDateLength-- > 0) {
        const lastDayInLastWeek = dates[dates.length - 1];
        dates.push(addToDate(lastDayInLastWeek, 1, 'day'));
      }
      const firstDay = dates[0];

      const firstDayInWeek = firstDay.getDay();
      // use Monday as first day of week

      const firstWeek = dates.splice(0, firstDayInWeek === 0 ? 1 : 7 - firstDayInWeek + 1);
      while (firstWeek.length < 7) {
        const firstDayInFirstWeek = firstWeek[0];
        firstWeek.unshift(addToDate(firstDayInFirstWeek, -1, 'day'));
      }
      dateInWeeks.push(firstWeek);
      while (dates.length) {
        dateInWeeks.push(dates.splice(0, 7));
      }
      const lastWeek = dateInWeeks[dateInWeeks.length - 1];
      while (lastWeek.length < 7) {
        const lastDayInLastWeek = lastWeek[lastWeek.length - 1];
        lastWeek.push(addToDate(lastDayInLastWeek, 1, 'day'));
      }

      const offsetX = (firstDayInWeek ? firstDayInWeek - 1 : 6) * columnWidth;
      bottomValues = (
        <div
          className="flex h-full w-full erda-gantt-calendar-header-container"
          style={{ transform: `translateX(${-offsetX}px)` }}
        >
          {<HoverBar style={{ transform: `translateX(${offsetX}px)` }} />}
          {<HoverTime style={{ transform: `translateX(${offsetX}px)` }} />}
          {flatten(dateInWeeks).map((day, idx) => {
            const mark =
              reHighlightRange?.x1 === columnWidth * idx - offsetX ||
              reHighlightRange?.x2 === columnWidth * (idx + 1) - offsetX;
            const cls = `${
              mark
                ? 'calendar-highlight-text'
                : `${[0, 6].includes(day.getDay()) ? 'calendar-disabled-text' : 'calendar-normal-text'}`
            }`;
            const isStartPos = columnWidth * idx - offsetX === 0;
            const isToday = moment(day).isSame(today, 'day');
            return (
              <div
                key={day.getTime()}
                style={{
                  width: columnWidth,
                  height: 40,
                  top: 28,
                  left: columnWidth * idx,
                }}
                className={`absolute flex flex-col items-center text-xs justify-center ${cls} ${
                  isToday ? 'text-red' : ''
                }`}
              >
                <span>{Days[day.getDay()]}</span>
                <span>{day.getDate()}</span>
                {isStartPos || day.getDate() === 1 ? (
                  <div className="absolute text-default-8 font-medium " style={{ top: -16 }}>
                    {Months[day.getMonth()]}
                  </div>
                ) : null}
                {isToday ? (
                  <div
                    style={{ left: (columnWidth + 22) / 2, bottom: -14 }}
                    className="absolute erda-gantt-calendar-today flex justify-center"
                  >
                    <div>{i18n.t('dop:Today')}</div>
                  </div>
                ) : null}
              </div>
            );
          })}
          {scrollX > 0 ? (
            <div
              className="flex items-center erda-gantt-calendar-arrow-left"
              onClick={() => onChangeScrollX(-1)}
              style={{ left: offsetX }}
            >
              <ErdaIcon type="zuofan" className="ml-1" size={10} />
            </div>
          ) : null}
          {displayWidth + scrollX < svgWidth ? (
            <div
              className="flex items-center erda-gantt-calendar-arrow-right"
              onClick={() => onChangeScrollX(1)}
              style={{ left: offsetX + displayWidth - 16 }}
            >
              <ErdaIcon type="youfan" className="ml-1" size={10} />
            </div>
          ) : null}
        </div>
      );
      return bottomValues;
    };

    const getCalendarValuesForOther = () => {
      const topValues: ReactChild[] = [];
      const bottomValues: ReactChild[] = [];
      const ticks = viewMode === ViewMode.HalfDay ? 2 : 4;
      const topDefaultHeight = height * 0.5;
      const { dates } = dateSetup;
      for (let i = 0; i < dates.length; i++) {
        const date = dates[i];
        const bottomValue = getCachedDateTimeFormat(locale, {
          hour: 'numeric',
        }).format(date);

        bottomValues.push(
          <text
            key={date.getTime()}
            y={height * 0.8}
            x={columnWidth * (i + +rtl)}
            className={'erda-gantt-calendar-bottom-text'}
            fontFamily={fontFamily}
          >
            {bottomValue}
          </text>,
        );
        if (i === 0 || date.getDate() !== dates[i - 1].getDate()) {
          const topValue = `${date.getDate()} ${getLocaleMonth(date, locale)}`;
          topValues.push(
            <TopPartOfCalendar
              key={topValue + date.getFullYear()}
              value={topValue}
              x1Line={columnWidth * i + ticks * columnWidth}
              y1Line={0}
              y2Line={topDefaultHeight}
              xText={columnWidth * i + ticks * columnWidth * 0.5}
              yText={topDefaultHeight * 0.9}
            />,
          );
        }
      }

      return [topValues, bottomValues];
    };

    // let topValues: ReactChild[] = [];
    // let bottomValues: ReactChild[] = [];
    // switch (dateSetup.viewMode) {
    //   // case ViewMode.Month:
    //   //   [topValues, bottomValues] = getCalendarValuesForMonth();
    //   //   break;
    //   // case ViewMode.Week:
    //   //   [topValues, bottomValues] = getCalendarValuesForWeek();
    //   //   break;
    //   case ViewMode.Day:
    //     [topValues, bottomValues] = getCalendarValuesForDay();
    //     break;
    //   default:
    //     [topValues, bottomValues] = getCalendarValuesForOther();
    //     break;
    // }
    const finalWidth = max([columnWidth * dateSetup.dates.length, width]);

    return (
      <svg
        xmlns="http://www.w3.org/2000/svg"
        className="overflow-visible"
        width={width}
        height={height}
        fontFamily={fontFamily}
      >
        <g className="erda-gantt-calendar" fontSize={fontSize}>
          <rect x={0} y={0} width={finalWidth} height={height} className={'erda-gantt-calendar-header'} />
          <foreignObject
            x={0}
            y={0}
            width={finalWidth}
            height={height}
            className={'erda-gantt-calendar-header overflow-visible'}
          >
            {getCalendarValuesForDay()}
          </foreignObject>
          {/* {topValues} */}
        </g>
      </svg>
    );
  },
)
Example #7
Source File: grid-body.tsx    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
GridBody: React.FC<GridBodyProps> = ({
  tasks: originTasks,
  dates,
  barTasks: tasks,
  rowHeight,
  svgWidth,
  columnWidth,
  todayColor,
  selectedTask,
  ganttHeight,
  setSelectedTask,
  rtl,
  onDateChange,
  ganttEvent,
  setRangeAddTime,
  horizontalRange,
  displayWidth,
  onMouseMove: propsOnMouseMove,
  mouseUnFocus: propsMouseUnFocus,
  mousePos,
}) => {
  let y = 0;
  const gridRows: ReactChild[] = [];
  const today = new Date();
  const dateDelta =
    dates[1].getTime() -
    dates[0].getTime() -
    dates[1].getTimezoneOffset() * 60 * 1000 +
    dates[0].getTimezoneOffset() * 60 * 1000;

  const [startPos, setStartPos] = React.useState<null | number[]>(null);
  const [endPos, setEndPos] = React.useState<null | number[]>(null);
  const [chosenTask, setChosenTask] = React.useState<Obj | null>(null);

  React.useEffect(() => {
    if (startPos && endPos) {
      setRangeAddTime({ x1: startPos[0], x2: endPos[0] });
    } else {
      setRangeAddTime(null);
    }
  }, [startPos, endPos]);

  const onMouseDown = (e: React.MouseEvent) => {
    const gridPos = e.currentTarget.getBoundingClientRect();
    const clickY = e.clientY - gridPos.y;
    const clickPos = Math.floor(clickY / rowHeight);
    const curTask = tasks[clickPos];

    if (!curTask.start || !curTask.end) {
      setSelectedTask(curTask.id);
      setChosenTask(curTask);

      setStartPos([
        Math.floor((e.clientX - gridPos.x) / columnWidth) * columnWidth,
        clickPos * rowHeight + 8,
        e.clientX - gridPos.x,
      ]);
    }
  };
  const mouseUnFocus = () => {
    propsMouseUnFocus();
    setStartPos(null);
    setEndPos(null);
    setChosenTask(null);
  };
  const curDates = dates.slice(...horizontalRange);
  const todayIndex = findIndex(curDates, (item) => moment(item).isSame(today, 'day'));
  const addTime = getDateFormX(startPos?.[0], endPos?.[0], dateDelta, columnWidth, curDates[0]?.getTime());

  const onMouseUp = () => {
    if (addTime.length && addTime[1] - addTime[0] >= dateDelta * 0.6 && chosenTask) {
      onDateChange({ ...chosenTask, start: new Date(addTime[0]), end: new Date(addTime[1]) });
    }
    mouseUnFocus();
  };
  const onMouseMove = (e: React.MouseEvent) => {
    const gridPos = e.currentTarget.getBoundingClientRect();
    propsOnMouseMove(e);
    const curEndPod = e.clientX - gridPos.x;

    if (startPos) {
      setEndPos(
        curEndPod - startPos[2] > 10
          ? [
              (Math.floor((e.clientX - gridPos.x + 1) / columnWidth) + 1) * columnWidth,
              startPos[1] + rowHeight - 16,
              curEndPod,
            ]
          : null,
      );
    }
  };

  tasks?.forEach((task: Task, idx: number) => {
    const validTask = task.start && task.end;
    let PointIcon = null;
    if (validTask) {
      const displayPos = Math.floor(displayWidth / columnWidth);
      if (curDates?.[0] && task.end < curDates[0]) {
        PointIcon = (
          <div className="text-default-2 hover:text-default-4 erda-gantt-grid-arrow-box flex items-center">
            <ErdaIcon className="cursor-pointer " type="zuo" size={20} onClick={() => setSelectedTask(task.id)} />
            <div className="erda-gantt-grid-arrow text-default-6">
              {moment(task.start).format('MM-DD')} ~ {moment(task.end).format('MM-DD')}
            </div>
          </div>
        );
      } else if (curDates?.[displayPos] && task.start > curDates[displayPos]) {
        PointIcon = (
          <div
            className="text-default-2 hover:text-default-4 erda-gantt-grid-arrow-box flex items-center"
            style={{ marginLeft: displayWidth - 20 - 80 }}
          >
            <div className="erda-gantt-grid-arrow text-default-6">
              {moment(task.start).format('MM-DD')} ~ {moment(task.end).format('MM-DD')}
            </div>
            <ErdaIcon className="cursor-pointer" onClick={() => setSelectedTask(task.id)} type="you" size={20} />
          </div>
        );
      }
    }
    gridRows.push(
      <foreignObject key={`Row${task.id}`} x="0" y={y} width={svgWidth} height={rowHeight}>
        <div
          className={`flex erda-gantt-grid-row h-full ${
            selectedTask?.id === task.id ? 'erda-gantt-grid-row-selected' : ''
          } ${!validTask ? 'on-add' : ''} ${mousePos?.[1] === idx ? 'on-hover' : ''}`}
        />
      </foreignObject>,
    );
    y += rowHeight;
  });

  const { changedTask } = ganttEvent || {};
  const realHeight = tasks.length * rowHeight;

  const getAddRangePos = () => {
    if (startPos && endPos) {
      return {
        transform: `translate(${min([startPos[0], endPos[0]])},${min([startPos[1], endPos[1]])})`,
        width: Math.abs(startPos[0] - endPos[0]),
        height: Math.abs(startPos[1] - endPos[1]),
      };
    }
    return null;
  };

  const getRangePos = () => {
    if (changedTask) {
      return {
        transform: `translate(${changedTask.x1},0)`,
        width: changedTask.x2 - changedTask.x1,
        height: max([ganttHeight, realHeight]),
      };
    } else if (startPos && endPos) {
      return {
        transform: `translate(${min([startPos[0], endPos[0]])},0)`,
        width: Math.abs(endPos[0] - startPos[0]),
        height: max([ganttHeight, realHeight]),
      };
    }
    return null;
  };

  const getMouseBlockPos = () => {
    if (mousePos) {
      const curTask = tasks[mousePos[1]];
      if (curTask && !curTask.start && !curTask.end) {
        return {
          width: columnWidth,
          height: rowHeight - 16,
          transform: `translate(${mousePos[0] * columnWidth},${mousePos[1] * rowHeight + 8})`,
        };
      }
    }
    return null;
  };

  const getMouseHoverPos = () => {
    if (mousePos) {
      return {
        width: 8,
        height: max([ganttHeight, realHeight]),
        transform: `translate(${mousePos[0] * columnWidth + columnWidth / 2 - 4},0)`,
      };
    }
    return null;
  };

  const rangePos = getRangePos();
  const mouseBlockPos = getMouseBlockPos();
  const addRangePos = getAddRangePos();
  const mouseHoverPos = getMouseHoverPos();
  const todayStartPos = todayIndex * columnWidth + columnWidth / 2 - 1;
  return (
    <g
      className="gridBody"
      onMouseDown={onMouseDown}
      onMouseUp={() => {
        onMouseUp();
      }}
      onMouseMove={onMouseMove}
      onMouseLeave={mouseUnFocus}
    >
      {rangePos ? (
        <rect {...rangePos} className="erda-gantt-grid-changed-range" />
      ) : mouseHoverPos ? (
        <foreignObject {...mouseHoverPos}>
          <div className="h-full w-full erda-gantt-grid-hover-box">
            <div className="erda-gantt-grid-hover-arrow" />
            <div className="erda-gantt-grid-hover-range h-full w-full" />
          </div>
        </foreignObject>
      ) : null}

      <g className="rows">{gridRows}</g>
      {addRangePos ? (
        <g>
          <foreignObject {...addRangePos}>
            <div className="erda-gantt-grid-add-rect text-sm text-desc  bg-white bg-opacity-100 w-full h-full">{`${moment(
              addTime[0],
            ).format('MM-DD')}~${moment(addTime[1]).format('MM-DD')}`}</div>
          </foreignObject>
        </g>
      ) : mouseBlockPos ? (
        <g>
          <foreignObject {...mouseBlockPos}>
            <div className="erda-gantt-grid-add-rect bg-white bg-opacity-100 w-full h-full" />
          </foreignObject>
        </g>
      ) : null}
      {todayIndex > -1 ? (
        <polyline
          points={`${todayStartPos + columnWidth / 2},4 ${todayStartPos + columnWidth / 2},${max([
            ganttHeight,
            realHeight,
          ])}`}
          className="erda-gantt-grid-today"
        />
      ) : null}
    </g>
  );
}