office-ui-fabric-react#Link TypeScript Examples

The following examples show how to use office-ui-fabric-react#Link. 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: Header.tsx    From website with MIT License 6 votes vote down vote up
Header = () => {
    var theme = useTheme();
    const logoProperties = { width: 25, height: 25, marginTop: '5px', marginBottom: '5px' };
    const logoFileName = 'unimi150.png';
    const titleStyle: ITextStyles = { root: { fontSize: FontSizes.size20, fontWeight: FontWeights.semibold, color: theme.palette.themePrimary } };
    
    return (
        <header style={{ borderBottom: '1px solid', borderColor: theme.palette.neutralLight, marginBottom: -1 }}>

            <div>
                <Row className="headerRow">
                    <Col style={{ maxWidth: 250, paddingLeft: 0, paddingRight: 0, display: 'flex', alignItems: 'center' }}>
                        <div style={{ width: 250, marginTop: 5 }}>
                            <Link href="http://studentiunimi.it/">
                                <Image id="logo"
                                    src={process.env.PUBLIC_URL + '/logo/' + logoFileName}
                                    alt='Network logo'
                                    style={logoProperties}
                                    className="mr-2 mt-2 mb-1 d-inline"
                                />
                            </Link>

                            <div className="d-inline mt-2"><Link href="http://studentiunimi.it/" className="text-decoration-none"><Text styles={titleStyle}>Network StudentiUniMi</Text></Link></div>
                        </div>
                    </Col>

                    <Col style={{ paddingLeft: 0, paddingRight: 0, width: "55%" }} className="header-col">
                        <HeaderMenu/>
                    </Col>

                </Row>
            </div>
        
        </header>
    )
}
Example #2
Source File: RepresentativesList.tsx    From website with MIT License 6 votes vote down vote up
RapresentativesList = (props: Props) => {
    var theme = useTheme();
    const locale = LocalizationService.strings();

    return (
        <div className="representatives pb-4 pt-2">
            {
                props.loadingRepresentatives || props.errorLoadingRepresentatives ? <LoadingSpinner loading={props.loadingRepresentatives} error={props.errorLoadingRepresentatives} />
                : props.data.length === 0 ?
                    <div className="justify-content-center">
                        <Message text={locale?.university.representativesNotAvailable!} />
                    </div> : <></>
            }
            
            <Row className="people-list text-center">
                {props.data.length !== 0 && !props.errorLoadingRepresentatives && !props.loadingRepresentatives ? props.data.map((x,i) => 
                    <Col key={i} xl={3} lg={3} md={4} sm={6} xs={12} className="mb-3 col-persona">
                        {
                            ( () => { 
                                var primaryText : any; 
                                var imageUrl = `https://studentiunimi-groups-propics.marcoaceti.workers.dev/${x.tguser?.id}.png`;
                                if (x.tguser?.username !== "") primaryText = (<><Icon iconName="Send" style={{ color: theme.palette.themePrimary }} />&nbsp;<Link href={`https://t.me/${x.tguser?.username}`}>{`${x.tguser?.first_name ?? ""} ${x.tguser?.last_name ?? ""}`}</Link></>); 
                                else { primaryText = `${x.tguser?.first_name ?? ""} ${x.tguser?.last_name ?? ""}`};
                                return <Persona imageUrl={imageUrl} onRenderPrimaryText={() => primaryText} text={`${x.tguser?.first_name ?? ""} ${x.tguser?.last_name ?? ""}`} secondaryText={x.degree_name} size={PersonaSize.size40} /> 
                            })()
                        }
                    </Col>
                ) : <></> }
            </Row>
        </div>
    )
}
Example #3
Source File: SpfxFluentuiMessagebar.tsx    From SPFx with Mozilla Public License 2.0 6 votes vote down vote up
WarningLongMessage = () => (
  <MessageBar
    dismissButtonAriaLabel="Close"
    messageBarType={MessageBarType.warning}
    actions={
      <div>
        <MessageBarButton>Yes</MessageBarButton>
        <MessageBarButton>No</MessageBarButton>
      </div>
    }
  >
    <b>Warning defaults to multiline</b>. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi luctus, purus a
    lobortis tristique, odio augue pharetra metus, ac placerat nunc mi nec dui. Vestibulum aliquam et nunc semper
    scelerisque. Curabitur vitae orci nec quam condimentum porttitor et sed lacus. Vivamus ac efficitur leo. Cras
    faucibus mauris libero, ac placerat erat euismod et. Donec pulvinar commodo odio sit amet faucibus. In hac habitasse
    platea dictumst. Duis eu ante commodo, condimentum nibh pellentesque, laoreet enim. Fusce massa lorem, ultrices eu
    mi a, fermentum suscipit magna. Integer porta purus pulvinar, hendrerit felis eget, condimentum mauris.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
)
Example #4
Source File: SpfxFluentuiMessagebar.tsx    From SPFx with Mozilla Public License 2.0 6 votes vote down vote up
WarningQuestion = () => (
  <MessageBar
    messageBarType={MessageBarType.warning}
    isMultiline={false}
    dismissButtonAriaLabel="Close"
    actions={
      <div>
        <MessageBarButton onClick={() => console.log('Action clicked')}>Action</MessageBarButton>
      </div>
    }
  >
    Warning MessageBar content.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
)
Example #5
Source File: ErrorMessageBar.tsx    From hypertrons-crx with Apache License 2.0 6 votes vote down vote up
ErrorMessageBar: React.FC<ErrorMessageBarProps> = ({
  errorCode = ErrorCode.UNKNOWN,
  url = HYPERTRONS_CRX_NEW_ISSUE,
}) => {
  const [inited, setInited] = useState(false);
  const [settings, setSettings] = useState(new Settings());

  useEffect(() => {
    const initSettings = async () => {
      const temp = await loadSettings();
      setSettings(temp);
      setInited(true);
    };
    if (!inited) {
      initSettings();
    }
  }, [inited, settings]);

  return (
    <Stack>
      <Stack.Item align="center">
        <MessageBar
          messageBarType={MessageBarType.error}
          isMultiline={false}
          dismissButtonAriaLabel="Close"
        >
          {getMessageByLocale('global_error_message', settings.locale)}
          {errorCode}.
          <Link href={url} target="_blank" underline>
            {getMessageByLocale('global_clickToshow', settings.locale)} Issue.
          </Link>
        </MessageBar>
      </Stack.Item>
    </Stack>
  );
}
Example #6
Source File: SpfxFluentuiMessagebar.tsx    From SPFx with Mozilla Public License 2.0 6 votes vote down vote up
SuccessQuestion = () => (
  <MessageBar
    actions={
      <div>
        <MessageBarButton onClick={() => console.log('Yes clicked')}>Yes</MessageBarButton>
        <MessageBarButton onClick={() => console.log('No clicked')}>No</MessageBarButton>
      </div>
    }
    messageBarType={MessageBarType.success}
    isMultiline={false}
  >
    Success MessageBar with single line and action buttons.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
)
Example #7
Source File: SpfxFluentuiMessagebar.tsx    From SPFx with Mozilla Public License 2.0 6 votes vote down vote up
WarningMessage = () => (
  <MessageBar
    messageBarType={MessageBarType.severeWarning}
    actions={
      <div>
        <MessageBarButton onClick={() => console.log('Yes clicked')}>Yes</MessageBarButton>
        <MessageBarButton onClick={() => console.log('No clicked')}>No</MessageBarButton>
      </div>
    }
  >
    SevereWarning MessageBar with action buttons which defaults to multiline.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
)
Example #8
Source File: index.tsx    From azure-serverless-workshop with MIT License 6 votes vote down vote up
public render(): JSX.Element {
    return (
        <div>
          {auth.isLoggedIn() ? (
            <>
              <DroneStatusDetailsList />
            </>
          ): (
            <>
              You should <Link onClick={e => {
              e.preventDefault()
              auth.login()
              }}>Sign in</Link> to see restricted
              content!
            </>
          )}
        </div>
    );
  }
Example #9
Source File: SpfxFluentuiMessagebar.tsx    From SPFx with Mozilla Public License 2.0 6 votes vote down vote up
ErrorMessage = () => (
  <MessageBar
    messageBarType={MessageBarType.error}
    isMultiline={false}
    dismissButtonAriaLabel="Close"
  >
    Error MessageBar with single line, with dismiss button.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
)
Example #10
Source File: RecordDetails.tsx    From NetworkViewPCF with MIT License 5 votes vote down vote up
render() {
    const { node, link } = this.props;
    return (
      <>
        {node && (
          <Stack styles={{ root: { padding: 10 } }}>
            <Stack.Item>{node.settings.displayName}</Stack.Item>
            <Stack.Item>
              <Stack horizontal verticalAlign="center">
                <Stack.Item>
                  <Link onClick={this.openRecord}>{node.name}</Link>
                </Stack.Item>
                <IconButton iconProps={{ iconName: "OpenInNewWindow" }} onClick={this.openRecord}></IconButton>
              </Stack>
            </Stack.Item>
          </Stack>
        )}
        {link && (
          <Stack styles={{ root: { padding: 10 } }}>
            <Stack horizontal tokens={{ childrenGap: 8 }} verticalAlign="center">
              <Stack.Item>{(link.source as RecordNode).settings.displayName}</Stack.Item>
              <Stack.Item>
                <Icon iconName="NavigateBackMirrored"></Icon>
              </Stack.Item>
              <Stack.Item>{(link.target as RecordNode).settings.displayName}</Stack.Item>
            </Stack>
            {link.intersect && (
              <>
                <Stack.Item>{link.intersect.settings.displayName}</Stack.Item>
                <Stack.Item>
                  {link.intersect.data?.formattedValues && link.intersect.data.formattedValues["_record1roleid_value"]}{" "}
                  {link.intersect.data?.formattedValues && link.intersect.data.formattedValues["_record2roleid_value"]}
                </Stack.Item>
              </>
            )}
          </Stack>
        )}
      </>
    );
  }
Example #11
Source File: Mantainers.tsx    From website with MIT License 5 votes vote down vote up
Mantainers = () => {
    var theme = useTheme();
    const locale = LocalizationService.strings();
    var language: string | undefined = LocalizationService.getLanguage();
    const profileIconStyle = { color: theme.palette.themePrimary, fontSize: FontSizes.size24 };

    const sectionCard = {
        minHeight: '120px',
        height: '100%',
        width: '100%',
        maxWidth: 'none',
        marginLeft: 'auto',
        marginRight: 'auto',
        maxHeight: 'none',
        backgroundColor: theme.palette.white
    };

    return (
        <div className="pb-4 pt-4" style={{ backgroundColor: theme.palette.neutralLighter }}>
            <Container className="contributors text-center">
                <div className="mb-4"><Text variant="xLarge">{locale?.contributors.header1}</Text></div>

                <Row className="justify-content-center">
                    {
                        developers.map((x: any, i: any) => {
                            return (
                                <Col className="mb-3" xl={4} lg={4} md={4} sm={6} xs={12} key={i}>
                                    <Card tokens={cardTokens} style={sectionCard} className="justify-content-center text-center">
                                        <Card.Section>
                                            <div className="justify-content-center">
                                                <Image id="logo"
                                                    src={process.env.PUBLIC_URL + "/contributors/" + x.pic}
                                                    alt={x.name}
                                                    style={developerPic}
                                                />
                                            </div>
                                            <div className="mb-0"><Text variant="medium" styles={semibold}>{x.name}</Text></div>
                                            <Text variant="medium" className="mt-2">
                                                {x.description[language!]}
                                            </Text>
                                            <div>
                                                <TooltipHost
                                                    content={locale?.contributors.githubProfile}
                                                    calloutProps={calloutProps}
                                                    styles={hostStyles}
                                                    delay={TooltipDelay.zero}
                                                >
                                                    <Link onClick={() => redirectToLink(x.github)}><Icon iconName="ProfileSearch" style={profileIconStyle} /></Link>
                                                </TooltipHost>
                                                &nbsp;&nbsp;
                                                <TooltipHost
                                                    content={locale?.contributors.websiteProfile}
                                                    calloutProps={calloutProps}
                                                    styles={hostStyles}
                                                    delay={TooltipDelay.zero}
                                                >
                                                    <Link onClick={() => redirectToLink(x.website)}><Icon iconName="Website" style={profileIconStyle} /></Link>
                                                </TooltipHost>
                                            </div>
                                        </Card.Section>
                                    </Card>
                                </Col>
                            )
                        })
                    }
                </Row>
            </Container>
        </div>
    )
}
Example #12
Source File: AdminsList.tsx    From website with MIT License 5 votes vote down vote up
AdminsList = (props: Props) => {
    var theme = useTheme();
    const locale = LocalizationService.strings();
    let [admins, setAdmins] = React.useState<Admin[]>([]); // Amministratori
    const [loadingAdmins, setLoadingAdmins] = React.useState<boolean>(false);
    const [errorLoadingAdmins, setErrorLoadingAdmins] = React.useState<boolean>(false);

    /* Admins callBack */
    const updateAdmins = React.useCallback(async () => {
        if (props.degree?.slug === '' || props.degree?.slug === undefined) return;
        setErrorLoadingAdmins(false);
        setLoadingAdmins(true);
        let adminsResult = await getDegreeAdmins(props.degree?.slug);

        if (adminsResult.status !== 200) {
            setLoadingAdmins(false);
            setErrorLoadingAdmins(true);
            return;
        }

        setLoadingAdmins(false);
        setAdmins(adminsResult.value ?? []);
    }, [props.degree?.slug]);


    React.useEffect(() => {
        updateAdmins();
    }, [props.degree, updateAdmins]);

    return (
        <div className="mb-2">
            <div className="pb-2 pt-2 mb-4" style={{ backgroundColor: theme.palette.neutralLight }}>
                <Container>
                    <div><Text variant="medium" styles={semibold}><Icon iconName="WorkforceManagement" /> {locale?.groups.availableAdmins}</Text></div>
                </Container>
            </div>

            {
                loadingAdmins || errorLoadingAdmins ? <LoadingSpinner loading={loadingAdmins} error={errorLoadingAdmins} />
                    : admins.length === 0 ?
                        <div className="justify-content-center">
                            <Message text={locale?.groups.adminsNotFound!} />
                        </div> : <></>
            }

            {admins.length !== 0 && !errorLoadingAdmins && !loadingAdmins ?
                <Container>
                    <Row className="admin-list" style={{ justifyContent: admins?.length === 0 ? 'center' : ""}}>
                        {admins?.length !== 0 ? admins?.map((x,i) =>
                            <Col key={i} xl={3} lg={3} md={4} sm={6} xs={12} className="mb-3 col-persona">
                                {(() => {
                                    var imageUrl = `https://studentiunimi-groups-propics.marcoaceti.workers.dev/${x.id}.png`;
                                    return <Persona imageUrl={imageUrl} onRenderPrimaryText={() => (<><Icon iconName="Send" style={{ color: theme.palette.themePrimary }}/>&nbsp;<Link href={`https://t.me/${x.username}`}>{`${x.first_name ?? ""} ${x.last_name ?? ""}`}</Link></>)} text={`@${x.first_name ?? ""} ${x.last_name ?? ""}`} secondaryText={`@${x.username}`} size={PersonaSize.size40} />
                                })()}
                            </Col>
                        ) : <Message text={locale?.groups.adminsNotFound!} />
                        }
                    </Row>
                </Container> : <></>
            }
        </div>
    )
}
Example #13
Source File: ErrorPage.tsx    From hypertrons-crx with Apache License 2.0 5 votes vote down vote up
ErrorPage: React.FC<ErrorPageProps> = ({ errorCode }) => {
  const [inited, setInited] = useState(false);
  const [settings, setSettings] = useState(new Settings());

  useEffect(() => {
    const initSettings = async () => {
      const temp = await loadSettings();
      setSettings(temp);
      setInited(true);
    };
    if (!inited) {
      initSettings();
    }
  }, [inited, settings]);

  const errMessageObj = getMessageByLocale(
    `global_error_message_${errorCode}`,
    settings.locale
  );

  const onButtonClick = () => {
    history.go(-1);
  };

  return (
    <Stack
      tokens={stackTokens}
      style={{
        width: '250px',
        margin: 'auto',
      }}
    >
      <Stack.Item>
        <FontIcon iconName="PageRemove" style={{ fontSize: 30 }} />
      </Stack.Item>
      <Stack.Item>
        <h3>{errMessageObj.status}</h3>
      </Stack.Item>
      <Stack.Item>
        <strong>{errMessageObj.measure.text}</strong>
        <ul style={{ margin: '15px 0 0 15px' }}>
          {errMessageObj.measure.tips.map((tip: string) => {
            return <li>{tip}</li>;
          })}
        </ul>
      </Stack.Item>
      <Stack.Item>
        <Link href={HYPERTRONS_CRX_NEW_ISSUE} target="_blank" underline>
          {getMessageByLocale('global_sendFeedback', settings.locale)}
        </Link>
      </Stack.Item>
      <Stack.Item>
        <DefaultButton
          text={getMessageByLocale('global_btn_goBack', settings.locale)}
          iconProps={navigateBackIcon}
          onClick={onButtonClick}
        />
      </Stack.Item>
    </Stack>
  );
}
Example #14
Source File: SpfxFluentuiMessagebar.tsx    From SPFx with Mozilla Public License 2.0 5 votes vote down vote up
InfoMessage = () => (
  <MessageBar>
    Info/Default MessageBar.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
)
Example #15
Source File: Graph.tsx    From hypertrons-crx with Apache License 2.0 4 votes vote down vote up
Graph: React.FC<GraphProps> = ({
  data,
  graphType = 'echarts',
  style = {},
  onNodeClick = (node: INode) => {
    const url = 'https://github.com/' + node.id;
    window.location.href = url;
  },
  focusedNodeID,
}) => {
  const NODE_SIZE = [10, 30];
  const NODE_COLOR =
    githubTheme === 'light'
      ? ['#9EB9A8', '#40C463', '#30A14E', '#216E39']
      : ['#0E4429', '#006D32', '#26A641', '#39D353'];
  const THRESHOLD = [10, 100, 1000];
  const FOCUSED_NODE_COLOR = githubTheme === 'light' ? '#D73A49' : '#DA3633';

  const [inited, setInited] = useState(false);
  const [settings, setSettings] = useState(new Settings());

  useEffect(() => {
    const initSettings = async () => {
      const temp = await loadSettings();
      setSettings(temp);
      setInited(true);
    };
    if (!inited) {
      initSettings();
    }
  }, [inited, settings]);

  const getColorMap = (value: number): string => {
    const length = Math.min(THRESHOLD.length, NODE_COLOR.length - 1);
    let i = 0;
    for (; i < length; i++) {
      if (value < THRESHOLD[i]) {
        return NODE_COLOR[i];
      }
    }
    return NODE_COLOR[i];
  };
  const generateEchartsData = (data: any): any => {
    const generateNodes = (nodes: any[]): any => {
      const minMax = getMinMax(nodes);
      return nodes.map((n: any) => {
        const imageURL =
          `image://https://avatars.githubusercontent.com/` + n.name;
        /* 
        Not to replace node color with profile picture in project correlation network
        checking weather nodes denotes repository
      */
        if (n.name.includes('/')) {
          return {
            id: n.name,
            name: n.name,
            value: n.value,
            symbolSize: linearMap(n.value, minMax, NODE_SIZE),
            itemStyle: {
              color:
                focusedNodeID && focusedNodeID === n.name
                  ? FOCUSED_NODE_COLOR
                  : getColorMap(n.value),
            },
          };
        } else {
          /* 
        nodes doesnot denote repositories
      */
          return {
            id: n.name,
            name: n.name,
            value: n.value,
            symbolSize: linearMap(n.value, minMax, NODE_SIZE),
            symbol: imageURL,
          };
        }
      });
    };
    const generateEdges = (edges: any[]): any => {
      return edges.map((e: any) => {
        return {
          source: e.source,
          target: e.target,
          value: e.weight,
        };
      });
    };
    return {
      nodes: generateNodes(data.nodes),
      edges: generateEdges(data.edges),
    };
  };

  const generateGraphinData = (data: any): any => {
    const generateNodes = (nodes: any[]): any => {
      const minMax = getMinMax(nodes);
      return nodes.map((n: any) => {
        const color =
          focusedNodeID && focusedNodeID === n.name
            ? FOCUSED_NODE_COLOR
            : getColorMap(n.value);
        return {
          id: n.name,
          value: n.value,
          style: {
            keyshape: {
              size: linearMap(n.value, minMax, NODE_SIZE),
              stroke: color,
              fill: color,
              fillOpacity: 1,
            },
          },
        };
      });
    };
    const generateEdges = (edges: any[]): any => {
      return edges.map((e: any) => {
        return {
          source: e.source,
          target: e.target,
          value: e.weight,
          style: {
            keyshape: {
              type: 'poly',
              poly: {
                distance: 40,
              },
            },
          },
        };
      });
    };
    return {
      nodes: generateNodes(data.nodes),
      edges: generateEdges(data.edges),
    };
  };

  let graphData: any;
  let graphOption: any;
  switch (graphType) {
    case 'echarts':
      graphData = generateEchartsData(data);
      graphOption = {
        tooltip: {},
        animation: true,
        animationDuration: 2000,
        series: [
          {
            type: 'graph',
            layout: 'force',
            nodes: graphData.nodes,
            edges: graphData.edges,
            // Enable mouse zooming and translating
            roam: true,
            label: {
              position: 'right',
            },
            force: {
              repulsion: 50,
              edgeLength: [1, 100],
              // Disable the iteration animation of layout
              layoutAnimation: false,
            },
            lineStyle: {
              curveness: 0.3,
              opacity: 0.7,
            },
            emphasis: {
              focus: 'adjacency',
              label: {
                position: 'right',
                show: true,
              },
            },
          },
        ],
      };
      break;
    case 'antv':
      graphData = generateGraphinData(data);
      break;
    default:
      break;
  }

  const colorCellsExample1 = [
    { id: 'L0', label: `< ${THRESHOLD[0]}`, color: NODE_COLOR[0] },
    {
      id: 'L1',
      label: `${THRESHOLD[0]} - ${THRESHOLD[1]}`,
      color: NODE_COLOR[1],
    },
    {
      id: 'L2',
      label: `${THRESHOLD[1]} - ${THRESHOLD[2]}`,
      color: NODE_COLOR[2],
    },
    { id: 'L3', label: `> ${THRESHOLD[2]}`, color: NODE_COLOR[3] },
  ];

  if (isNull(data)) {
    return <div />;
  }
  return (
    <Stack>
      <Stack className="hypertrons-crx-border">
        {graphType === 'echarts' && (
          <EChartsWrapper
            option={graphOption}
            style={style}
            onEvents={{
              click: onNodeClick,
            }}
          />
        )}
        {graphType === 'antv' && (
          <GraphinWrapper
            data={graphData}
            style={style}
            onNodeClick={onNodeClick}
          />
        )}
      </Stack>
      <Stack
        horizontal
        horizontalAlign="space-between"
        style={{ padding: '3px' }}
        tokens={{
          childrenGap: 10,
        }}
      >
        <Link
          href={getMessageByLocale(
            'component_activity_definition_link',
            settings.locale
          )}
          target="_blank"
        >
          {getMessageByLocale('component_activity_definition', settings.locale)}
        </Link>
        <Stack horizontal horizontalAlign="space-between">
          <span>Less</span>
          <div style={{ marginTop: '-12px', maxWidth: '80px' }}>
            <SwatchColorPicker
              columnCount={4}
              cellShape={'square'}
              cellHeight={10}
              cellWidth={10}
              colorCells={colorCellsExample1}
            />
          </div>
          <span>More</span>
        </Stack>
      </Stack>
    </Stack>
  );
}
Example #16
Source File: SiteScriptDesigner.tsx    From sp-site-designs-studio with MIT License 4 votes vote down vote up
SiteScriptActionDesignerBlock = (props: ISiteScriptActionDesignerBlockProps) => {

    const [appContext] = useAppContext<IApplicationState, ActionType>();

    // Get service references
    const siteScriptSchemaService = appContext.serviceScope.consume(SiteScriptSchemaServiceKey);
    const rendering = appContext.serviceScope.consume(RenderingServiceKey);
    const [seeMore, setSeeMore] = useState<boolean>(false);
    const [isSortingSubactions, setIsSortingSubactions] = useState<boolean>(false);


    const getActionDescription = () => siteScriptSchemaService.getActionDescription(props.siteScriptAction, props.parentSiteScriptAction);
    const getActionLabel = () => siteScriptSchemaService.getActionTitle(props.siteScriptAction, props.parentSiteScriptAction);
    const getAddableActions = () => {
        const groupLabel = `${getActionLabel()} - Subactions`;
        return {
            [groupLabel]: siteScriptSchemaService.getAvailableSubActions(props.siteScriptAction).map(a => ({
                group: groupLabel,
                iconName: "SetAction",
                key: a.verb,
                text: a.label,
                item: a
            } as IAddableItem))
        };
    };

    const toggleEdit = () => {
        props.onSiteScriptContentUIChanged(props.siteScriptContentUI.toggleEditing(props.siteScriptAction));
    };

    const onActionUpdated = (siteScriptAction: ISiteScriptActionUIWrapper) => {
        props.onSiteScriptContentUIChanged(props.siteScriptContentUI.replaceAction(siteScriptAction));
    };

    const onActionAdded = (verb: string, parentSiteScriptAction?: ISiteScriptActionUIWrapper) => {
        const newAction = parentSiteScriptAction
            ? siteScriptSchemaService.getNewSubActionFromVerb(parentSiteScriptAction.verb, verb)
            : siteScriptSchemaService.getNewActionFromVerb(verb);
        const updatedContentUI = parentSiteScriptAction
            ? props.siteScriptContentUI.addSubAction(parentSiteScriptAction, newAction)
            : props.siteScriptContentUI.addAction(newAction);
        props.onSiteScriptContentUIChanged(updatedContentUI);
    };

    const onActionRemoved = (removedAction: ISiteScriptActionUIWrapper, parentSiteScriptAction?: ISiteScriptActionUIWrapper) => {
        const updatedContentUI = parentSiteScriptAction
            ? props.siteScriptContentUI.removeSubAction(parentSiteScriptAction, removedAction)
            : props.siteScriptContentUI.removeAction(removedAction);
        props.onSiteScriptContentUIChanged(updatedContentUI);
    };

    const renderSummaryContent = (() => {
        const summaryValues = siteScriptSchemaService.getPropertiesAndValues(props.siteScriptAction, props.parentSiteScriptAction);
        if (!seeMore) {
            const previewSummary = summaryValues.slice(0, SEE_PROPERTIES_DEFAULT_COUNT);
            const displaySeeMoreLink = summaryValues.length >= SEE_PROPERTIES_DEFAULT_COUNT && !seeMore;
            return <ul>
                {previewSummary.map((pv, index) => <li key={`${props.siteScriptAction.$uiKey}_prop_${index}`}>{pv.property}: <strong title={pv.value}>{(!pv.value && pv.value !== false) ? "Not set" : getTrimmedText(pv.value, SUMMARY_VALUE_MAX_LEN)}</strong></li>)}
                {displaySeeMoreLink && <li key={`${props.siteScriptAction.$uiKey}_more_prop`}><Link onClick={() => setSeeMore(true)}>...</Link></li>}
            </ul>;
        } else {
            return <ul>
                {summaryValues.map((pv, index) => <li key={`${props.siteScriptAction.$uiKey}_prop_${index}`}>{pv.property}: <strong title={pv.value}>{!pv.value ? "Not set" : getTrimmedText(pv.value, SUMMARY_VALUE_MAX_LEN)}</strong></li>)}
            </ul>;
        }
    });

    const DragHandle = SortableHandle(() =>
        <div>
            <Icon iconName={props.index === (props.actionsCount - 1) ? "SortUp" : props.index === 0 ? "SortDown" : "Sort"} />
        </div>
    );

    const onSubActionSortChanged = (args: ISortEndEventArgs) => {
        props.onSiteScriptContentUIChanged(props.siteScriptContentUI.reorderSubActions(props.siteScriptAction.$uiKey, args.newIndex, args.oldIndex));
    };


    const toggleSortingSubactions = () => {
        if (!isSortingSubactions) {
            setTimeout(() => {
                props.onSiteScriptContentUIChanged(props.siteScriptContentUI.clearEditing([props.parentSiteScriptAction.$uiKey]));
            }, 0);
        }
        setIsSortingSubactions(!isSortingSubactions);
    };

    const renderScriptSubAction = (scriptActionUI: ISiteScriptActionUIWrapper, index: number) => {

        const scriptActionBlock = <SiteScriptActionDesignerBlock key={scriptActionUI.$uiKey}
            siteScriptAction={scriptActionUI}
            parentSiteScriptAction={props.siteScriptAction}
            siteScriptContentUI={props.siteScriptContentUI}
            onSiteScriptContentUIChanged={props.onSiteScriptContentUIChanged}
            isSorting={isSortingSubactions}
            index={index}
            actionsCount={(props.siteScriptAction
                && props.siteScriptAction.subactions
                && props.siteScriptAction.subactions.length) || 0}
        />;

        if (isSortingSubactions) {
            const SortableItem = SortableElement(() => scriptActionBlock);
            return <SortableItem key={scriptActionUI.$uiKey} index={index} />;
        } else {
            return scriptActionBlock;
        }
    };

    const renderScriptSubActionsList = () => {
        if (!props.siteScriptAction.subactions) {
            return null;
        }

        if (isSortingSubactions) {
            const SortableListContainer = SortableContainer(({ items }) => {
                return <div>{items.map(renderScriptSubAction)}</div>;
            });

            return <SortableListContainer
                items={props.siteScriptAction.subactions}
                // onSortStart={(args) => this._onSortStart(args)}
                onSortEnd={(args: any) => onSubActionSortChanged(args)}
                lockToContainerEdges={true}
                useDragHandle={false}
            />;
        } else {
            return <div>{props.siteScriptAction.subactions.map(renderScriptSubAction)}</div>;
        }
    };



    const hasSubActions = siteScriptSchemaService.hasSubActions(props.siteScriptAction);
    const isEditing = props.siteScriptContentUI.editingActionKeys.indexOf(props.siteScriptAction.$uiKey) >= 0;
    return <div className={`${styles.siteScriptAction} ${isEditing ? styles.isEditing : ""} ${props.isSorting ? styles.isSorting : ''}`}>
        <h4 title={getActionDescription()}>
            {props.isSorting && <span className={styles.sortIndex}>{props.index + 1}</span>}
            <span className={styles.actionLabelText}>{getActionLabel()}</span>
        </h4>
        <div className={styles.tools}>
            <Stack horizontal tokens={{ childrenGap: 3 }}>
                {!isEditing && props.isSorting && <DragHandle />}
                {!props.isSorting && <IconButton iconProps={{ iconName: isEditing ? "Accept" : "Edit" }} onClick={() => toggleEdit()} />}
                {!props.isSorting && !isEditing && <IconButton iconProps={{ iconName: "Delete" }} onClick={() => onActionRemoved(props.siteScriptAction, props.parentSiteScriptAction)} />}
            </Stack>
        </div>
        <div className={`${styles.summary} ${!isEditing || isSortingSubactions ? styles.isNotEditing : styles.isEditing}`}>
            {renderSummaryContent()}
        </div>
        {isEditing && <div className={`${styles.properties} ${isEditing ? styles.isEditing : ""}`}>
            {rendering.renderActionProperties(props.siteScriptAction,
                props.parentSiteScriptAction,
                (o) => onActionUpdated({ ...props.siteScriptAction, ...o } as ISiteScriptActionUIWrapper), ['verb', 'subactions', '$uiKey', '$isEditing'])}
            {hasSubActions && <div className={styles.subactions}>
                <div className={styles.row}>
                    <div className={styles.column10}>
                        <Label>Subactions</Label>
                    </div>
                    <div className={styles.column2}>
                        {props.siteScriptAction.subactions && props.siteScriptAction.subactions.length > 1 && <IconButton iconProps={{ iconName: "Sort" }}
                            // styles={{ root: { position: "absolute", top: -32, right: 9 } }}
                            checked={isSortingSubactions}
                            onClick={toggleSortingSubactions} />}
                    </div>
                </div>
                {renderScriptSubActionsList()}
                {!isSortingSubactions && <Adder items={getAddableActions()}
                    searchBoxPlaceholderText="Search a sub action..."
                    onSelectedItem={(item) => onActionAdded(item.key, props.siteScriptAction)} />}
            </div>}
        </div>}
    </div>;
}
Example #17
Source File: Options.tsx    From hypertrons-crx with Apache License 2.0 4 votes vote down vote up
Options: React.FC = () => {
  const [settings, setSettings] = useState(new Settings());
  const [metaData, setMetaData] = useState(new MetaData());
  const [inited, setInited] = useState(false);
  const [version, setVersion] = useState('0.0.0');
  const [checkingUpdate, setCheckingUpdate] = useState(false);
  const [token, setToken] = useState('');
  const [checkingToken, setCheckingToken] = useState(false);
  const [showDialogToken, setShowDialogToken] = useState(false);
  const [showDialogTokenError, setShowDialogTokenError] = useState(false);
  const [showDialogNotification, setShowDialogNotification] = useState(false);
  const [notificationId, setNotificationId] = useState(0);
  const [notification, setNotification] = useState('');
  const [updateStatus, setUpdateStatus] = useState(UpdateStatus.undefine);
  const [updateUrl, setUpdateUrl] = useState(
    'https://github.com/hypertrons/hypertrons-crx/releases'
  );
  const tokenCurrent = metaData.token;

  const graphOptions: IChoiceGroupOption[] = [
    {
      key: 'antv',
      text: 'Antv',
    },
    {
      key: 'echarts',
      text: 'Echarts',
    },
  ];

  const locale = settings.locale;
  const localeOptions: IChoiceGroupOption[] = [
    {
      key: 'en',
      text: 'English',
    },
    {
      key: 'zh_CN',
      text: '简体中文 (Simplified Chinese)',
    },
  ];

  useEffect(() => {
    const initMetaData = async () => {
      const tempMetaData = await loadMetaData();
      setMetaData(tempMetaData);
      if (tempMetaData.token !== '') {
        setToken(tempMetaData.token);
      }
      const notificationInformation = await getNotificationInformation();
      if (
        notificationInformation.is_published &&
        tempMetaData.idLastNotication < notificationInformation.id
      ) {
        if (locale === 'zh_CN') {
          setNotification(notificationInformation.content.zh);
        } else {
          setNotification(notificationInformation.content.en);
        }
        setNotificationId(notificationInformation.id);
        setShowDialogNotification(true);
      }
    };
    if (!inited) {
      initMetaData();
    }
  }, [inited, locale, metaData]);

  useEffect(() => {
    const initSettings = async () => {
      const temp = await loadSettings();
      setSettings(temp);
      setInited(true);
    };
    if (!inited) {
      initSettings();
    }
  }, [inited, settings]);

  const getVersion = async () => {
    let version = (await chrome.management.getSelf()).version;
    setVersion(version);
  };

  useEffect(() => {
    getVersion();
  }, [version]);

  const saveSettings = async (settings: Settings) => {
    setSettings(settings);
    await chromeSet('settings', settings.toJson());
  };

  const checkUpdateManually = async () => {
    setUpdateStatus(UpdateStatus.undefine);
    setCheckingUpdate(true);
    const [currentVersion, latestVersion, updateUrl] = await checkUpdate();
    if (compareVersion(currentVersion, latestVersion) === -1) {
      setUpdateUrl(updateUrl);
      setUpdateStatus(UpdateStatus.yes);
    } else {
      setUpdateStatus(UpdateStatus.no);
    }
    setCheckingUpdate(false);
  };

  if (!inited) {
    return <div />;
  }

  return (
    <Stack>
      {showDialogNotification && (
        <Dialog
          hidden={!showDialogNotification}
          onDismiss={() => {
            setShowDialogNotification(false);
          }}
          dialogContentProps={{
            type: DialogType.normal,
            title: getMessageByLocale(
              'global_notificationTitle',
              settings.locale
            ),
          }}
          modalProps={{
            isBlocking: true,
          }}
        >
          <Text variant="mediumPlus">{notification}</Text>
          <DialogFooter>
            <DefaultButton
              onClick={() => {
                setShowDialogNotification(false);
              }}
            >
              {getMessageByLocale('global_btn_ok', settings.locale)}
            </DefaultButton>
            <PrimaryButton
              onClick={async () => {
                metaData.idLastNotication = notificationId;
                setMetaData(metaData);
                await chromeSet('meta_data', metaData.toJson());
                setShowDialogNotification(false);
              }}
            >
              {getMessageByLocale('global_btn_disable', settings.locale)}
            </PrimaryButton>
          </DialogFooter>
        </Dialog>
      )}
      {showDialogToken && (
        <Dialog
          hidden={!showDialogToken}
          onDismiss={() => {
            setShowDialogToken(false);
          }}
          dialogContentProps={{
            type: DialogType.normal,
            title: getMessageByLocale(
              'options_token_dialog_title',
              settings.locale
            ),
          }}
          modalProps={{
            isBlocking: true,
          }}
        >
          <p style={{ fontSize: 14, color: '#6a737d', margin: 5 }}>
            {getMessageByLocale(
              'options_token_dialog_description',
              settings.locale
            )}
          </p>
          <Stack horizontal style={{ fontSize: 16, margin: 5 }}>
            <Link
              href="https://github.com/settings/tokens/new"
              target="_blank"
              underline
            >
              {getMessageByLocale(
                'options_token_dialog_message',
                settings.locale
              )}
            </Link>
          </Stack>
          {checkingToken && (
            <Spinner
              label={getMessageByLocale(
                'options_token_dialog_checking',
                settings.locale
              )}
            />
          )}
          {showDialogTokenError && (
            <MessageBar messageBarType={MessageBarType.error}>
              {getMessageByLocale(
                'options_token_dialog_error',
                settings.locale
              )}
            </MessageBar>
          )}
          <Stack
            horizontal
            horizontalAlign="space-around"
            verticalAlign="end"
            style={{ margin: '10px' }}
            tokens={{
              childrenGap: 15,
            }}
          >
            <TextField
              style={{ width: '200px' }}
              defaultValue={token}
              onChange={(e, value) => {
                if (value) {
                  setShowDialogTokenError(false);
                  setToken(value);
                }
              }}
            />
            <PrimaryButton
              disabled={checkingToken}
              onClick={async () => {
                setCheckingToken(true);
                const result = await checkIsTokenAvailabe(token);
                setCheckingToken(false);
                if ('id' in result) {
                  metaData.token = token;
                  metaData.avatar = result['avatar_url'];
                  metaData.name = result['name'];
                  metaData.id = result['id'];
                  setMetaData(metaData);
                  await chromeSet('meta_data', metaData.toJson());
                  setShowDialogToken(false);
                } else {
                  setShowDialogTokenError(true);
                }
              }}
            >
              {getMessageByLocale('global_btn_ok', settings.locale)}
            </PrimaryButton>
          </Stack>
          {tokenCurrent !== '' && (
            <DefaultButton
              onClick={async () => {
                metaData.token = '';
                metaData.avatar = '';
                metaData.name = '';
                metaData.id = '';
                setMetaData(metaData);
                await chromeSet('meta_data', metaData.toJson());
                setShowDialogToken(false);
              }}
              style={{
                width: 120,
              }}
            >
              {getMessageByLocale('options_token_btn_rmToken', settings.locale)}
            </DefaultButton>
          )}
        </Dialog>
      )}
      <Stack horizontalAlign="center" style={{ paddingBottom: '10px' }}>
        <h1>PERCEPTOR</h1>
        <sub>{`version ${version}`}</sub>
      </Stack>
      <Stack
        horizontalAlign="center"
        tokens={{
          childrenGap: 30,
        }}
      >
        <Stack.Item className="Box">
          <TooltipHost
            content={getMessageByLocale(
              'options_enable_toolTip',
              settings.locale
            )}
          >
            <Stack.Item className="Box-header">
              <h2 className="Box-title">
                {getMessageByLocale('options_enable_title', settings.locale)}
              </h2>
            </Stack.Item>
          </TooltipHost>
          <Stack
            style={{ margin: '10px 25px' }}
            tokens={{
              childrenGap: 10,
            }}
          >
            <p>
              {getMessageByLocale('options_enable_toolTip', settings.locale)}.
            </p>
            <Toggle
              label={getMessageByLocale(
                'options_enable_toggle_autoCheck',
                settings.locale
              )}
              defaultChecked={settings.isEnabled}
              onText={getMessageByLocale(
                'global_toggle_onText',
                settings.locale
              )}
              offText={getMessageByLocale(
                'global_toggle_offText',
                settings.locale
              )}
              onChange={async (e, checked) => {
                settings.isEnabled = checked;
                await saveSettings(settings);
              }}
            />
          </Stack>
        </Stack.Item>
        <Stack.Item className="Box">
          <TooltipHost
            content={getMessageByLocale(
              'options_locale_toolTip',
              settings.locale
            )}
          >
            <Stack.Item className="Box-header">
              <h2 className="Box-title">
                {getMessageByLocale('options_locale_title', settings.locale)}
              </h2>
            </Stack.Item>
          </TooltipHost>
          <Stack style={{ margin: '10px 25px' }}>
            <p>
              {getMessageByLocale('options_locale_toolTip', settings.locale)} :
            </p>
            <ChoiceGroup
              defaultSelectedKey={settings.locale}
              options={localeOptions}
              onChange={async (e, option: any) => {
                settings.locale = option.key;
                await saveSettings(settings);
              }}
            />
          </Stack>
        </Stack.Item>
        <Stack.Item className="Box">
          <TooltipHost
            content={getMessageByLocale(
              'options_components_toolTip',
              settings.locale
            )}
          >
            <Stack.Item className="Box-header">
              <h2 className="Box-title">
                {getMessageByLocale(
                  'options_components_title',
                  settings.locale
                )}
              </h2>
            </Stack.Item>
          </TooltipHost>
          <Stack
            style={{ margin: '10px 25px' }}
            tokens={{
              childrenGap: 10,
            }}
          >
            <p>
              {getMessageByLocale(
                'options_components_toolTip',
                settings.locale
              )}{' '}
              :
            </p>
            <Checkbox
              label={getMessageByLocale(
                'component_developerCollabrationNetwork_title',
                settings.locale
              )}
              defaultChecked={settings.developerNetwork}
              onChange={async (e, checked) => {
                settings.developerNetwork = checked;
                await saveSettings(settings);
              }}
            />
            <Checkbox
              label={getMessageByLocale(
                'component_projectCorrelationNetwork_title',
                settings.locale
              )}
              defaultChecked={settings.projectNetwork}
              onChange={async (e, checked) => {
                settings.projectNetwork = checked;
                await saveSettings(settings);
              }}
            />
          </Stack>
        </Stack.Item>
        <Stack.Item className="Box">
          <TooltipHost
            content={getMessageByLocale(
              'options_graphType_toolTip',
              settings.locale
            )}
          >
            <Stack.Item className="Box-header">
              <h2 className="Box-title">
                {getMessageByLocale('options_graphType_title', settings.locale)}
              </h2>
            </Stack.Item>
          </TooltipHost>
          <Stack style={{ margin: '10px 25px' }}>
            <p>
              {getMessageByLocale('options_graphType_toolTip', settings.locale)}{' '}
              :
            </p>
            <ChoiceGroup
              defaultSelectedKey={settings.graphType}
              options={graphOptions}
              onChange={async (e, option: any) => {
                settings.graphType = option.key as GraphType;
                await saveSettings(settings);
              }}
            />
          </Stack>
        </Stack.Item>
        <Stack.Item className="Box">
          <TooltipHost
            content={getMessageByLocale(
              'options_update_toolTip',
              settings.locale
            )}
          >
            <Stack.Item className="Box-header">
              <h2 className="Box-title">
                {getMessageByLocale('options_update_title', settings.locale)}
              </h2>
            </Stack.Item>
          </TooltipHost>
          <Stack
            style={{ margin: '10px 25px' }}
            tokens={{
              childrenGap: 10,
            }}
          >
            <p>
              {getMessageByLocale('options_update_toolTip', settings.locale)}.
            </p>
            <Toggle
              label={getMessageByLocale(
                'options_update_toggle_autoCheck',
                settings.locale
              )}
              defaultChecked={settings.checkForUpdates}
              onText={getMessageByLocale(
                'global_toggle_onText',
                settings.locale
              )}
              offText={getMessageByLocale(
                'global_toggle_offText',
                settings.locale
              )}
              onChange={async (e, checked) => {
                settings.checkForUpdates = checked;
                await saveSettings(settings);
              }}
            />
            {checkingUpdate && (
              <Stack horizontalAlign="start">
                <Spinner
                  label={getMessageByLocale(
                    'options_update_checking',
                    settings.locale
                  )}
                />
              </Stack>
            )}
            {updateStatus === UpdateStatus.yes && (
              <MessageBar
                messageBarType={MessageBarType.success}
                isMultiline={false}
              >
                {getMessageByLocale(
                  'options_update_btn_updateStatusYes',
                  settings.locale
                )}
                <Link href={updateUrl} target="_blank" underline>
                  {getMessageByLocale(
                    'options_update_btn_getUpdate',
                    settings.locale
                  )}
                </Link>
              </MessageBar>
            )}
            {updateStatus === UpdateStatus.no && (
              <MessageBar
                messageBarType={MessageBarType.info}
                isMultiline={false}
              >
                {getMessageByLocale(
                  'options_update_btn_updateStatusNo',
                  settings.locale
                )}
              </MessageBar>
            )}
            <DefaultButton
              style={{
                width: 120,
              }}
              disabled={checkingUpdate}
              onClick={async () => {
                await checkUpdateManually();
              }}
            >
              {getMessageByLocale(
                'options_update_btn_checkUpdate',
                settings.locale
              )}
            </DefaultButton>
          </Stack>
        </Stack.Item>
        <Stack.Item className="Box">
          <TooltipHost
            content={getMessageByLocale(
              'options_token_toolTip',
              settings.locale
            )}
          >
            <Stack.Item className="Box-header">
              <h2 className="Box-title">
                {getMessageByLocale('options_token_title', settings.locale)}
              </h2>
            </Stack.Item>
          </TooltipHost>
          <Stack
            style={{ margin: '10px 25px' }}
            tokens={{
              childrenGap: 10,
            }}
          >
            <p>
              {getMessageByLocale('options_token_toolTip', settings.locale)} :
            </p>
            {tokenCurrent !== '' && (
              <Stack
                horizontal
                verticalAlign="center"
                style={{
                  margin: '5px',
                  padding: '3px',
                  width: '300px',
                  boxShadow: '4px 4px 10px rgba(0, 0, 0, 0.2)',
                }}
                tokens={{
                  childrenGap: 5,
                }}
              >
                <Image
                  width={75}
                  height={75}
                  src={metaData.avatar}
                  imageFit={ImageFit.centerCover}
                />
                <Text
                  variant="large"
                  style={{
                    marginLeft: 25,
                    maxWidth: 200,
                    wordWrap: 'break-word',
                  }}
                >
                  {metaData.name}
                </Text>
              </Stack>
            )}
            <DefaultButton
              onClick={() => {
                setShowDialogToken(true);
              }}
              style={{
                width: 120,
              }}
            >
              {getMessageByLocale(
                'options_token_btn_setToken',
                settings.locale
              )}
            </DefaultButton>
          </Stack>
        </Stack.Item>
        <Stack.Item className="Box">
          <TooltipHost
            content={getMessageByLocale(
              'options_about_toolTip',
              settings.locale
            )}
          >
            <Stack.Item className="Box-header">
              <h2 className="Box-title">
                {getMessageByLocale('options_about_title', settings.locale)}
              </h2>
            </Stack.Item>
          </TooltipHost>
          <Stack style={{ margin: '10px 25px' }}>
            <p>
              {getMessageByLocale('options_about_description', settings.locale)}
            </p>
            <p>
              {getMessageByLocale(
                'options_about_description_website',
                settings.locale
              )}
            </p>
            <Link href={HYPERTRONS_CRX_WEBSITE} target="_blank" underline>
              {HYPERTRONS_CRX_WEBSITE}
            </Link>
          </Stack>
        </Stack.Item>
      </Stack>
    </Stack>
  );
}
Example #18
Source File: Progress.tsx    From AIPerf with MIT License 4 votes vote down vote up
render(): React.ReactNode {
        const { bestAccuracy } = this.props;
        const { isShowLogDrawer, isCalloutVisible, isShowSucceedInfo, info, typeInfo } = this.state;

        const count = TRIALS.countStatus();
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        const stoppedCount = count.get('USER_CANCELED')! + count.get('SYS_CANCELED')! + count.get('EARLY_STOPPED')!;
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        const bar2 = count.get('RUNNING')! + count.get('SUCCEEDED')! + count.get('FAILED')! + stoppedCount;
        // support type [0, 1], not 98%
        const bar2Percent = bar2 / EXPERIMENT.profile.params.maxTrialNum;
        const percent = EXPERIMENT.profile.execDuration / EXPERIMENT.profile.params.maxExecDuration;
        const remaining = convertTime(EXPERIMENT.profile.params.maxExecDuration - EXPERIMENT.profile.execDuration);
        const maxDuration = convertTime(EXPERIMENT.profile.params.maxExecDuration);
        const maxTrialNum = EXPERIMENT.profile.params.maxTrialNum;
        const execDuration = convertTime(EXPERIMENT.profile.execDuration);

        return (
            <Stack className="progress" id="barBack">
                <Stack className="basic lineBasic">
                    <p>Status</p>
                    <Stack horizontal className="status">
                        <span className={`${EXPERIMENT.status} status-text`}>{EXPERIMENT.status}</span>
                        {
                            EXPERIMENT.status === 'ERROR'
                                ?
                                <div>
                                    <div className={styles.buttonArea} ref={(val): any => this.menuButtonElement = val}>
                                        <IconButton
                                            iconProps={{ iconName: 'info' }}
                                            onClick={isCalloutVisible ? this.onDismiss : this.onShow}
                                        />
                                    </div>
                                    {isCalloutVisible && (
                                        <Callout
                                            className={styles.callout}
                                            ariaLabelledBy={this.labelId}
                                            ariaDescribedBy={this.descriptionId}
                                            role="alertdialog"
                                            gapSpace={0}
                                            target={this.menuButtonElement}
                                            onDismiss={this.onDismiss}
                                            setInitialFocus={true}
                                        >
                                            <div className={styles.header}>
                                                <p className={styles.title} id={this.labelId}>Error</p>
                                            </div>
                                            <div className={styles.inner}>
                                                <p className={styles.subtext} id={this.descriptionId}>
                                                    {EXPERIMENT.error}
                                                </p>
                                                <div className={styles.actions}>
                                                    <Link className={styles.link} onClick={this.isShowDrawer}>
                                                        Learn about
                                                    </Link>
                                                </div>
                                            </div>
                                        </Callout>
                                    )}
                                </div>
                                :
                                null
                        }
                    </Stack>
                </Stack>
                <ProgressBar
                    who="Duration"
                    percent={percent}
                    description={execDuration}
                    bgclass={EXPERIMENT.status}
                    maxString={`Max duration: ${maxDuration}`}
                />
                <ProgressBar
                    who="Trial numbers"
                    percent={bar2Percent}
                    description={bar2.toString()}
                    bgclass={EXPERIMENT.status}
                    maxString={`Max trial number: ${maxTrialNum}`}
                />
                <Stack className="basic colorOfbasic mess" horizontal>
                    <StackItem grow={50}>
                        <p>Best metric</p>
                        <div>{isNaN(bestAccuracy) ? 'N/A' : bestAccuracy.toFixed(6)}</div>
                    </StackItem>
                    <StackItem>
                        {isShowSucceedInfo && <MessageInfo className="info" typeInfo={typeInfo} info={info} />}
                    </StackItem>
                </Stack>
                <Stack horizontal horizontalAlign="space-between" className="mess">
                    <span style={itemStyles} className="basic colorOfbasic">
                        <p>Spent</p>
                        <div>{execDuration}</div>
                    </span>
                    <span style={itemStyles} className="basic colorOfbasic">
                        <p>Remaining</p>
                        <div className="time">{remaining}</div>
                    </span>
                    <span style={itemStyles}>
                        {/* modify concurrency */}
                        <TooltipHost content={CONCURRENCYTOOLTIP}>
                        <p className="cursor">Concurrency<span className="progress-info">{infoIcon}</span></p>
                        </TooltipHost>
                        <ConcurrencyInput value={this.props.concurrency} updateValue={this.editTrialConcurrency} />
                    </span>
                    <span style={itemStyles} className="basic colorOfbasic"></span>
                </Stack>
                <Stack horizontal horizontalAlign="space-between" className="mess">
                    <div style={itemStyles} className="basic colorOfbasic">
                        <p>Running</p>
                        <div>{count.get('RUNNING')}</div>
                    </div>
                    <div style={itemStyles} className="basic colorOfbasic">
                        <p>Succeeded</p>
                        <div>{count.get('SUCCEEDED')}</div>
                    </div>
                    <div style={itemStyles} className="basic">
                        <p>Stopped</p>
                        <div>{stoppedCount}</div>
                    </div>
                    <div style={itemStyles} className="basic">
                        <p>Failed</p>
                        <div>{count.get('FAILED')}</div>
                    </div>
                </Stack>
                {/* learn about click -> default active key is dispatcher. */}
                {isShowLogDrawer ? (
                    <LogDrawer
                        closeDrawer={this.closeDrawer}
                        activeTab="dispatcher"
                    />
                ) : null}
            </Stack>
        );
    }
Example #19
Source File: RulesView.tsx    From website with MIT License 4 votes vote down vote up
Rules = () => {
    const theme = useTheme();
    const locale = LocalizationService.strings();
    var language: string | undefined = LocalizationService.getLanguage();
    const icon: IIconProps = { iconName: 'QandA' };

    const rulesData: Rule[] = getRules();

    const imageProperties = { display: 'inline-block', width: '100%' };

    const [isCalloutVisible, { toggle: toggleIsCalloutVisible }] = useBoolean(false);
    const buttonId = useId('callout-button');

    const styles = mergeStyleSets({
        callout: {
            maxWidth: 800,
            padding: '20px 24px',
            marginLeft: '5px',
            marginRight: '15px'
        },
        button: {
            width: 'auto',
            height: 'auto',
            borderRadius: 3
        },
    });

    return (
        <div className="rules pb-3">
            <div className="pt-5 pb-5 mb-4" style={{ backgroundColor: theme.palette.themePrimary }}>
                <Container>

                    <Row>
                        <Col lg={4} className="text-center">
                            <div style={{ marginLeft: 'auto', marginRight: 'auto', maxWidth: 300 }}>
                                <Image id="logo" className="mb-2" src={process.env.PUBLIC_URL + '/images/rules.png'} style={imageProperties} />
                            </div>
                        </Col>

                        <Col lg={8}>
                            <div className="mb-2">
                                <Text variant="xLargePlus" style={{color: theme.palette.white}}>{locale?.rules.text1}</Text>
                            </div>

                            <div className="mb-3">
                                <Text variant="large" style={{ color: theme.palette.white }}>{locale?.rules.text2}</Text>
                            </div>

                            <div className="mb-3">
                                <DefaultButton
                                    id={buttonId}
                                    onClick={toggleIsCalloutVisible}
                                    text={locale?.rules.question}
                                    className={styles.button}
                                    iconProps={icon}
                                    theme={theme}
                                    style={{ boxShadow: theme.effects.elevation8 }}
                                />
                                {isCalloutVisible && (
                                    <Callout
                                        className={styles.callout}
                                        role="alertdialog"
                                        gapSpace={3}
                                        target={`#${buttonId}`}
                                        onDismiss={toggleIsCalloutVisible}
                                        directionalHint={DirectionalHint.bottomCenter}
                                        setInitialFocus
                                    >
                                        <Text block variant="medium" className="mb-1" styles={semibold}>{locale?.rules.answer.text1}</Text>
                                        <Text block variant="small"><JsxParser bindings={{ theme: theme }} components={{ Text, Link }} jsx={locale?.rules.answer.text2} /></Text>
                                    </Callout>
                                )}
                            </div>

                            <div>
                                <Text variant="medium" style={{ color: theme.palette.white }}><i>{locale?.rules.text3}</i></Text>
                            </div>
                        </Col>
                    </Row>

                </Container>
            </div>
            
            <div className="mb-4">
                <div className="mb-4 text-center">
                    <Text variant="xLarge">{locale?.rules.header}</Text>
                </div>
            </div>

            <div className="mb-3">
                <Container>
                    {
                        rulesData.map((x, i) => {
                            return (
                                <Accordion style={{ backgroundColor: theme.palette.white, color: theme.palette.black, boxShadow: theme.effects.elevation8, marginRight: 10, marginLeft: 10 }} key={i}>
                                    <AccordionSummary
                                        expandIcon={<ExpandMoreIcon style={{ color: theme.palette.black }} />}
                                        aria-controls="panel1a-content"
                                        id="panel1a-header"
                                    >
                                        <Text variant="medium" style={{ color: theme.palette.themePrimary }} styles={semibold}>{x.title![language!]}</Text>
                                    </AccordionSummary>
                                    <AccordionDetails>
                                        <Text variant="medium">
                                            <JsxParser bindings={{ theme: theme, semibold: semibold }} components={{ Text, Link }} jsx={x.description![language!]} />
                                        </Text>
                                    </AccordionDetails>
                                </Accordion>
                            )
                        })
                    }
                </Container>
            </div>
        </div>
    )
}
Example #20
Source File: OrganizationView.tsx    From website with MIT License 4 votes vote down vote up
OrganizationView = () => {
    var theme = useTheme();
    const locale = LocalizationService.strings();
    var language: string | undefined = LocalizationService.getLanguage();
    const networkMembers = getNetworkMembers();
    const icon: IIconProps = { iconName: 'DocumentSearch' };
    const imageProperties = { display: 'inline-block', width: '100%' };

    return (
        <div className="organization pb-3">

            <div className="pt-5 pb-5" style={{ backgroundColor: theme.palette.themeDarkAlt }}>
                <Container>

                    <Row>
                        <Col lg={4} className="text-center">
                            <div style={{ marginLeft: 'auto', marginRight: 'auto', maxWidth: 300 }}>
                                <Image id="logo" className="mb-2" src={process.env.PUBLIC_URL + '/images/organization.png'} style={imageProperties} />
                            </div>
                        </Col>

                        <Col lg={8} className="mb-2">
                            <div className="mb-2">
                                <Text variant="xLargePlus" style={{ color: theme.palette.white }}>{locale?.aboutUs.text1}</Text>
                            </div>

                            <div className="mb-2">
                                <Text variant="large" style={{ color: theme.palette.white }}>{locale?.aboutUs.text2}</Text>
                            </div>

                            <div className="mb-3">
                                <Text variant="medium" style={{ color: theme.palette.white }}>{locale?.aboutUs.text3}</Text>
                            </div>

                            <div className="mb-2">
                                <CompoundButton primary theme={theme} secondaryText={locale?.aboutUs.button.text2} href="https://github.com/StudentiUniMi/docs/raw/main/statuto.pdf" style={{ textDecoration: 'none', boxShadow: theme.effects.elevation8 }} iconProps={icon}>
                                    {locale?.aboutUs.button.text1}
                                </CompoundButton>
                            </div>
                        </Col>
                    </Row>

                </Container>
            </div>

            <div className="pt-4 pb-4">
                <div className="mb-4 text-center"><Text variant="xLarge" styles={semibold} style={{ color: theme.palette.themePrimary }}>{locale?.aboutUs.header1}</Text></div>
                
                <div style={{maxWidth: 230, marginLeft: 'auto', marginRight: 'auto'}}>
                    <Persona
                        size={PersonaSize.size72}
                        imageUrl={"https://studentiunimi-groups-propics.marcoaceti.workers.dev/26170256.png"}
                        text={networkMembers[0].name}
                        onRenderPrimaryText={() => <Text variant="medium" styles={semibold}>{networkMembers[0].name}</Text>}
                        secondaryText={networkMembers[0].username}
                        onRenderSecondaryText={() => <Text variant="medium"><Link href={`https://t.me/${networkMembers[0].username}`}>@{networkMembers[0].username}</Link></Text>}
                    />
                </div>
            </div>

            <div className="pb-4">
                <Container>
                    <div className="mb-4 text-center"><Text variant="xLarge" styles={semibold} style={{color: theme.palette.themePrimary}}>{locale?.aboutUs.header2}</Text></div>

                    <Row className="justify-content-center">
                        {
                            (networkMembers.slice(1, networkMembers.length)).map((x, i) =>
                                <>
                                    <Col className="mb-4" lg={3} md={6} sm={6} xs={12}>
                                        <div style={{ maxWidth: 240, marginLeft: 'auto', marginRight: 'auto' }}>
                                            <Persona
                                                size={PersonaSize.size72}
                                                imageUrl={`https://studentiunimi-groups-propics.marcoaceti.workers.dev/${x.user_id}.png`}
                                                text={x.name}
                                                onRenderPrimaryText={() => <Text variant="medium" styles={semibold}>{x.name}</Text>}
                                                secondaryText={x.username}
                                                onRenderSecondaryText={() => <Text variant="medium"><Link href={`https://t.me/${x.username}`}>@{x.username}</Link></Text>}
                                            />
                                        </div>
                                    </Col>
                                </>
                            )
                        }
                    </Row>
                
                </Container>
            </div>

            <div className="pb-4">
                <Container>
                    <div className="mb-4 text-center"><Text variant="xLarge" styles={semibold} style={{ color: theme.palette.themePrimary }}>{locale?.contributors.header1}</Text></div>

                    <Row className="justify-content-center">
                        {
                            developers.map((x:any, i:any) =>
                                <>
                                    <Col className="mb-3" lg={4} sm={6} xs={12}>
                                        <div style={{ maxWidth: 250, marginLeft: 'auto', marginRight: 'auto' }}>
                                            <Persona
                                                size={PersonaSize.size72}
                                                imageUrl={`https://studentiunimi-groups-propics.marcoaceti.workers.dev/${x.user_id}.png`}
                                                text={x.name}
                                                onRenderPrimaryText={() => <Text variant="medium" styles={semibold}><Link href={x.github}>{x.name}</Link></Text>}
                                                secondaryText={x.username}
                                                onRenderSecondaryText={() => <Text variant="medium"><Link href={`https://t.me/${x.username}`}>@{x.username}</Link></Text>}
                                                tertiaryText={x.description[language!]}
                                                onRenderTertiaryText={() => <Text variant="small">{x.description[language!]}</Text>}
                                            />
                                        </div>
                                    </Col>
                                </>
                            )
                        }
                    </Row>

                </Container>
            </div>

        </div>
    )
}
Example #21
Source File: Footer.tsx    From website with MIT License 4 votes vote down vote up
Footer = (props: Props) => {
    var theme = useTheme();
    const [cookies, setCookie] = useCookies();
    const locale = LocalizationService.strings();
    var language: string | undefined = LocalizationService.getLanguage();
    const date: Date = addDays(new Date(), 90);

    const themeToggled = () => {
        if (cookies["theme"] === "dark") setCookie("theme", "light", { path: "/", expires: date });
        else { setCookie("theme", "dark", { path: "/", expires: date }); }
        props.changeTheme();
    };

    const changeLanguage = (lang: string) => {
        LocalizationService.localize(lang);
        setCookie("language", lang, { path: "/", expires: date });
        props.changeLanguage(lang);
    };
    
    const wrapIconStyle = { backgroundColor: theme.palette.themeSecondary, borderRadius: '35%', minWidth: 30, minHeight: 30, display: 'inline-block', textAlign: 'center', justifyContent: 'center', verticalAlign: 'middle' } as React.CSSProperties;
    const iconStyle = { color: theme.palette.white, fontSize: '17px', marginTop: 6 };
    
    const buttonStyle = { maxWidth: '270px', boxShadow: theme.effects.elevation8 };
    const buttonIconProps: IIconProps = { iconName: 'ChevronRightSmall', styles: { root: { fontSize: 12 } } };

    /* Theme palette code */
    const colorCells: any[] = palettes.map(x => ({ id: x.id, label: x.label, color: x.palette?.themePrimary }));
    const resetColorIcon: IIconProps = { iconName: 'SyncOccurence' };
    const calloutPropsResetColor = { gapSpace: 10 };
    const hostStylesResetColor: Partial<ITooltipHostStyles> = { root: { display: 'inline-block' } };

    return (
        <footer style={{ backgroundColor: theme.palette.neutralQuaternaryAlt, borderTop: '1px solid', borderColor: theme.palette.neutralLight }} className="pt-4 pb-4">
            <Container style={{ width: '100%', color: theme.palette.neutralSecondary }}>

                <Row className="mb-4">
                    <Col xl={4} lg={4} md={6} sm={12} xs={12} className="mb-4 mb-md-0">
                        <div className="mb-2">
                            <Text styles={semibold} style={{ color: theme.palette.themePrimary }} variant="large">
                                &copy; Network StudentiUniMi
                            </Text>
                        </div>

                        <div className="mb-2 text">
                            <PrimaryButton text={locale?.footer[0].buttonText} iconProps={buttonIconProps} href="https://t.me/unimichat" className="text-decoration-none" allowDisabledFocus style={buttonStyle} />
                        </div>
                    </Col>
                    

                    <Col xl={2} lg={2} md={3} sm={12} xs={12} className="mb-2 mb-md-0">
                        <div>
                            <div className="mb-2">
                                <Text styles={semibold} variant="medium">{locale?.footer[1].header}</Text>
                            </div>

                            <div>
                                <Text variant="medium">
                                    <ul className="list-unstyled mb-3">
                                        <li style={listElement}>
                                            <Link href="http://www.quickunimi.it/">QuickUnimi</Link>
                                        </li>
                                        <li style={listElement}>
                                            <Link href="https://codeshare.tech">Codeshare.tech</Link>
                                        </li>
                                    </ul>
                                </Text>
                            </div>
                        </div>
                    </Col>
                    
                    <Col xl={3} lg={2} md={3} sm={12} xs={12}>
                        <div className="mb-2">
                            <Toggle
                                label={locale?.settingsPanel.changeTheme}
                                onText={locale?.settingsPanel.darkTheme}
                                offText={locale?.settingsPanel.lightTheme}
                                checked={cookies["theme"] === "dark"}
                                onChange={themeToggled}
                                theme={theme}
                            />
                        </div>
                        
                        <div className="mb-2 language-selector">
                            <Label>{locale?.settingsPanel.selectLanguage}</Label>
                            <Text 
                                variant="medium" 
                                style={{ cursor: 'pointer' }} 
                                styles={cookies["language"] === "it" ? bold : {}} onClick={() => { changeLanguage("it") } }
                            >
                                ITA
                            </Text>
                            
                            <Text variant="medium"> | </Text>

                            <Text 
                                variant="medium" 
                                style={{ cursor: 'pointer' }} 
                                styles={cookies["language"] === "en" ? bold : {}} onClick={() => { changeLanguage("en") }}
                            >
                                ENG
                            </Text>
                        </div>
                    </Col>

                    <Col xl={3} lg={4} md={6} sm={12} xs={12}>
                        <div>
                            <Text variant="medium" styles={semibold}>{locale?.settingsPanel.selectColor}  </Text>
                            <TooltipHost
                                content="Reset color"
                                calloutProps={calloutPropsResetColor}
                                styles={hostStylesResetColor}
                            >
                                <IconButton iconProps={resetColorIcon} onClick={() => { setCookie("palette", 'a', { path: "/", expires: date }); props.changePalette('a'); }} />
                            </TooltipHost>
                            <SwatchColorPicker selectedId={cookies["palette"]} columnCount={7} cellShape={'square'} colorCells={colorCells} onColorChanged={(id) => { setCookie("palette", id, { path: "/", expires: date }); props.changePalette(id!); }} />
                        </div>
                    </Col>
                
                </Row>


                <Row>
                    <Col lg={6} sm={12} style={{ display: 'table' }} className="center-mobile mb-2">
                        <Text variant="medium"  style={{  display: 'table-cell', verticalAlign: 'middle' }}>
                            {locale?.footer[0].text}
                        </Text>
                    </Col>

                    <Col lg={6} sm={12}>
                        <div className="mb-1 text-right center-mobile">
                            {footerIcons.map( (x: any, i: number) => { 
                                return (
                                    <TooltipHost
                                        content={x.name[language!]}
                                        calloutProps={calloutPropsResetColor}
                                        styles={hostStylesResetColor}
                                        key={i}
                                        delay={TooltipDelay.zero}
                                    >
                                        <Link href={x.link}>
                                            <span style={wrapIconStyle} className="text-decoration mr-1">
                                                { x.type === 'brand' ?
                                                <FontAwesomeIcon icon={['fab', x.iconName]} style={iconStyle} />
                                                :
                                                <FontAwesomeIcon icon={x.iconName} style={iconStyle} /> }
                                            </span>
                                        </Link>
                                    </TooltipHost>
                                )}
                            )}
                        </div>
                    </Col>

                </Row>

            </Container>
        </footer>
    )
}