text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="path_to_url">
<item android:drawable="@drawable/ic_main_nav_play_list_selected" android:state_checked="true" />
<item android:drawable="@drawable/ic_main_nav_play_list"/>
</selector>
``` | /content/code_sandbox/app/src/main/res/drawable/selector_main_nav_play_list.xml | xml | 2016-09-13T14:38:32 | 2024-08-16T12:30:58 | StylishMusicPlayer | ryanhoo/StylishMusicPlayer | 3,699 | 65 |
```xml
import { Component } from '@angular/core';
@Component({
selector: 'ngx-search-fields',
templateUrl: 'search-fields.component.html',
})
export class SearchComponent {
}
``` | /content/code_sandbox/src/app/pages/ui-features/search-fields/search-fields.component.ts | xml | 2016-05-25T10:09:03 | 2024-08-16T16:34:03 | ngx-admin | akveo/ngx-admin | 25,169 | 36 |
```xml
import {
BasicTableSettings,
FilteredColumnsTableSettings,
RefreshableTableSettings,
SettableColumnsTableSettings,
} from '@@/datatables/types';
export type QuickAction = 'attach' | 'exec' | 'inspect' | 'logs' | 'stats';
export interface SettableQuickActionsTableSettings<TAction> {
hiddenQuickActions: TAction[];
setHiddenQuickActions: (hiddenQuickActions: TAction[]) => void;
}
export interface TableSettings
extends BasicTableSettings,
SettableColumnsTableSettings,
SettableQuickActionsTableSettings<QuickAction>,
RefreshableTableSettings,
FilteredColumnsTableSettings {
truncateContainerName: number;
setTruncateContainerName: (value: number) => void;
}
``` | /content/code_sandbox/app/react/docker/containers/ListView/ContainersDatatable/types.ts | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 163 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>PreferenceSpecifiers</key>
<array>
<dict>
<key>FooterText</key>
<string>This application makes use of the following third party libraries:</string>
<key>Title</key>
<string>Acknowledgements</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</string>
<key>Title</key>
<string>Commander</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>- MIT LICENSE -
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</string>
<key>Title</key>
<string>GenumKit</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</string>
<key>Title</key>
<string>PathKit</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</string>
<key>Title</key>
<string>Stencil</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>Generated by CocoaPods - path_to_url
<key>Title</key>
<string></string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
</array>
<key>StringsTable</key>
<string>Acknowledgements</string>
<key>Title</key>
<string>Acknowledgements</string>
</dict>
</plist>
``` | /content/code_sandbox/Vendor/SwiftGen/Pods/Target Support Files/Pods-swiftgen/Pods-swiftgen-acknowledgements.plist | xml | 2016-06-12T02:03:36 | 2024-08-13T13:02:39 | Iconic | home-assistant/Iconic | 1,576 | 1,445 |
```xml
<!--
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
path_to_url
Unless required by applicable law or agreed to in writing,
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
specific language governing permissions and limitations
-->
<Configuration>
<name>pulsar-functions-instance</name>
<monitorInterval>30</monitorInterval>
<Properties>
<Property>
<name>pulsar.log.appender</name>
<value>RollingFile</value>
</Property>
<Property>
<name>pulsar.log.level</name>
<value>info</value>
</Property>
<Property>
<name>bk.log.level</name>
<value>info</value>
</Property>
</Properties>
<Appenders>
<Console>
<name>Console</name>
<target>SYSTEM_OUT</target>
<PatternLayout>
<Pattern>%d{ISO8601_OFFSET_DATE_TIME_HHMM} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
</Console>
<RollingFile>
<name>RollingFile</name>
<fileName>${sys:pulsar.function.log.dir}/${sys:pulsar.function.log.file}.log</fileName>
<filePattern>${sys:pulsar.function.log.dir}/${sys:pulsar.function.log.file}-%d{MM-dd-yyyy}-%i.log.gz</filePattern>
<immediateFlush>true</immediateFlush>
<PatternLayout>
<Pattern>%d{ISO8601_OFFSET_DATE_TIME_HHMM} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy>
<interval>1</interval>
<modulate>true</modulate>
</TimeBasedTriggeringPolicy>
<SizeBasedTriggeringPolicy>
<size>1 GB</size>
</SizeBasedTriggeringPolicy>
<CronTriggeringPolicy>
<schedule>0 0 0 * * ?</schedule>
</CronTriggeringPolicy>
</Policies>
<DefaultRolloverStrategy>
<Delete>
<basePath>${sys:pulsar.function.log.dir}</basePath>
<maxDepth>2</maxDepth>
<IfFileName>
<glob>*/${sys:pulsar.function.log.file}*log.gz</glob>
</IfFileName>
<IfLastModified>
<age>30d</age>
</IfLastModified>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<RollingRandomAccessFile>
<name>BkRollingFile</name>
<fileName>${sys:pulsar.function.log.dir}/${sys:pulsar.function.log.file}.bk</fileName>
<filePattern>${sys:pulsar.function.log.dir}/${sys:pulsar.function.log.file}.bk-%d{MM-dd-yyyy}-%i.log.gz</filePattern>
<immediateFlush>true</immediateFlush>
<PatternLayout>
<Pattern>%d{ISO8601_OFFSET_DATE_TIME_HHMM} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy>
<interval>1</interval>
<modulate>true</modulate>
</TimeBasedTriggeringPolicy>
<SizeBasedTriggeringPolicy>
<size>1 GB</size>
</SizeBasedTriggeringPolicy>
<CronTriggeringPolicy>
<schedule>0 0 0 * * ?</schedule>
</CronTriggeringPolicy>
</Policies>
<DefaultRolloverStrategy>
<Delete>
<basePath>${sys:pulsar.function.log.dir}</basePath>
<maxDepth>2</maxDepth>
<IfFileName>
<glob>*/${sys:pulsar.function.log.file}.bk*log.gz</glob>
</IfFileName>
<IfLastModified>
<age>30d</age>
</IfLastModified>
</Delete>
</DefaultRolloverStrategy>
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<Logger>
<name>org.apache.pulsar.functions.runtime.shaded.org.apache.bookkeeper</name>
<level>${sys:bk.log.level}</level>
<additivity>false</additivity>
<AppenderRef>
<ref>BkRollingFile</ref>
</AppenderRef>
</Logger>
<Root>
<level>info</level>
<AppenderRef>
<ref>${sys:pulsar.log.appender}</ref>
<level>${sys:pulsar.log.level}</level>
</AppenderRef>
</Root>
</Loggers>
</Configuration>
``` | /content/code_sandbox/pulsar-functions/runtime-all/src/main/resources/java_instance_log4j2.xml | xml | 2016-06-28T07:00:03 | 2024-08-16T17:12:43 | pulsar | apache/pulsar | 14,047 | 1,086 |
```xml
import * as React from "react";
import * as ReactDOM from "react-dom/client";
import "./style.css";
import App from "./components/App";
import GraphiQL from "./components/playground/GraphiQL";
function Routes() {
if (window.location.pathname === "/playground") {
return <GraphiQL />;
}
return <App />;
}
const root = ReactDOM.createRoot(document.getElementById("app"));
root.render(<Routes />);
``` | /content/code_sandbox/newsfeed/src/index.tsx | xml | 2016-06-21T17:45:14 | 2024-08-06T13:25:19 | relay-examples | relayjs/relay-examples | 1,141 | 92 |
```xml
import stripHeredoc from "./stripHeredoc";
import findQueryByLine from "./findQueryByLine";
export default {
stripHeredoc,
findQueryByLine,
};
``` | /content/code_sandbox/src/lib/Util/index.ts | xml | 2016-08-23T12:20:03 | 2024-08-14T08:26:34 | bdash | bdash-app/bdash | 1,488 | 41 |
```xml
/**
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {Operation} from './Operation';
export class ContinueOperation extends Operation {
static opName = 'Continue';
constructor() {
super('ContinueMergeOperation');
}
getArgs() {
return ['continue'];
}
// It's tempting to add makeOptimisticMergeConflictsApplier to `continue`,
// but we don't know if we'll hit additional merge conflicts,
// and we don't want our detection of conflicts to not work.
// Instead of optimistically hiding the conflicts, we show a spinner on the continue button.
}
``` | /content/code_sandbox/addons/isl/src/operations/ContinueMergeOperation.ts | xml | 2016-05-05T16:53:47 | 2024-08-16T19:12:02 | sapling | facebook/sapling | 5,987 | 148 |
```xml
import { EditorInterface, Element, Editor, Text } from '../interfaces'
export const shouldMergeNodesRemovePrevNode: EditorInterface['shouldMergeNodesRemovePrevNode'] =
(editor, [prevNode, prevPath], [curNode, curNodePath]) => {
// If the target node that we're merging with is empty, remove it instead
// of merging the two. This is a common rich text editor behavior to
// prevent losing formatting when deleting entire nodes when you have a
// hanging selection.
// if prevNode is first child in parent,don't remove it.
return (
(Element.isElement(prevNode) && Editor.isEmpty(editor, prevNode)) ||
(Text.isText(prevNode) &&
prevNode.text === '' &&
prevPath[prevPath.length - 1] !== 0)
)
}
``` | /content/code_sandbox/packages/slate/src/editor/should-merge-nodes-remove-prev-node.ts | xml | 2016-06-18T01:52:42 | 2024-08-16T18:43:42 | slate | ianstormtaylor/slate | 29,492 | 182 |
```xml
//
//
// Microsoft Bot Framework: path_to_url
//
// Bot Framework Emulator Github:
// path_to_url
//
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import {
beginAdd,
closeDocument as closeChatDocument,
close as closeEditorDocument,
newNotification,
openBotViaUrlAction,
openTranscript,
SharedConstants,
} from '@bfemulator/app-shared';
import { ChannelService, CommandServiceImpl, CommandServiceInstance } from '@bfemulator/sdk-shared';
import { IEndpointService } from 'botframework-config/lib/schema';
import { Command } from '@bfemulator/sdk-shared';
import { EmulatorMode } from '@bfemulator/sdk-shared';
import { getTabGroupForDocument } from '../state/helpers/editorHelpers';
import { store } from '../state/store';
const {
Emulator,
Telemetry: { TrackEvent },
} = SharedConstants.Commands;
export class EmulatorCommands {
@CommandServiceInstance()
private commandService: CommandServiceImpl;
// your_sha256_hash-----------
// Open a new emulator tabbed document
// NOTE: only called for livechats started from .bot file endpoints
@Command(Emulator.NewLiveChat)
protected newLiveChat(endpoint: IEndpointService, mode: EmulatorMode = 'livechat') {
// extract information normally used to start a conversation via URL
// and pass it through that flow
store.dispatch(
openBotViaUrlAction({
appId: endpoint.appId,
appPassword: endpoint.appPassword,
tenantId: endpoint.tenantId,
channelService: endpoint.channelService as ChannelService,
endpoint: endpoint.endpoint,
isFromBotFile: true,
mode,
})
);
}
// your_sha256_hash-----------
// Prompt to open a transcript file, then open it
@Command(Emulator.PromptToOpenTranscript)
protected async promptToOpenTranscript() {
const dialogOptions = {
title: 'Open transcript file',
buttonLabel: 'Choose file',
properties: ['openFile'],
filters: [
{
name: 'Transcript Files (.chat, .transcript)',
extensions: ['chat', 'transcript'],
},
],
};
try {
const { ShowOpenDialog } = SharedConstants.Commands.Electron;
const filename: string = await this.commandService.remoteCall(ShowOpenDialog, dialogOptions);
if (filename) {
store.dispatch(openTranscript(filename));
this.commandService
.remoteCall(TrackEvent, 'transcriptFile_open', {
method: 'file_menu',
})
.catch(_e => void 0);
}
} catch (e) {
const errMsg = `Error while opening transcript file: ${e}`;
const notification = newNotification(errMsg);
store.dispatch(beginAdd(notification));
}
}
// your_sha256_hash-----------
// Same as open transcript, except that it closes the transcript first, before reopening it
@Command(Emulator.ReloadTranscript)
protected reloadTranscript(filePath: string, filename: string) {
const tabGroup = getTabGroupForDocument(filePath);
if (tabGroup) {
store.dispatch(closeEditorDocument(getTabGroupForDocument(filePath), filePath));
store.dispatch(closeChatDocument(filePath));
}
store.dispatch(openTranscript(filename));
}
}
``` | /content/code_sandbox/packages/app/client/src/commands/emulatorCommands.ts | xml | 2016-11-11T23:15:09 | 2024-08-16T12:45:29 | BotFramework-Emulator | microsoft/BotFramework-Emulator | 1,803 | 932 |
```xml
import { SchemaGeneratorBase } from '../generator'
import { IGQLType } from 'prisma-datamodel'
import { GraphQLSchema } from 'graphql/type'
export default class SchemaGenerator extends SchemaGeneratorBase {
public getTypeName(input: IGQLType[], args: {}) {
return '__Schema'
}
public generate(input: IGQLType[], args?: {}) {
return new GraphQLSchema({
query: this.generators.query.generate(input, {}),
mutation: this.generators.mutation.generate(input, {}),
subscription: this.generators.subscription.generate(input, {}),
})
}
}
``` | /content/code_sandbox/cli/packages/prisma-generate-schema/src/generator/default/schemaGenerator.ts | xml | 2016-09-25T12:54:40 | 2024-08-16T11:41:23 | prisma1 | prisma/prisma1 | 16,549 | 123 |
```xml
import React, { useMemo } from "react";
import { useSelector } from "react-redux";
import { getAvailableTeams, getCurrentlyActiveWorkspace } from "store/features/teams/selectors";
import { Avatar, Row, Dropdown } from "antd";
import { getUniqueColorForWorkspace } from "utils/teams";
import { RQButton } from "lib/design-system/components";
import { MdOutlineKeyboardArrowDown } from "@react-icons/all-files/md/MdOutlineKeyboardArrowDown";
import type { MenuProps } from "antd";
import { Team } from "types";
import { trackShareModalWorkspaceDropdownClicked } from "modules/analytics/events/misc/sharing";
interface Props {
/**
* The default number of active workspaces to display before dropdown menu.
*/
defaultActiveWorkspaces?: number;
onTransferClick: (teamData: Team) => void;
isLoading: boolean;
}
interface WorkspaceItemProps {
team: Team;
availableTeams?: Team[];
onTransferClick?: (teamData: Team) => void;
showArrow?: boolean;
isLoading?: boolean;
}
export const WorkspaceShareMenu: React.FC<Props> = ({ onTransferClick, isLoading, defaultActiveWorkspaces = 0 }) => {
const availableTeams = useSelector(getAvailableTeams);
const currentlyActiveWorkspaceId = useSelector(getCurrentlyActiveWorkspace)?.id;
const activeTeamData: Team = useMemo(
() => availableTeams?.find((team: Team) => team?.id === currentlyActiveWorkspaceId),
[currentlyActiveWorkspaceId, availableTeams]
);
const sortedTeams: Team[] = useMemo(
() => (availableTeams ? [...availableTeams].sort((a: Team, b: Team) => b.accessCount - a.accessCount) : []),
[availableTeams]
);
const menuItems: MenuProps["items"] = useMemo(() => {
return sortedTeams
.slice(defaultActiveWorkspaces || 0)
.map((team: Team, index: number) => {
if (!defaultActiveWorkspaces && team?.id === activeTeamData?.id) return null;
return {
key: index,
label: <WorkspaceItem isLoading={isLoading} onTransferClick={onTransferClick} team={team} />,
};
})
.filter(Boolean);
}, [sortedTeams, activeTeamData?.id, onTransferClick, defaultActiveWorkspaces, isLoading]);
const chooseOtherWorkspaceItem = (
<div className="workspace-share-menu-item-card workspace-share-menu-dropdown">
<Row align="middle" className="items-center">
<Avatar
size={35}
className="workspace-avatar"
shape="square"
icon="*"
style={{
backgroundColor: "#B835F6",
}}
/>
<span className="workspace-card-description">
<div className="text-gray">Choose other workspace</div>
</span>
</Row>
<MdOutlineKeyboardArrowDown className="text-gray header mr-8" />
</div>
);
return (
<>
{defaultActiveWorkspaces ? (
<>
<div className="mt-1">
{sortedTeams.slice(0, defaultActiveWorkspaces).map((team: Team, index: number) => (
<WorkspaceItem isLoading={isLoading} team={team} onTransferClick={onTransferClick} key={index} />
))}
</div>
{sortedTeams.length > defaultActiveWorkspaces && (
<Dropdown
menu={{ items: menuItems }}
placement="bottom"
overlayClassName="workspace-share-menu-wrapper"
trigger={["click"]}
onOpenChange={(open) => {
if (open) trackShareModalWorkspaceDropdownClicked();
}}
>
<div>{chooseOtherWorkspaceItem}</div>
</Dropdown>
)}
</>
) : (
<Dropdown
menu={{ items: menuItems }}
placement="bottom"
overlayClassName="workspace-share-menu-wrapper"
trigger={availableTeams?.length > 1 ? ["click"] : [null]}
onOpenChange={(open) => {
if (open) trackShareModalWorkspaceDropdownClicked();
}}
>
<div>
<WorkspaceItem team={activeTeamData} showArrow availableTeams={availableTeams} />
</div>
</Dropdown>
)}
</>
);
};
const WorkspaceItem: React.FC<WorkspaceItemProps> = ({
team,
onTransferClick,
availableTeams,
showArrow = false,
isLoading = false,
}) => {
return (
<div
className={`workspace-share-menu-item-card ${
showArrow && availableTeams?.length > 1 && "workspace-share-menu-dropdown"
}`}
>
<Row align="middle" className="items-center">
<Avatar
size={35}
className="workspace-avatar"
shape="square"
icon={team.name ? team.name?.[0]?.toUpperCase() : "W"}
style={{
backgroundColor: `${getUniqueColorForWorkspace(team.id ?? "", team.name)}`,
}}
/>
<span className="workspace-card-description">
<div className="text-white">{team.name}</div>
<div className="text-gray">
{team.accessCount} {team.accessCount > 1 ? "members" : "member"}
</div>
</span>
</Row>
{showArrow ? (
availableTeams?.length > 1 ? (
<MdOutlineKeyboardArrowDown className="text-gray header mr-8" />
) : null
) : (
<RQButton
disabled={isLoading}
type="link"
className="workspace-menu-item-transfer-btn"
onClick={() => onTransferClick(team)}
>
Transfer here
</RQButton>
)}
</div>
);
};
``` | /content/code_sandbox/app/src/components/common/SharingModal/Workspaces/WorkspaceShareMenu.tsx | xml | 2016-12-01T04:36:06 | 2024-08-16T19:12:19 | requestly | requestly/requestly | 2,121 | 1,226 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="path_to_url">
<PropertyGroup Label="Globals">
<ProjectGuid>{D9DF7F2F-93B7-4810-B5CD-96F4F33C079B}</ProjectGuid>
<Keyword>MakeFileProj</Keyword>
<ConfigurationType>Makefile</ConfigurationType>
<UseOfMfc>false</UseOfMfc>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<!-- The following import will include the 'default' configuration options for VS projects. -->
<Import Project="..\allinone\Build.Windows.ProjectConfiguration.props" />
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir>.\data\tmp\$(Platform)\</OutDir>
<IntDir>.\data\build\</IntDir>
<MakeCFG>$(Platform)\$(Configuration)</MakeCFG>
<DebugBuild Condition="'$(Configuration)'=='Debug'">true</DebugBuild>
<!-- The ICU projects use "Win32" to mean "x86", so we need to special case it. -->
<OutDir Condition="'$(Platform)'=='Win32'">.\data\tmp\x86\</OutDir>
<MakeCFG Condition="'$(Platform)'=='Win32'">x86\$(Configuration)</MakeCFG>
<!-- NMake -->
<NMakeBuildCommandLine>NMAKE /f makedata.mak ICUMAKE="$(ProjectDir)\" CFG=$(MakeCFG) DEBUG=$(DebugBuild)</NMakeBuildCommandLine>
<NMakeReBuildCommandLine>NMAKE /f makedata.mak ICUMAKE="$(ProjectDir)\" CFG=$(MakeCFG) clean all</NMakeReBuildCommandLine>
<NMakeCleanCommandLine>NMAKE /f makedata.mak ICUMAKE="$(ProjectDir)\" CFG=$(MakeCFG) clean</NMakeCleanCommandLine>
<NMakeOutput/>
<NMakePreprocessorDefinitions>$(NMakePreprocessorDefinitions)</NMakePreprocessorDefinitions>
<NMakeIncludeSearchPath>$(NMakeIncludeSearchPath)</NMakeIncludeSearchPath>
<NMakeForcedIncludes>$(NMakeForcedIncludes)</NMakeForcedIncludes>
<NMakeAssemblySearchPath>$(NMakeAssemblySearchPath)</NMakeAssemblySearchPath>
<NMakeForcedUsingAssemblies>$(NMakeForcedUsingAssemblies)</NMakeForcedUsingAssemblies>
</PropertyGroup>
<ItemDefinitionGroup>
<BuildLog>
<Path>.\data\log\$(Platform)\$(Configuration)BuildLog.html</Path>
</BuildLog>
</ItemDefinitionGroup>
<ItemGroup>
<None Include="makedata.mak" />
<None Include="..\test\testdata\testdata.mak" />
<None Include="mappings\ucmcore.mk" />
<None Include="mappings\ucmebcdic.mk" />
<None Include="mappings\ucmfiles.mk" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\common\common.vcxproj">
<Project>{73c0a65b-d1f2-4de1-b3a6-15dad2c23f3d}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\extra\uconv\uconv.vcxproj">
<Project>{dba4088d-f6f9-4f8f-8820-082a4765c16c}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\i18n\i18n.vcxproj">
<Project>{0178b127-6269-407d-b112-93877bb62776}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\io\io.vcxproj">
<Project>{c2b04507-2521-4801-bf0d-5fd79d6d518c}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\stubdata\stubdata.vcxproj">
<Project>{203ec78a-0531-43f0-a636-285439bde025}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\test\cintltst\cintltst.vcxproj">
<Project>{3d1246ae-1b32-479b-beca-aefa97be2321}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\test\intltest\intltest.vcxproj">
<Project>{73632960-b3a6-464d-83a3-4b43365f19b8}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\test\iotest\iotest.vcxproj">
<Project>{e4993e82-d68a-46ca-bae0-9d35e172e46f}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\ctestfw\ctestfw.vcxproj">
<Project>{eca6b435-b4fa-4f9f-bf95-f451d078fc47}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\genbrk\genbrk.vcxproj">
<Project>{c2be5000-7501-4e87-9724-b8d82494fae6}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\genccode\genccode.vcxproj">
<Project>{fdd3c4f2-9805-44eb-9a77-bc1c1c95b547}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\gencfu\gencfu.vcxproj">
<Project>{691ee0c0-dc57-4a48-8aee-8ed75eb3a057}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\gencmn\gencmn.vcxproj">
<Project>{a8d36f8d-09e6-4174-91c3-7beaa9c3f04f}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\gencnval\gencnval.vcxproj">
<Project>{8b41752b-5a52-41e4-b7e0-07921c0cc6bf}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\gendict\gendict.vcxproj">
<Project>{9d4211f7-2c77-439c-82f0-30a4e43ba569}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\gennorm2\gennorm2.vcxproj">
<Project>{c7891a65-80ab-4245-912e-5f1e17b0e6c4}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\genrb\derb.vcxproj">
<Project>{d3065adb-8820-4cc7-9b6c-9510833961a3}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\genrb\genrb.vcxproj">
<Project>{97521d06-ec47-45d4-8bd0-9e16b3f93b2a}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\gensprep\gensprep.vcxproj">
<Project>{631c23ce-6c1d-4875-88f0-85e0a42b36ea}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\gentest\gentest.vcxproj">
<Project>{77c78066-746f-4ea6-b3fe-b8c8a4a97891}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\icupkg\icupkg.vcxproj">
<Project>{62d4b15d-7a90-4ecb-ba19-5e021d6a21bc}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\makeconv\makeconv.vcxproj">
<Project>{f5ad9738-1a3d-4906-b9c4-a7d9ce33dc2c}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\pkgdata\pkgdata.vcxproj">
<Project>{4c8454fe-81d3-4ca3-9927-29ba96f03dac}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\tools\toolutil\toolutil.vcxproj">
<Project>{6b231032-3cb5-4eed-9210-810d666a23a0}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
``` | /content/code_sandbox/icu4c/source/data/makedata.vcxproj | xml | 2016-01-08T02:42:32 | 2024-08-16T18:14:55 | icu | unicode-org/icu | 2,693 | 2,336 |
```xml
import * as React from 'react';
import createSvgIcon from '../utils/createSvgIcon';
const HealthSolidIcon = createSvgIcon({
svg: ({ classes }) => (
<svg xmlns="path_to_url" viewBox="0 0 2048 2048" className={classes.svg} focusable="false">
<path d="M1504 128q113 0 212 42t172 116 116 173 43 212q0 58-12 115t-36 110h-463l-192-200-320 320-448-448-320 328H49q-24-53-36-110T1 671q0-113 42-212t116-172 173-116 212-43q109 0 208 41t177 118l95 96 95-96q77-77 176-118t209-41zm-96 896h510l-14 16q-7 8-15 17l-865 864-865-864q-8-8-15-16t-14-17h254l192-184 448 448 320-320 64 56z" />
</svg>
),
displayName: 'HealthSolidIcon',
});
export default HealthSolidIcon;
``` | /content/code_sandbox/packages/react-icons-mdl2/src/components/HealthSolidIcon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 284 |
```xml
export const mockHandlers = new Map();
const channel = {
registerMessage: jest.fn().mockImplementation((type, handler) => mockHandlers.set(type, handler)),
onMessage: jest.fn(),
buffer: {
push: jest.fn(),
flush: jest.fn(),
},
ports: {
broadcast: jest.fn(),
onConnect: jest.fn(),
disconnect: jest.fn(),
query: jest.fn(),
},
};
export default channel;
``` | /content/code_sandbox/applications/pass-extension/src/__mocks__/app/worker/channel.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 96 |
```xml
import { useTheme } from "@emotion/react"
import Color from "color"
import { observer } from "mobx-react-lite"
import { FC } from "react"
import { colorToVec4 } from "../../../gl/color"
import { useStores } from "../../../hooks/useStores"
import { trackColorToCSSColor } from "../../../track/TrackColor"
import { NoteCircles } from "./NoteCircles"
import { NoteRectangles } from "./NoteRectangles"
export const Notes: FC<{ zIndex: number }> = observer(({ zIndex }) => {
const {
pianoRollStore: { notes, selectedTrack },
} = useStores()
const theme = useTheme()
if (selectedTrack === undefined) {
return <></>
}
const baseColor = Color(
selectedTrack.color !== undefined
? trackColorToCSSColor(selectedTrack.color)
: theme.themeColor,
)
const borderColor = colorToVec4(baseColor.lighten(0.3))
const selectedColor = colorToVec4(baseColor.lighten(0.7))
const backgroundColor = colorToVec4(Color(theme.backgroundColor))
const baseColorVec4 = colorToVec4(baseColor)
return (
<>
{selectedTrack.isRhythmTrack && (
<NoteCircles
strokeColor={borderColor}
rects={notes}
inactiveColor={backgroundColor}
activeColor={baseColorVec4}
selectedColor={selectedColor}
zIndex={zIndex}
/>
)}
{!selectedTrack.isRhythmTrack && (
<NoteRectangles
strokeColor={borderColor}
inactiveColor={backgroundColor}
activeColor={baseColorVec4}
selectedColor={selectedColor}
rects={notes}
zIndex={zIndex + 0.1}
/>
)}
</>
)
})
``` | /content/code_sandbox/app/src/components/PianoRoll/PianoRollCanvas/Notes.tsx | xml | 2016-03-06T15:19:53 | 2024-08-15T14:27:10 | signal | ryohey/signal | 1,238 | 386 |
```xml
export function GET(req: Request) {
return Response.json(Object.fromEntries(req.headers))
}
``` | /content/code_sandbox/test/e2e/app-dir/x-forwarded-headers/app/route.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 20 |
```xml
import green from '@mui/material/colors/green';
import type { SxProps } from '@mui/material';
import orange from '@mui/material/colors/orange';
import red from '@mui/material/colors/red';
import { Identifier } from 'react-admin';
import { Review } from './../types';
const rowSx =
(selectedRow?: Identifier) =>
(record: Review): SxProps => {
let style = {};
if (!record) {
return style;
}
if (selectedRow && selectedRow === record.id) {
style = {
...style,
backgroundColor: 'action.selected',
};
}
if (record.status === 'accepted')
return {
...style,
borderLeftColor: green[500],
borderLeftWidth: 5,
borderLeftStyle: 'solid',
};
if (record.status === 'pending')
return {
...style,
borderLeftColor: orange[500],
borderLeftWidth: 5,
borderLeftStyle: 'solid',
};
if (record.status === 'rejected')
return {
...style,
borderLeftColor: red[500],
borderLeftWidth: 5,
borderLeftStyle: 'solid',
};
return style;
};
export default rowSx;
``` | /content/code_sandbox/examples/demo/src/reviews/rowSx.tsx | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 273 |
```xml
<?xml version="1.0"?>
<RDF xmlns="path_to_url#"
xmlns:em="path_to_url#">
<Description about="urn:mozilla:install-manifest">
<em:id>test-addon-3@mozilla.org</em:id>
<em:version>0.1</em:version>
<em:name>Test Add-on 3</em:name>
<em:creator>Mozilla</em:creator>
<em:homepageURL>path_to_url
<em:type>2</em:type>
<!-- Firefox -->
<em:targetApplication>
<Description>
<em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
<em:minVersion>3.5.*</em:minVersion>
<em:maxVersion>*</em:maxVersion>
</Description>
</em:targetApplication>
</Description>
</RDF>
``` | /content/code_sandbox/deps/3rdparty/spidermonkey/mozjs/testing/mozbase/mozprofile/tests/install_manifests/test_addon_3.rdf | xml | 2016-05-23T10:56:48 | 2024-05-23T14:42:06 | eventql | eventql/eventql | 1,180 | 211 |
```xml
<clickhouse>
<profiles>
<default>
<max_expanded_ast_elements>1800</max_expanded_ast_elements>
<force_index_by_date>1</force_index_by_date>
<force_primary_key>1</force_primary_key>
</default>
</profiles>
</clickhouse>
``` | /content/code_sandbox/tests/integration/test_mutations_with_merge_tree/configs/users.xml | xml | 2016-06-02T08:28:18 | 2024-08-16T18:39:33 | ClickHouse | ClickHouse/ClickHouse | 36,234 | 68 |
```xml
import { Indicator, IndicatorInput } from '../indicator/indicator';
import { SMA } from '../moving_averages/SMA'
import { CandleData } from '../StockData';
export class AwesomeOscillatorInput extends IndicatorInput {
high:number[]
low:number[]
fastPeriod :number
slowPeriod :number
}
export class AwesomeOscillator extends Indicator {
generator:IterableIterator<number | undefined>;
constructor (input:AwesomeOscillatorInput) {
super(input);
var highs = input.high;
var lows = input.low;
var fastPeriod = input.fastPeriod;
var slowPeriod = input.slowPeriod;
var slowSMA = new SMA({ values : [], period : slowPeriod })
var fastSMA = new SMA({ values : [], period : fastPeriod })
this.result = [];
this.generator = (function* (){
var result;
var tick;
var medianPrice;
var slowSmaValue;
var fastSmaValue;
tick = yield;
while (true)
{
medianPrice = (tick.high + tick.low) / 2
slowSmaValue = slowSMA.nextValue(medianPrice);
fastSmaValue = fastSMA.nextValue(medianPrice);
if(slowSmaValue !== undefined && fastSmaValue !== undefined) {
result = fastSmaValue - slowSmaValue;
}
tick = yield result
}
})();
this.generator.next();
highs.forEach((tickHigh, index) => {
var tickInput = {
high : tickHigh,
low : lows[index],
}
var result = this.generator.next(tickInput);
if(result.value != undefined){
this.result.push(this.format(result.value));
}
});
};
static calculate = awesomeoscillator;
nextValue(price:CandleData):number | undefined {
var result = this.generator.next(price);
if(result.value != undefined){
return this.format(result.value);
}
};
}
export function awesomeoscillator(input:AwesomeOscillatorInput):number[] {
Indicator.reverseInputs(input);
var result = new AwesomeOscillator(input).result;
if(input.reversedInput) {
result.reverse();
}
Indicator.reverseInputs(input);
return result;
};
``` | /content/code_sandbox/src/oscillators/AwesomeOscillator.ts | xml | 2016-05-02T19:16:32 | 2024-08-15T14:25:09 | technicalindicators | anandanand84/technicalindicators | 2,137 | 497 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions
xmlns="path_to_url"
xmlns:activiti="path_to_url"
targetNamespace="Examples">
<process id="startToEnd">
<startEvent id="theStart" />
<sequenceFlow id="flow1" sourceRef="theStart" targetRef="task" />
<serviceTask id="task" activiti:class="org.flowable.engine.test.bpmn.StartToEndTest$PrimitiveServiceTaskDelegate" />
<sequenceFlow id="flow2" sourceRef="task" targetRef="theEnd" />
<endEvent id="theEnd" />
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable-engine/src/test/resources/org/flowable/engine/test/bpmn/StartToEndTest.testStartWithServiceTask.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 147 |
```xml
import React from 'react';
import { getRouter } from '@storybook/nextjs/router.mock';
import type { Meta, StoryObj } from '@storybook/react';
import { expect, userEvent, within } from '@storybook/test';
import Router, { useRouter } from 'next/router';
function Component() {
const router = useRouter();
const searchParams = router.query;
const routerActions = [
{
cb: () => router.back(),
name: 'Go back',
},
{
cb: () => router.forward(),
name: 'Go forward',
},
{
cb: () => router.prefetch('/prefetched-html'),
name: 'Prefetch',
},
{
// @ts-expect-error (old API)
cb: () => router.push('/push-html', { forceOptimisticNavigation: true }),
name: 'Push HTML',
},
{
// @ts-expect-error (old API)
cb: () => router.replace('/replaced-html', { forceOptimisticNavigation: true }),
name: 'Replace',
},
];
return (
<div>
<div>Router pathname: {Router.pathname}</div>
<div>pathname: {router.pathname}</div>
<div>
searchparams:{' '}
<ul>
{Object.entries(searchParams).map(([key, value]) => (
<li key={key}>
{key}: {value}
</li>
))}
</ul>
</div>
{routerActions.map(({ cb, name }) => (
<div key={name} style={{ marginBottom: '1em' }}>
<button type="button" onClick={cb}>
{name}
</button>
</div>
))}
</div>
);
}
export default {
component: Component,
parameters: {
nextjs: {
router: {
pathname: '/hello',
query: {
foo: 'bar',
},
prefetch: () => {
console.log('custom prefetch');
},
},
},
},
} as Meta<typeof Component>;
export const Default: StoryObj<typeof Component> = {
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);
const routerMock = getRouter();
await step('Router property overrides should be available in useRouter fn', async () => {
await expect(Router.pathname).toBe('/hello');
await expect(Router.query).toEqual({ foo: 'bar' });
});
await step(
'Router property overrides should be available in default export from next/router',
async () => {
await expect(Router.pathname).toBe('/hello');
await expect(Router.query).toEqual({ foo: 'bar' });
}
);
await step('Asserts whether forward hook is called', async () => {
const forwardBtn = await canvas.findByText('Go forward');
await userEvent.click(forwardBtn);
await expect(routerMock.forward).toHaveBeenCalled();
});
await step('Asserts whether custom prefetch hook is called', async () => {
const prefetchBtn = await canvas.findByText('Prefetch');
await userEvent.click(prefetchBtn);
await expect(routerMock.prefetch).toHaveBeenCalledWith('/prefetched-html');
});
},
};
``` | /content/code_sandbox/code/frameworks/nextjs/template/stories_nextjs-default-ts/Router.stories.tsx | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 692 |
```xml
<manifest xmlns:android="path_to_url" package="org.chromium.ui">
</manifest>
``` | /content/code_sandbox/libraries_res/ui_res/src/main/AndroidManifest.xml | xml | 2016-07-04T07:28:36 | 2024-08-15T05:20:42 | AndroidChromium | JackyAndroid/AndroidChromium | 3,090 | 21 |
```xml
import { describe, expect, it } from "vitest";
import { Formatter } from "@export/formatter";
import { MathRun } from "../math-run";
import { MathSum } from "./math-sum";
describe("MathSum", () => {
describe("#constructor()", () => {
it("should create a MathSum with correct root key", () => {
const mathSum = new MathSum({
children: [new MathRun("1")],
subScript: [new MathRun("2")],
superScript: [new MathRun("3")],
});
const tree = new Formatter().format(mathSum);
expect(tree).to.deep.equal({
"m:nary": [
{
"m:naryPr": [
{
"m:chr": {
_attr: {
"m:val": "",
},
},
},
{
"m:limLoc": {
_attr: {
"m:val": "undOvr",
},
},
},
],
},
{
"m:sub": [
{
"m:r": [
{
"m:t": ["2"],
},
],
},
],
},
{
"m:sup": [
{
"m:r": [
{
"m:t": ["3"],
},
],
},
],
},
{
"m:e": [
{
"m:r": [
{
"m:t": ["1"],
},
],
},
],
},
],
});
});
it("should add a hide when there is no subScript or superScript", () => {
const mathSum = new MathSum({
children: [new MathRun("1")],
});
const tree = new Formatter().format(mathSum);
expect(tree).to.deep.equal({
"m:nary": [
{
"m:naryPr": [
{
"m:chr": {
_attr: {
"m:val": "",
},
},
},
{
"m:limLoc": {
_attr: {
"m:val": "undOvr",
},
},
},
{
"m:supHide": {
_attr: {
"m:val": 1,
},
},
},
{
"m:subHide": {
_attr: {
"m:val": 1,
},
},
},
],
},
{
"m:e": [
{
"m:r": [
{
"m:t": ["1"],
},
],
},
],
},
],
});
});
});
});
``` | /content/code_sandbox/src/file/paragraph/math/n-ary/math-sum.spec.ts | xml | 2016-03-26T23:43:56 | 2024-08-16T13:02:47 | docx | dolanmiu/docx | 4,139 | 583 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!--
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<resources>
<style name="ThemeOverlay.Material3.Catalog.Toolbar.Contextual" parent="">
<item name="colorControlNormal">?attr/colorPrimary</item>
</style>
<style name="TextAppearance.Material3.Catalog.Toolbar.Contextual.Title" parent="TextAppearance.Material3.TitleMedium">
<item name="android:textColor">?attr/colorPrimary</item>
<item name="android:textSize">@dimen/m3_toolbar_text_size_title</item>
</style>
</resources>
``` | /content/code_sandbox/catalog/java/io/material/catalog/search/res/values/styles.xml | xml | 2016-12-05T16:11:29 | 2024-08-16T17:51:42 | material-components-android | material-components/material-components-android | 16,176 | 160 |
```xml
declare module "@datacamp/ui-plot" {
import { Component, Props } from "react";
export interface IPlotSource {
type: "img" | "html";
src: string;
}
export interface IPlotProps extends Props<Plot> {
sources?: IPlotSource[];
currentIndex?: number;
setIndex: (currentIndex: number) => void;
exercise: {
language: string;
type: string;
};
resizePlot: (
currentIndex: number,
language: string,
width?: number,
height?: number
) => void;
expand: (source: string) => void;
}
export default class Plot extends Component<IPlotProps> {}
}
``` | /content/code_sandbox/vendor/@datacamp/ui-plot/index.d.ts | xml | 2016-01-21T17:02:22 | 2024-08-12T19:21:02 | datacamp-light | datacamp/datacamp-light | 1,304 | 154 |
```xml
import { CommonProps, TreeCanvasProps, TreeSvgProps } from './types'
import { Node } from './Node'
import { Link } from './Link'
import { Label } from './Label'
import { renderNode, renderLink, renderLabel } from './canvas'
export const commonDefaultProps: Pick<
CommonProps<any>,
| 'identity'
| 'mode'
| 'layout'
| 'nodeSize'
| 'nodeColor'
| 'fixNodeColorAtDepth'
| 'linkCurve'
| 'linkThickness'
| 'linkColor'
| 'enableLabel'
| 'label'
| 'labelsPosition'
| 'orientLabel'
| 'labelOffset'
| 'isInteractive'
| 'useMesh'
| 'meshDetectionRadius'
| 'debugMesh'
| 'highlightAncestorNodes'
| 'highlightDescendantNodes'
| 'highlightAncestorLinks'
| 'highlightDescendantLinks'
| 'nodeTooltipPosition'
| 'nodeTooltipAnchor'
| 'role'
| 'animate'
| 'motionConfig'
> = {
identity: 'id',
mode: 'dendogram',
layout: 'top-to-bottom',
nodeSize: 12,
nodeColor: { scheme: 'nivo' },
fixNodeColorAtDepth: Infinity,
linkCurve: 'bump',
linkThickness: 1,
linkColor: { from: 'source.color', modifiers: [['opacity', 0.4]] },
enableLabel: true,
label: 'id',
labelsPosition: 'outward',
orientLabel: true,
labelOffset: 6,
isInteractive: true,
useMesh: true,
meshDetectionRadius: Infinity,
debugMesh: false,
highlightAncestorNodes: true,
highlightDescendantNodes: false,
highlightAncestorLinks: true,
highlightDescendantLinks: false,
nodeTooltipPosition: 'fixed',
nodeTooltipAnchor: 'top',
role: 'img',
animate: true,
motionConfig: 'gentle',
}
export const svgDefaultProps: typeof commonDefaultProps &
Required<
Pick<
TreeSvgProps<any>,
'layers' | 'nodeComponent' | 'linkComponent' | 'labelComponent' | 'linkTooltipAnchor'
>
> = {
...commonDefaultProps,
layers: ['links', 'nodes', 'labels', 'mesh'],
nodeComponent: Node,
linkComponent: Link,
labelComponent: Label,
linkTooltipAnchor: 'top',
}
export const canvasDefaultProps: typeof commonDefaultProps &
Required<
Pick<
TreeCanvasProps<any>,
'layers' | 'renderNode' | 'renderLink' | 'renderLabel' | 'pixelRatio'
>
> = {
...commonDefaultProps,
layers: ['links', 'nodes', 'labels', 'mesh'],
renderNode,
renderLink,
renderLabel,
pixelRatio: typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1,
}
``` | /content/code_sandbox/packages/tree/src/defaults.ts | xml | 2016-04-16T03:27:56 | 2024-08-16T03:38:37 | nivo | plouc/nivo | 13,010 | 667 |
```xml
import './version';
export {
AnimationClassNames,
AnimationStyles,
AnimationVariables,
ColorClassNames,
DefaultEffects,
DefaultFontStyles,
DefaultPalette,
// eslint-disable-next-line deprecation/deprecation
EdgeChromiumHighContrastSelector,
FontClassNames,
FontSizes,
FontWeights,
HighContrastSelector,
HighContrastSelectorBlack,
HighContrastSelectorWhite,
IconFontSizes,
InjectionMode,
PulsingBeaconAnimationStyles,
ScreenWidthMaxLarge,
ScreenWidthMaxMedium,
ScreenWidthMaxSmall,
ScreenWidthMaxXLarge,
ScreenWidthMaxXXLarge,
ScreenWidthMinLarge,
ScreenWidthMinMedium,
ScreenWidthMinSmall,
ScreenWidthMinUhfMobile,
ScreenWidthMinXLarge,
ScreenWidthMinXXLarge,
ScreenWidthMinXXXLarge,
Stylesheet,
ThemeSettingName,
ZIndexes,
buildClassMap,
concatStyleSets,
concatStyleSetsWithProps,
createFontStyles,
focusClear,
fontFace,
// eslint-disable-next-line deprecation/deprecation
getEdgeChromiumNoHighContrastAdjustSelector,
getFadedOverflowStyle,
getFocusOutlineStyle,
// eslint-disable-next-line deprecation/deprecation
getFocusStyle,
getGlobalClassNames,
getHighContrastNoAdjustStyle,
getIcon,
getIconClassName,
getInputFocusStyle,
getPlaceholderStyles,
getScreenSelector,
getTheme,
getThemedContext,
hiddenContentStyle,
keyframes,
loadTheme,
mergeStyleSets,
mergeStyles,
noWrap,
normalize,
registerIconAlias,
registerIcons,
registerOnThemeChangeCallback,
removeOnThemeChangeCallback,
setIconOptions,
unregisterIcons,
} from '@fluentui/style-utilities';
export { createTheme, registerDefaultFontFaces } from '@fluentui/theme';
export type {
GlobalClassNames,
IAnimationStyles,
IAnimationVariables,
ICSPSettings,
IEffects,
IFontFace,
IFontStyles,
IFontWeight,
IGetFocusStylesOptions,
IIconOptions,
IIconRecord,
IIconSubset,
IIconSubsetRecord,
IPalette,
IPartialTheme,
IProcessedStyleSet,
IRawStyle,
IScheme,
ISchemeNames,
ISemanticColors,
ISemanticTextColors,
ISpacing,
IStyle,
IStyleSet,
IStyleSheetConfig,
ITheme,
ShadowConfig,
} from '@fluentui/style-utilities';
import type { ShadowConfig } from '@fluentui/style-utilities';
export interface IShadowDomStyle {
/**
* Optional configuration object when using shadow DOM.
*/
__shadowConfig__?: ShadowConfig;
}
``` | /content/code_sandbox/packages/react/src/Styling.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 615 |
```xml
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
import { getModelState } from '@proton/account/test';
import type { WorkerDecryptionResult } from '@proton/crypto';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import type { AttachmentsMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { encryptAttachment } from '@proton/shared/lib/mail/send/attachments';
import { mockDefaultBreakpoints } from '@proton/testing/lib/mockUseActiveBreakpoint';
import isTruthy from '@proton/utils/isTruthy';
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
import ItemColumnLayout from 'proton-mail/components/list/ItemColumnLayout';
import { MAX_COLUMN_ATTACHMENT_THUMBNAILS } from 'proton-mail/constants';
import { filterAttachmentToPreview } from 'proton-mail/helpers/attachment/attachmentThumbnails';
import { arrayToBase64 } from 'proton-mail/helpers/base64';
import { addApiMock } from 'proton-mail/helpers/test/api';
import type { GeneratedKey } from 'proton-mail/helpers/test/helper';
import {
addApiKeys,
assertIcon,
clearAll,
createAttachment,
generateKeys,
getAddressKeyCache,
getCompleteAddress,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from 'proton-mail/helpers/test/helper';
import { render } from 'proton-mail/helpers/test/render';
import type { Conversation } from 'proton-mail/models/conversation';
import { addAttachment } from 'proton-mail/store/attachments/attachmentsActions';
jest.mock('@proton/shared/lib/helpers/downloadFile'); // mocking left to individual tests
const mockDownloadFile = downloadFile as jest.MockedFunction<typeof downloadFile>;
const fileContent = `test-content`;
const generateAttachmentsMetadata = (numberOfAttachments: number, extension = 'png', mimeType = 'image/png') => {
const attachmentsMetadata: AttachmentsMetadata[] = [];
for (let i = 0; i < numberOfAttachments; i++) {
const metadata: AttachmentsMetadata = {
ID: i.toString(),
Disposition: ATTACHMENT_DISPOSITION.ATTACHMENT,
MIMEType: mimeType,
Size: 200000,
Name: `Attachment-${i}.${extension}`,
};
attachmentsMetadata.push(metadata);
}
return attachmentsMetadata;
};
const setup = async (
attachmentsMetadata: AttachmentsMetadata[],
numAttachments: number,
{
AddressID,
fromAddress,
fromKeys,
showAttachmentThumbnails = true,
}: { AddressID: string; fromAddress: string; fromKeys: GeneratedKey; showAttachmentThumbnails?: boolean }
) => {
const element = {
ID: 'conversationID',
Subject: 'Conversation thumbnails',
Time: Date.now(),
Senders: [{ Address: 'sender@proton.me', Name: 'Sender' }],
Recipients: [{ Address: 'recipient@proton.me', Name: 'Recipient' }],
Labels: [{ ID: MAILBOX_LABEL_IDS.INBOX }],
NumAttachments: numAttachments,
AttachmentsMetadata: attachmentsMetadata,
} as Conversation;
return render(
<ItemColumnLayout
labelID={MAILBOX_LABEL_IDS.INBOX}
element={element}
conversationMode={true}
showIcon={true}
senders={<>Sender</>}
breakpoints={mockDefaultBreakpoints}
unread={false}
onBack={jest.fn()}
isSelected={false}
showAttachmentThumbnails={showAttachmentThumbnails}
attachmentsMetadata={filterAttachmentToPreview(attachmentsMetadata)}
/>,
{
preloadedState: {
addresses: getModelState([getCompleteAddress({ ID: AddressID, Email: fromAddress })]),
addressKeys: getAddressKeyCache(AddressID, fromKeys),
},
}
);
};
describe('ItemAttachmentThumbnails', () => {
const AddressID = 'AddressID';
const fromAddress = 'me@home.net';
let fromKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
addApiKeys(false, fromAddress, []);
});
beforeEach(async () => {
clearAll();
fromKeys = await generateKeys('me', fromAddress);
});
afterEach(() => clearAll());
afterAll(async () => {
await releaseCryptoProxy();
});
it('should not display attachment thumbnails', async () => {
const elementTotalAttachments = 0;
// The conversation has no attachments.
await setup([], elementTotalAttachments, { AddressID, fromKeys, fromAddress });
// No attachment thumbnail displayed
expect(screen.queryByText(`Attachment-`)).toBeNull();
// +X should not be displayed
expect(screen.queryByTestId('attachment-thumbnail:other-attachment-number')).toBeNull();
// Paper clip icon is not displayed
expect(screen.queryByTestId('item-attachment-icon-paper-clip')).toBeNull();
});
it('should display attachment thumbnails', async () => {
const numberOfReceivedMetadata = 5;
const attachmentsMetadata = generateAttachmentsMetadata(numberOfReceivedMetadata);
// We received the metadata for 5 attachments, and we can display 2 thumbnails
await setup(attachmentsMetadata, numberOfReceivedMetadata, { AddressID, fromKeys, fromAddress });
const items = screen.getAllByTestId('attachment-thumbnail');
// 2 first attachments are displayed
for (let i = 0; i < MAX_COLUMN_ATTACHMENT_THUMBNAILS; i++) {
expect(items[i].textContent).toEqual(`Attachment-${i}.png`);
}
// Other received attachments are not displayed since we cannot display them
for (let i = MAX_COLUMN_ATTACHMENT_THUMBNAILS; i < numberOfReceivedMetadata; i++) {
// use title because text is split in multiple elements
expect(screen.queryByTitle(`Attachment-${i}.png`)).toBeNull();
}
// Since we have 5 attachment metadata, and we display 2 of them. So we should see +3
screen.getByText(`+${numberOfReceivedMetadata - MAX_COLUMN_ATTACHMENT_THUMBNAILS}`);
// Paper clip icon is displayed (in row mode paper clip can be rendered twice because of responsive)
screen.getAllByTestId('item-attachment-icon-paper-clip');
});
it('should not display +X attachment', async () => {
const numberOfReceivedMetadata = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numberOfReceivedMetadata);
// The conversation has 1 attachment in total.
// We received the metadata for 1 of them, which will display 1 thumbnail
await setup(attachmentsMetadata, numberOfReceivedMetadata, { AddressID, fromKeys, fromAddress });
const items = screen.getAllByTestId('attachment-thumbnail');
// 2 first attachments are displayed
for (let i = 0; i < numberOfReceivedMetadata; i++) {
// use title because text is split in multiple elements
expect(items[i].textContent).toEqual(`Attachment-${i}.png`);
}
// No other thumbnail element is displayed
for (let i = numberOfReceivedMetadata; i < MAX_COLUMN_ATTACHMENT_THUMBNAILS; i++) {
expect(screen.queryByTitle(`Attachment-${i}.png`)).toBeNull();
}
// +X should not be displayed
expect(screen.queryByTestId('attachment-thumbnail:other-attachment-number')).toBeNull();
// Paper clip icon is displayed (in row mode paper clip can be rendered twice because of responsive)
screen.getAllByTestId('item-attachment-icon-paper-clip');
});
it('should should display paper clip icon and no thumbnails when no attachment can be previewed', async () => {
const elementTotalAttachments = 10;
// The conversation has 10 attachment in total.
// We received no metadata, so no thumbnail will be displayed
await setup([], elementTotalAttachments, { AddressID, fromKeys, fromAddress });
// No attachment thumbnail displayed
expect(screen.queryByText(`Attachment-`)).toBeNull();
// +X should not be displayed
expect(screen.queryByTestId('attachment-thumbnail:other-attachment-number')).toBeNull();
// Paper clip icons are displayed
expect(screen.getAllByTestId('item-attachment-icon-paper-clip').length).toBe(2);
});
it('should display the expected attachment icon', async () => {
const numAttachments = 2;
const attachmentsMetadata: AttachmentsMetadata[] = [
{
ID: '0',
Disposition: ATTACHMENT_DISPOSITION.ATTACHMENT,
MIMEType: 'image/png',
Size: 200000,
Name: `Attachment-0.png`,
},
{
ID: '1',
Disposition: ATTACHMENT_DISPOSITION.ATTACHMENT,
MIMEType: 'application/pdf',
Size: 200000,
Name: `Attachment-1.pdf`,
},
];
const icons = ['sm-image', 'sm-pdf'];
const extensions = ['png', 'pdf'];
await setup(attachmentsMetadata, numAttachments, { AddressID, fromKeys, fromAddress });
const items = screen.getAllByTestId('attachment-thumbnail');
for (let i = 0; i < 2; i++) {
expect(items[i].textContent).toEqual(`Attachment-${i}.${extensions[i]}`);
assertIcon(items[i].querySelector('svg'), icons[i], undefined, 'mime');
}
});
});
describe('ItemAttachmentThumbnails - Preview', () => {
const AddressID = 'AddressID';
const fromAddress = 'me@home.net';
let fromKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
// Mock feature flag
// TODO update when we'll have a better solution
addApiKeys(false, fromAddress, []);
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(async () => {
clearAll();
fromKeys = await generateKeys('me', fromAddress);
});
afterEach(async () => {
clearAll();
});
const mockAttachmentThumbnailsAPICalls = async (
attachmentsMetadata: AttachmentsMetadata[],
keys: GeneratedKey,
decryptShouldFail = false
) => {
addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [] } }));
return Promise.all(
attachmentsMetadata.map(async (metadata) => {
const { ID, Name, MIMEType } = metadata;
const attachmentID = ID;
const attachmentName = Name;
const attachmentType = MIMEType;
const file = new File([new Blob([fileContent])], attachmentName, { type: attachmentType });
const attachmentPackets = await encryptAttachment(fileContent, file, false, keys.publicKeys, []);
// Trigger a fail during decrypt (when necessary) to test some scenarios (e.g. decryption failed)
const attachmentKeyPackets = decryptShouldFail ? new Uint8Array() : attachmentPackets.keys;
const concatenatedPackets = mergeUint8Arrays(
[attachmentPackets.data, attachmentKeyPackets, attachmentPackets.signature].filter(isTruthy)
);
const attachmentSpy = jest.fn(() => concatenatedPackets);
const attachmentMetadataSpy = jest.fn(() => ({
Attachment: {
KeyPackets: arrayToBase64(attachmentKeyPackets),
Sender: { Address: fromAddress },
AddressID,
},
}));
addApiMock(`mail/v4/attachments/${attachmentID}`, attachmentSpy);
addApiMock(`mail/v4/attachments/${attachmentID}/metadata`, attachmentMetadataSpy);
return {
attachmentSpy,
attachmentMetadataSpy,
attachmentPackets,
};
})
);
};
const waitForVisibleAttachmentPreview = async (
attachmentMetadata: AttachmentsMetadata,
preview: HTMLElement = screen.getByTestId('file-preview')
) => {
expect(preview.textContent).toMatch(new RegExp(attachmentMetadata.Name));
// File content is visible
await waitFor(() => expect(preview.textContent).toMatch(new RegExp(fileContent)));
};
it('should preview an attachment that was already in Redux state', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const { attachment } = await createAttachment(
{
ID: attachmentsMetadata[0].ID,
Name: attachmentsMetadata[0].Name,
MIMEType: attachmentsMetadata[0].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
// Mock to check that if attachment is in the state, no api call is done
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys);
const { store } = await setup(attachmentsMetadata, numAttachments, { AddressID, fromKeys, fromAddress });
store.dispatch(
addAttachment({
ID: attachment.ID as string,
attachment: {
data: attachment.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
const preview = screen.getByTestId('file-preview');
await waitFor(() => expect(preview.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name)));
expect(mocks[0].attachmentSpy).not.toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).not.toHaveBeenCalled();
});
it('should preview an attachment that was not in Redux state', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys);
await setup(attachmentsMetadata, numAttachments, { AddressID, fromKeys, fromAddress });
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
await waitForVisibleAttachmentPreview(attachmentsMetadata[0]);
});
it('should be possible to switch between attachments when Redux state is filled', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 2;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const { attachment: attachment1 } = await createAttachment(
{
ID: attachmentsMetadata[0].ID,
Name: attachmentsMetadata[0].Name,
MIMEType: attachmentsMetadata[0].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
const { attachment: attachment2 } = await createAttachment(
{
ID: attachmentsMetadata[1].ID,
Name: attachmentsMetadata[1].Name,
MIMEType: attachmentsMetadata[1].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
const { store } = await setup(attachmentsMetadata, numAttachments, { AddressID, fromKeys, fromAddress });
store.dispatch(
addAttachment({
ID: attachment1.ID as string,
attachment: {
data: attachment1.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
store.dispatch(
addAttachment({
ID: attachment2.ID as string,
attachment: {
data: attachment2.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
const item = screen.getAllByTestId('attachment-thumbnail');
// Preview first item
fireEvent.click(item[0]);
const preview = screen.getByTestId('file-preview');
await waitFor(() => expect(preview.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name)));
// Switch to next item
const nextButton = screen.getByTestId('file-preview:navigation:next');
fireEvent.click(nextButton);
await waitFor(() => expect(preview.textContent).toMatch(new RegExp(attachmentsMetadata[1].Name)));
});
it('should show a message instead of preview when attachment decryption failed', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys, true);
await setup(attachmentsMetadata, numAttachments, { AddressID, fromKeys, fromAddress });
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
expect(preview.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// File preview cannot be displayed because decryption failed
await waitFor(() =>
expect(preview.textContent).toMatch(new RegExp('Preview for this file type is not supported'))
);
});
it('should be possible to switch between attachments when not present in Redux state', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 2;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys);
await setup(attachmentsMetadata, numAttachments, { AddressID, fromKeys, fromAddress });
const item = screen.getAllByTestId('attachment-thumbnail');
// Preview first item
fireEvent.click(item[0]);
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
await waitForVisibleAttachmentPreview(attachmentsMetadata[0], preview);
// Switch to next item
const nextButton = screen.getByTestId('file-preview:navigation:next');
fireEvent.click(nextButton);
expect(mocks[1].attachmentSpy).toHaveBeenCalled();
expect(mocks[1].attachmentMetadataSpy).toHaveBeenCalled();
await waitForVisibleAttachmentPreview(attachmentsMetadata[1], preview);
});
it('should download the attachment', async () => {
// Promise to ensure we wait until the async onClick callback is executed before carrying out the final checks
const downloadFileCalled = new Promise<void>((resolve) => {
mockDownloadFile.mockImplementation(() => resolve());
});
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const { attachment } = await createAttachment(
{
ID: attachmentsMetadata[0].ID,
Name: attachmentsMetadata[0].Name,
MIMEType: attachmentsMetadata[0].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
const { store } = await setup(attachmentsMetadata, numAttachments, { AddressID, fromKeys, fromAddress });
store.dispatch(
addAttachment({
ID: attachment.ID as string,
attachment: {
data: attachment.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
const preview = screen.getByTestId('file-preview');
await waitFor(() => expect(preview.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name)));
const downloadButton = screen.getByTestId('file-preview:actions:download');
fireEvent.click(downloadButton);
await act(() => downloadFileCalled);
expect(downloadFile).toHaveBeenCalled();
});
it('should download a pgp attachment when decryption failed', async () => {
// Promise to ensure we wait until the async onClick callback is executed before carrying out the final checks
const downloadFileCalled = new Promise<void>((resolve) => {
mockDownloadFile.mockImplementation(() => resolve());
});
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys, true);
await setup(attachmentsMetadata, numAttachments, { AddressID, fromKeys, fromAddress });
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
expect(preview.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// File preview cannot be displayed because decryption failed
await waitFor(() =>
expect(preview.textContent).toMatch(new RegExp('Preview for this file type is not supported'))
);
// Download the encrypted attachment
const downloadButton = screen.getByTestId('file-preview:actions:download');
fireEvent.click(downloadButton);
await act(() => downloadFileCalled);
const blob = new Blob([mocks[0].attachmentPackets.data], {
type: 'application/pgp-encrypted',
});
await waitFor(() => expect(downloadFile).toHaveBeenCalledTimes(1));
expect(downloadFile).toHaveBeenCalledWith(blob, 'Attachment-0.txt.pgp');
});
});
``` | /content/code_sandbox/applications/mail/src/app/components/list/ItemAttachmentThumbnails.test.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 4,548 |
```xml
import { Droppable } from '@hello-pangea/dnd';
import { Box, Stack, Typography } from '@mui/material';
import { Deal } from '../types';
import { DealCard } from './DealCard';
import { useConfigurationContext } from '../root/ConfigurationContext';
import { findDealLabel } from './deal';
export const DealColumn = ({
stage,
deals,
}: {
stage: string;
deals: Deal[];
}) => {
const totalAmount = deals.reduce((sum, deal) => sum + deal.amount, 0);
const { dealStages } = useConfigurationContext();
return (
<Box
sx={{
flex: 1,
paddingTop: '8px',
paddingBottom: '16px',
bgcolor: '#eaeaee',
'&:first-of-type': {
paddingLeft: '5px',
borderTopLeftRadius: 5,
},
'&:last-of-type': {
paddingRight: '5px',
borderTopRightRadius: 5,
},
}}
>
<Stack alignItems="center">
<Typography variant="subtitle1">
{findDealLabel(dealStages, stage)}
</Typography>
<Typography
variant="subtitle1"
color="text.secondary"
fontSize="small"
>
{totalAmount.toLocaleString('en-US', {
notation: 'compact',
style: 'currency',
currency: 'USD',
currencyDisplay: 'narrowSymbol',
minimumSignificantDigits: 3,
})}
</Typography>
</Stack>
<Droppable droppableId={stage}>
{(droppableProvided, snapshot) => (
<Box
ref={droppableProvided.innerRef}
{...droppableProvided.droppableProps}
className={
snapshot.isDraggingOver ? ' isDraggingOver' : ''
}
sx={{
display: 'flex',
flexDirection: 'column',
borderRadius: 1,
padding: '5px',
'&.isDraggingOver': {
bgcolor: '#dadadf',
},
}}
>
{deals.map((deal, index) => (
<DealCard key={deal.id} deal={deal} index={index} />
))}
{droppableProvided.placeholder}
</Box>
)}
</Droppable>
</Box>
);
};
``` | /content/code_sandbox/examples/crm/src/deals/DealColumn.tsx | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 511 |
```xml
// See LICENSE in the project root for license information.
import { DependencySpecifier } from '../DependencySpecifier';
describe(DependencySpecifier.name, () => {
it('parses a simple version', () => {
const specifier = new DependencySpecifier('dep', '1.2.3');
expect(specifier).toMatchInlineSnapshot(`
DependencySpecifier {
"aliasTarget": undefined,
"packageName": "dep",
"specifierType": "Version",
"versionSpecifier": "1.2.3",
}
`);
});
it('parses a range version', () => {
const specifier = new DependencySpecifier('dep', '^1.2.3');
expect(specifier).toMatchInlineSnapshot(`
DependencySpecifier {
"aliasTarget": undefined,
"packageName": "dep",
"specifierType": "Range",
"versionSpecifier": "^1.2.3",
}
`);
});
it('parses an alias version', () => {
const specifier = new DependencySpecifier('dep', 'npm:alias-target@1.2.3');
expect(specifier).toMatchInlineSnapshot(`
DependencySpecifier {
"aliasTarget": DependencySpecifier {
"aliasTarget": undefined,
"packageName": "alias-target",
"specifierType": "Version",
"versionSpecifier": "1.2.3",
},
"packageName": "dep",
"specifierType": "Alias",
"versionSpecifier": "npm:alias-target@1.2.3",
}
`);
});
it('parses a git version', () => {
const specifier = new DependencySpecifier('dep', 'git+path_to_url
expect(specifier).toMatchInlineSnapshot(`
DependencySpecifier {
"aliasTarget": undefined,
"packageName": "dep",
"specifierType": "Git",
"versionSpecifier": "git+path_to_url",
}
`);
});
it('parses a file version', () => {
const specifier = new DependencySpecifier('dep', 'file:foo.tar.gz');
expect(specifier).toMatchInlineSnapshot(`
DependencySpecifier {
"aliasTarget": undefined,
"packageName": "dep",
"specifierType": "File",
"versionSpecifier": "file:foo.tar.gz",
}
`);
});
it('parses a directory version', () => {
const specifier = new DependencySpecifier('dep', 'file:../foo/bar/');
expect(specifier).toMatchInlineSnapshot(`
DependencySpecifier {
"aliasTarget": undefined,
"packageName": "dep",
"specifierType": "Directory",
"versionSpecifier": "file:../foo/bar/",
}
`);
});
it('parses a remote version', () => {
const specifier = new DependencySpecifier('dep', 'path_to_url
expect(specifier).toMatchInlineSnapshot(`
DependencySpecifier {
"aliasTarget": undefined,
"packageName": "dep",
"specifierType": "Remote",
"versionSpecifier": "path_to_url",
}
`);
});
describe('Workspace protocol', () => {
it('correctly parses a "workspace:*" version', () => {
const specifier = new DependencySpecifier('dep', 'workspace:*');
expect(specifier).toMatchInlineSnapshot(`
DependencySpecifier {
"aliasTarget": undefined,
"packageName": "dep",
"specifierType": "Workspace",
"versionSpecifier": "*",
}
`);
});
it('correctly parses a "workspace:^1.0.0" version', () => {
const specifier = new DependencySpecifier('dep', 'workspace:^1.0.0');
expect(specifier).toMatchInlineSnapshot(`
DependencySpecifier {
"aliasTarget": undefined,
"packageName": "dep",
"specifierType": "Workspace",
"versionSpecifier": "^1.0.0",
}
`);
});
it('correctly parses a "workspace:alias@1.2.3" version', () => {
const specifier = new DependencySpecifier('dep', 'workspace:alias-target@*');
expect(specifier).toMatchInlineSnapshot(`
DependencySpecifier {
"aliasTarget": DependencySpecifier {
"aliasTarget": undefined,
"packageName": "alias-target",
"specifierType": "Range",
"versionSpecifier": "*",
},
"packageName": "dep",
"specifierType": "Workspace",
"versionSpecifier": "alias-target@*",
}
`);
});
});
});
``` | /content/code_sandbox/libraries/rush-lib/src/logic/test/DependencySpecifier.test.ts | xml | 2016-09-30T00:28:20 | 2024-08-16T18:54:35 | rushstack | microsoft/rushstack | 5,790 | 928 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="path_to_url"
android:ordering="together" >
<objectAnimator
android:propertyName="translationY"
android:duration="1"
android:valueFrom="-50"
android:valueTo="-50" />
<objectAnimator
android:propertyName="alpha"
android:duration="1"
android:valueFrom="0.0"
android:valueTo="0.0" />
<objectAnimator
android:propertyName="translationY"
android:interpolator="@android:anim/bounce_interpolator"
android:startOffset="900"
android:duration="500"
android:valueFrom="-50"
android:valueTo="0" />
<objectAnimator
android:propertyName="alpha"
android:startOffset="900"
android:duration="150"
android:valueFrom="0.0"
android:valueTo="1.0" />
</set>
``` | /content/code_sandbox/app/src/main/res/animator/weather_hail_2.xml | xml | 2016-02-21T04:39:19 | 2024-08-16T13:35:51 | GeometricWeather | WangDaYeeeeee/GeometricWeather | 2,420 | 211 |
```xml
/** @jsx jsx */
import { Transforms } from 'slate'
import { jsx } from '../../..'
export const input = (
<editor>
<block>
wo
<anchor />
rd
<focus />
</block>
</editor>
)
export const run = editor => {
Transforms.wrapNodes(editor, <block new />, { split: true })
}
export const output = (
<editor>
<block>wo</block>
<block new>
<block>
<anchor />
rd
<focus />
</block>
</block>
</editor>
)
``` | /content/code_sandbox/packages/slate/test/transforms/wrapNodes/split-block/block-end.tsx | xml | 2016-06-18T01:52:42 | 2024-08-16T18:43:42 | slate | ianstormtaylor/slate | 29,492 | 134 |
```xml
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable max-classes-per-file */
import {
CancellationToken,
MessageItem,
MessageOptions,
Progress,
ProgressOptions,
QuickPick,
QuickInputButtons,
QuickPickItem,
QuickPickOptions,
TextEditor,
window,
Disposable,
QuickPickItemButtonEvent,
Uri,
TerminalShellExecutionStartEvent,
LogOutputChannel,
OutputChannel,
} from 'vscode';
import { createDeferred, Deferred } from '../utils/async';
import { Resource } from '../types';
import { getWorkspaceFolders } from './workspaceApis';
export function showTextDocument(uri: Uri): Thenable<TextEditor> {
return window.showTextDocument(uri);
}
export function showQuickPick<T extends QuickPickItem>(
items: readonly T[] | Thenable<readonly T[]>,
options?: QuickPickOptions,
token?: CancellationToken,
): Thenable<T | undefined> {
return window.showQuickPick(items, options, token);
}
export function createQuickPick<T extends QuickPickItem>(): QuickPick<T> {
return window.createQuickPick<T>();
}
export function showErrorMessage<T extends string>(message: string, ...items: T[]): Thenable<T | undefined>;
export function showErrorMessage<T extends string>(
message: string,
options: MessageOptions,
...items: T[]
): Thenable<T | undefined>;
export function showErrorMessage<T extends MessageItem>(message: string, ...items: T[]): Thenable<T | undefined>;
export function showErrorMessage<T extends MessageItem>(
message: string,
options: MessageOptions,
...items: T[]
): Thenable<T | undefined>;
export function showErrorMessage<T>(message: string, ...items: any[]): Thenable<T | undefined> {
return window.showErrorMessage(message, ...items);
}
export function showWarningMessage<T extends string>(message: string, ...items: T[]): Thenable<T | undefined>;
export function showWarningMessage<T extends string>(
message: string,
options: MessageOptions,
...items: T[]
): Thenable<T | undefined>;
export function showWarningMessage<T extends MessageItem>(message: string, ...items: T[]): Thenable<T | undefined>;
export function showWarningMessage<T extends MessageItem>(
message: string,
options: MessageOptions,
...items: T[]
): Thenable<T | undefined>;
export function showWarningMessage<T>(message: string, ...items: any[]): Thenable<T | undefined> {
return window.showWarningMessage(message, ...items);
}
export function showInformationMessage<T extends string>(message: string, ...items: T[]): Thenable<T | undefined>;
export function showInformationMessage<T extends string>(
message: string,
options: MessageOptions,
...items: T[]
): Thenable<T | undefined>;
export function showInformationMessage<T extends MessageItem>(message: string, ...items: T[]): Thenable<T | undefined>;
export function showInformationMessage<T extends MessageItem>(
message: string,
options: MessageOptions,
...items: T[]
): Thenable<T | undefined>;
export function showInformationMessage<T>(message: string, ...items: any[]): Thenable<T | undefined> {
return window.showInformationMessage(message, ...items);
}
export function withProgress<R>(
options: ProgressOptions,
task: (progress: Progress<{ message?: string; increment?: number }>, token: CancellationToken) => Thenable<R>,
): Thenable<R> {
return window.withProgress(options, task);
}
export function getActiveTextEditor(): TextEditor | undefined {
const { activeTextEditor } = window;
return activeTextEditor;
}
export function onDidChangeActiveTextEditor(handler: (e: TextEditor | undefined) => void): Disposable {
return window.onDidChangeActiveTextEditor(handler);
}
export function onDidStartTerminalShellExecution(handler: (e: TerminalShellExecutionStartEvent) => void): Disposable {
return window.onDidStartTerminalShellExecution(handler);
}
export enum MultiStepAction {
Back = 'Back',
Cancel = 'Cancel',
Continue = 'Continue',
}
export async function showQuickPickWithBack<T extends QuickPickItem>(
items: readonly T[],
options?: QuickPickOptions,
token?: CancellationToken,
itemButtonHandler?: (e: QuickPickItemButtonEvent<T>) => void,
): Promise<T | T[] | undefined> {
const quickPick: QuickPick<T> = window.createQuickPick<T>();
const disposables: Disposable[] = [quickPick];
quickPick.items = items;
quickPick.buttons = [QuickInputButtons.Back];
quickPick.canSelectMany = options?.canPickMany ?? false;
quickPick.ignoreFocusOut = options?.ignoreFocusOut ?? false;
quickPick.matchOnDescription = options?.matchOnDescription ?? false;
quickPick.matchOnDetail = options?.matchOnDetail ?? false;
quickPick.placeholder = options?.placeHolder;
quickPick.title = options?.title;
const deferred = createDeferred<T | T[] | undefined>();
disposables.push(
quickPick,
quickPick.onDidTriggerButton((item) => {
if (item === QuickInputButtons.Back) {
deferred.reject(MultiStepAction.Back);
quickPick.hide();
}
}),
quickPick.onDidAccept(() => {
if (!deferred.completed) {
if (quickPick.canSelectMany) {
deferred.resolve(quickPick.selectedItems.map((item) => item));
} else {
deferred.resolve(quickPick.selectedItems[0]);
}
quickPick.hide();
}
}),
quickPick.onDidHide(() => {
if (!deferred.completed) {
deferred.resolve(undefined);
}
}),
quickPick.onDidTriggerItemButton((e) => {
if (itemButtonHandler) {
itemButtonHandler(e);
}
}),
);
if (token) {
disposables.push(
token.onCancellationRequested(() => {
quickPick.hide();
}),
);
}
quickPick.show();
try {
return await deferred.promise;
} finally {
disposables.forEach((d) => d.dispose());
}
}
export class MultiStepNode {
constructor(
public previous: MultiStepNode | undefined,
public readonly current: (context?: MultiStepAction) => Promise<MultiStepAction>,
public next: MultiStepNode | undefined,
) {}
public static async run(step: MultiStepNode, context?: MultiStepAction): Promise<MultiStepAction> {
let nextStep: MultiStepNode | undefined = step;
let flowAction = await nextStep.current(context);
while (nextStep !== undefined) {
if (flowAction === MultiStepAction.Cancel) {
return flowAction;
}
if (flowAction === MultiStepAction.Back) {
nextStep = nextStep?.previous;
}
if (flowAction === MultiStepAction.Continue) {
nextStep = nextStep?.next;
}
if (nextStep) {
flowAction = await nextStep?.current(flowAction);
}
}
return flowAction;
}
}
export function createStepBackEndNode<T>(deferred?: Deferred<T>): MultiStepNode {
return new MultiStepNode(
undefined,
async () => {
if (deferred) {
// This is to ensure we don't leave behind any pending promises.
deferred.reject(MultiStepAction.Back);
}
return Promise.resolve(MultiStepAction.Back);
},
undefined,
);
}
export function createStepForwardEndNode<T>(deferred?: Deferred<T>, result?: T): MultiStepNode {
return new MultiStepNode(
undefined,
async () => {
if (deferred) {
// This is to ensure we don't leave behind any pending promises.
deferred.resolve(result);
}
return Promise.resolve(MultiStepAction.Back);
},
undefined,
);
}
export function getActiveResource(): Resource {
const editor = window.activeTextEditor;
if (editor && !editor.document.isUntitled) {
return editor.document.uri;
}
const workspaces = getWorkspaceFolders();
return Array.isArray(workspaces) && workspaces.length > 0 ? workspaces[0].uri : undefined;
}
export function createOutputChannel(name: string, languageId?: string): OutputChannel {
return window.createOutputChannel(name, languageId);
}
export function createLogOutputChannel(name: string, options: { log: true }): LogOutputChannel {
return window.createOutputChannel(name, options);
}
``` | /content/code_sandbox/src/client/common/vscodeApis/windowApis.ts | xml | 2016-01-19T10:50:01 | 2024-08-12T21:05:24 | pythonVSCode | DonJayamanne/pythonVSCode | 2,078 | 1,810 |
```xml
import {Component, ElementRef, Input, OnChanges, ViewChild,} from '@angular/core';
import {PhotoDTO} from '../../../../../common/entities/PhotoDTO';
import {Dimension, IRenderable} from '../../../model/IRenderable';
import {GalleryMapLightboxComponent} from './lightbox/lightbox.map.gallery.component';
import {FileDTO} from '../../../../../common/entities/FileDTO';
import {MapService} from './map.service';
import {Config} from '../../../../../common/config/public/Config';
import {LatLngLiteral, Map, MapOptions, Marker, marker, tileLayer, TileLayer} from 'leaflet';
import {ThemeService} from '../../../model/theme.service';
import {Subscription} from 'rxjs';
import {MarkerFactory} from './MarkerFactory';
@Component({
selector: 'app-gallery-map',
templateUrl: './map.gallery.component.html',
styleUrls: ['./map.gallery.component.css'],
})
export class GalleryMapComponent implements OnChanges, IRenderable {
@Input() photos: PhotoDTO[];
@Input() gpxFiles: FileDTO[];
@ViewChild(GalleryMapLightboxComponent, {static: false})
mapLightbox: GalleryMapLightboxComponent;
@ViewChild('map', {static: false}) mapElement: ElementRef;
leafletMap: Map;
layers: { light: TileLayer, dark: TileLayer };
options: MapOptions = {
zoomControl: false,
dragging: false,
keyboard: false,
tap: false,
doubleClickZoom: false,
boxZoom: false,
zoom: 0,
center: [0, 0],
};
markerLayer: Marker[] = [];
darkModeSubscription: Subscription;
constructor(public mapService: MapService,
private themeService: ThemeService) {
this.initThemeModes();
}
ngOnDestroy(): void {
this.darkModeSubscription.unsubscribe();
}
initThemeModes() {
this.layers = {
'light': tileLayer(this.mapService.MapLayer.url, {
attribution: this.mapService.ShortAttributions,
}),
'dark':
tileLayer(this.mapService.DarkMapLayer.url, {
attribution: this.mapService.ShortAttributions,
})
};
if (this.themeService.darkMode.value) {
this.options.layers = [this.layers.dark];
} else {
this.options.layers = [this.layers.light];
}
// update map theme on dark theme
this.darkModeSubscription = this.themeService.darkMode.subscribe((isDark) => {
if (!this.leafletMap) {
return;
}
if (isDark) {
if (this.leafletMap.hasLayer(this.layers.dark)) {
return;
}
this.leafletMap.removeLayer(this.layers.light);
this.leafletMap.addLayer(this.layers.dark);
} else {
if (this.leafletMap.hasLayer(this.layers.light)) {
return;
}
this.leafletMap.removeLayer(this.layers.dark);
this.leafletMap.addLayer(this.layers.light);
}
});
}
onMapReady(map: Map): void {
this.leafletMap = map;
if (!this.leafletMap) {
return;
}
if (this.markerLayer.length > 0) {
this.leafletMap.setView(this.markerLayer[0].getLatLng(), 99);
this.leafletMap.fitBounds(
this.markerLayer.map(
(mp): [number, number] =>
[mp.getLatLng().lat, mp.getLatLng().lng] as [number, number]
)
);
}
this.leafletMap.setZoom(0);
}
ngOnChanges(): void {
this.markerLayer = this.photos
.filter((p): number => {
return (
p.metadata &&
p.metadata.positionData &&
p.metadata.positionData.GPSData &&
p.metadata.positionData.GPSData.latitude &&
p.metadata.positionData.GPSData.longitude
);
})
.slice(0, Config.Map.maxPreviewMarkers)
.map((p): Marker => {
return marker({
lat: p.metadata.positionData.GPSData.latitude,
lng: p.metadata.positionData.GPSData.longitude,
} as LatLngLiteral).setIcon(MarkerFactory.defIconSmall);
});
if (this.leafletMap && this.markerLayer.length > 0) {
this.options.center = this.markerLayer[0].getLatLng();
this.leafletMap.setView(this.markerLayer[0].getLatLng(), 99);
this.leafletMap.fitBounds(
this.markerLayer.map(
(mp): [number, number] =>
[mp.getLatLng().lat, mp.getLatLng().lng] as [number, number]
)
);
this.leafletMap.setZoom(0);
}
}
click(): void {
this.mapLightbox.show(this.getDimension());
}
public getDimension(): Dimension {
return {
top: this.mapElement.nativeElement.parentElement.offsetParent.offsetTop,
left: this.mapElement.nativeElement.parentElement.offsetLeft,
width: this.mapElement.nativeElement.offsetWidth,
height: this.mapElement.nativeElement.offsetHeight,
} as Dimension;
}
}
``` | /content/code_sandbox/src/frontend/app/ui/gallery/map/map.gallery.component.ts | xml | 2016-03-12T11:46:41 | 2024-08-16T19:56:44 | pigallery2 | bpatrik/pigallery2 | 1,727 | 1,080 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="path_to_url">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{8A5B637C-E4FF-4145-B887-9347020100F4}</ProjectGuid>
<ProjectTypeGuids>{6BC8ED88-2882-458C-8E55-DFD12B67127B};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<RootNamespace>monotouch</RootNamespace>
<AssemblyName>monotouch</AssemblyName>
<UseMSBuildEngine>True</UseMSBuildEngine>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>IPHONE;MINIMAL</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GenerateDocumentation>True</GenerateDocumentation>
<NoWarn>3021,3014,3003</NoWarn>
<MtouchLink>SdkOnly</MtouchLink>
<MtouchHttpClientHandler>HttpClientHandler</MtouchHttpClientHandler>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<MtouchLink>SdkOnly</MtouchLink>
<MtouchHttpClientHandler>HttpClientHandler</MtouchHttpClientHandler>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\iOS\Xamarin.MonoTouch.CSharp.targets" />
<PropertyGroup>
<CscToolExe>$(MSBuildProjectDirectory)\..\src\custom-make.sh</CscToolExe>
</PropertyGroup>
<ItemGroup>
<None Include="Makefile" />
<None Include="xamarin\main.h" />
<None Include="xamarin\mono-runtime.h" />
<None Include="xamarin\runtime.h" />
<None Include="xamarin\trampolines.h" />
<None Include="xamarin\xamarin.h" />
<None Include="bindings.m" />
<None Include="Delegates.cs.t4" />
<None Include="delegates.h" />
<None Include="delegates.h.t4" />
<None Include="delegates.inc" />
<None Include="delegates.inc.t4" />
<None Include="delegates.t4" />
<None Include="exports.t4" />
<None Include="mono-runtime.h.t4" />
<None Include="mono-runtime.m" />
<None Include="mono-runtime.m.t4" />
<None Include="monotouch-debug.h" />
<None Include="monotouch-debug.m" />
<None Include="monotouch-main.m" />
<None Include="xamarin-support.m" />
<None Include="product.h" />
<None Include="README.md" />
<None Include="runtime-internal.h" />
<None Include="runtime.m" />
<None Include="shared.h" />
<None Include="shared.m" />
<None Include="trampolines.m" />
<None Include="Delegates.generated.cs" />
<None Include="trampolines-internal.h" />
<None Include="trampolines-invoke.m" />
<None Include="trampolines-x86_64-asm.s" />
<None Include="trampolines-x86_64.m" />
<None Include="extension-main.m" />
<None Include="slinked-list.h" />
<None Include="trampolines-x86_64.h" />
<None Include="monotouch-support.h" />
<None Include="bindings.h" />
<None Include="trampolines-i386-asm.s" />
<None Include="trampolines-i386.h" />
<None Include="trampolines-i386.m" />
<None Include="trampolines-varargs.h" />
<None Include="trampolines-varargs.m" />
<None Include="trampolines-x86_64-objc_msgSendSuper.s" />
<None Include="trampolines-x86_64-objc_msgSend.s" />
<None Include="trampolines-x86_64-objc_msgSend-post.inc" />
<None Include="trampolines-x86_64-objc_msgSend-copyframe.inc" />
<None Include="trampolines-x86_64-objc_msgSend-pre.inc" />
<None Include="trampolines-x86_64-objc_msgSend_stret.s" />
<None Include="trampolines-x86_64-objc_msgSendSuper_stret.s" />
<None Include="trampolines-i386-objc_msgSend.s" />
<None Include="trampolines-i386-objc_msgSendSuper.s" />
<None Include="trampolines-i386-objc_msgSend_stret.s" />
<None Include="trampolines-i386-objc_msgSendSuper_stret.s" />
<None Include="trampolines-i386-objc_msgSend-copyframe.inc" />
<None Include="trampolines-i386-objc_msgSend-post.inc" />
<None Include="trampolines-i386-objc_msgSend-pre.inc" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/runtime/libmonotouch.csproj | xml | 2016-04-20T18:24:26 | 2024-08-16T13:29:19 | xamarin-macios | xamarin/xamarin-macios | 2,436 | 1,416 |
```xml
import type {ESLint, Linter} from 'eslint';
declare const eslintPluginUnicorn: ESLint.Plugin & {
configs: {
recommended: Linter.Config;
all: Linter.Config;
'flat/all': Linter.FlatConfig;
'flat/recommended': Linter.FlatConfig;
};
};
export = eslintPluginUnicorn;
``` | /content/code_sandbox/index.d.ts | xml | 2016-04-09T07:48:04 | 2024-08-16T11:39:15 | eslint-plugin-unicorn | sindresorhus/eslint-plugin-unicorn | 4,109 | 78 |
```xml
import type { BloomFilter } from '../../../shared/lib/bloom-filter'
import type { Rewrite, CustomRoutes } from '../../../lib/load-custom-routes'
import devalue from 'next/dist/compiled/devalue'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import {
BUILD_MANIFEST,
MIDDLEWARE_BUILD_MANIFEST,
CLIENT_STATIC_FILES_PATH,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP,
SYSTEM_ENTRYPOINTS,
} from '../../../shared/lib/constants'
import type { BuildManifest } from '../../../server/get-page-files'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { spans } from './profiling-plugin'
import { Span } from '../../../trace'
type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> }
export type ClientBuildManifest = {
[key: string]: string[]
}
// Add the runtime ssg manifest file as a lazy-loaded file dependency.
// We also stub this file out for development mode (when it is not
// generated).
export const srcEmptySsgManifest = `self.__SSG_MANIFEST=new Set;self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`
// nodejs: '/static/<build id>/low-priority.js'
function buildNodejsLowPriorityPath(filename: string, buildId: string) {
return `${CLIENT_STATIC_FILES_PATH}/${buildId}/${filename}`
}
function createEdgeRuntimeManifest(originAssetMap: BuildManifest): string {
const manifestFilenames = ['_buildManifest.js', '_ssgManifest.js']
const assetMap: BuildManifest = {
...originAssetMap,
lowPriorityFiles: [],
}
const manifestDefCode = `self.__BUILD_MANIFEST = ${JSON.stringify(
assetMap,
null,
2
)};\n`
// edge lowPriorityFiles item: '"/static/" + process.env.__NEXT_BUILD_ID + "/low-priority.js"'.
// Since lowPriorityFiles is not fixed and relying on `process.env.__NEXT_BUILD_ID`, we'll produce code creating it dynamically.
const lowPriorityFilesCode =
`self.__BUILD_MANIFEST.lowPriorityFiles = [\n` +
manifestFilenames
.map((filename) => {
return `"/static/" + process.env.__NEXT_BUILD_ID + "/${filename}",\n`
})
.join(',') +
`\n];`
return manifestDefCode + lowPriorityFilesCode
}
function normalizeRewrite(item: {
source: string
destination: string
has?: any
}): CustomRoutes['rewrites']['beforeFiles'][0] {
return {
has: item.has,
source: item.source,
destination: item.destination,
}
}
export function normalizeRewritesForBuildManifest(
rewrites: CustomRoutes['rewrites']
): CustomRoutes['rewrites'] {
return {
afterFiles: rewrites.afterFiles
?.map(processRoute)
?.map((item) => normalizeRewrite(item)),
beforeFiles: rewrites.beforeFiles
?.map(processRoute)
?.map((item) => normalizeRewrite(item)),
fallback: rewrites.fallback
?.map(processRoute)
?.map((item) => normalizeRewrite(item)),
}
}
// This function takes the asset map generated in BuildManifestPlugin and creates a
// reduced version to send to the client.
export function generateClientManifest(
assetMap: BuildManifest,
rewrites: CustomRoutes['rewrites'],
clientRouterFilters?: {
staticFilter: ReturnType<BloomFilter['export']>
dynamicFilter: ReturnType<BloomFilter['export']>
},
compiler?: any,
compilation?: any
): string | undefined {
const compilationSpan = compilation
? spans.get(compilation)
: compiler
? spans.get(compiler)
: new Span({ name: 'client-manifest' })
const genClientManifestSpan = compilationSpan?.traceChild(
'NextJsBuildManifest-generateClientManifest'
)
return genClientManifestSpan?.traceFn(() => {
const clientManifest: ClientBuildManifest = {
__rewrites: normalizeRewritesForBuildManifest(rewrites) as any,
__routerFilterStatic: clientRouterFilters?.staticFilter as any,
__routerFilterDynamic: clientRouterFilters?.dynamicFilter as any,
}
const appDependencies = new Set(assetMap.pages['/_app'])
const sortedPageKeys = getSortedRoutes(Object.keys(assetMap.pages))
sortedPageKeys.forEach((page) => {
const dependencies = assetMap.pages[page]
if (page === '/_app') return
// Filter out dependencies in the _app entry, because those will have already
// been loaded by the client prior to a navigation event
const filteredDeps = dependencies.filter(
(dep) => !appDependencies.has(dep)
)
// The manifest can omit the page if it has no requirements
if (filteredDeps.length) {
clientManifest[page] = filteredDeps
}
})
// provide the sorted pages as an array so we don't rely on the object's keys
// being in order and we don't slow down look-up time for page assets
clientManifest.sortedPages = sortedPageKeys
return devalue(clientManifest)
})
}
export function getEntrypointFiles(entrypoint: any): string[] {
return (
entrypoint
?.getFiles()
.filter((file: string) => {
// We don't want to include `.hot-update.js` files into the initial page
return /(?<!\.hot-update)\.(js|css)($|\?)/.test(file)
})
.map((file: string) => file.replace(/\\/g, '/')) ?? []
)
}
export const processRoute = (r: Rewrite) => {
const rewrite = { ...r }
// omit external rewrite destinations since these aren't
// handled client-side
if (!rewrite?.destination?.startsWith('/')) {
delete (rewrite as any).destination
}
return rewrite
}
// This plugin creates a build-manifest.json for all assets that are being output
// It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production
export default class BuildManifestPlugin {
private buildId: string
private rewrites: CustomRoutes['rewrites']
private isDevFallback: boolean
private appDirEnabled: boolean
private clientRouterFilters?: Parameters<typeof generateClientManifest>[2]
constructor(options: {
buildId: string
rewrites: CustomRoutes['rewrites']
isDevFallback?: boolean
appDirEnabled: boolean
clientRouterFilters?: Parameters<typeof generateClientManifest>[2]
}) {
this.buildId = options.buildId
this.isDevFallback = !!options.isDevFallback
this.rewrites = {
beforeFiles: [],
afterFiles: [],
fallback: [],
}
this.appDirEnabled = options.appDirEnabled
this.clientRouterFilters = options.clientRouterFilters
this.rewrites.beforeFiles = options.rewrites.beforeFiles.map(processRoute)
this.rewrites.afterFiles = options.rewrites.afterFiles.map(processRoute)
this.rewrites.fallback = options.rewrites.fallback.map(processRoute)
}
createAssets(compiler: any, compilation: any, assets: any) {
const compilationSpan = spans.get(compilation) || spans.get(compiler)
const createAssetsSpan = compilationSpan?.traceChild(
'NextJsBuildManifest-createassets'
)
return createAssetsSpan?.traceFn(() => {
const entrypoints: Map<string, any> = compilation.entrypoints
const assetMap: DeepMutable<BuildManifest> = {
polyfillFiles: [],
devFiles: [],
ampDevFiles: [],
lowPriorityFiles: [],
rootMainFiles: [],
rootMainFilesTree: {},
pages: { '/_app': [] },
ampFirstPages: [],
}
const ampFirstEntryNames = ampFirstEntryNamesMap.get(compilation)
if (ampFirstEntryNames) {
for (const entryName of ampFirstEntryNames) {
const pagePath = getRouteFromEntrypoint(entryName)
if (!pagePath) {
continue
}
assetMap.ampFirstPages.push(pagePath)
}
}
const mainFiles = new Set(
getEntrypointFiles(entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_MAIN))
)
if (this.appDirEnabled) {
assetMap.rootMainFiles = [
...new Set(
getEntrypointFiles(
entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_MAIN_APP)
)
),
]
}
const compilationAssets: {
name: string
source: typeof sources.RawSource
info: object
}[] = compilation.getAssets()
assetMap.polyfillFiles = compilationAssets
.filter((p) => {
// Ensure only .js files are passed through
if (!p.name.endsWith('.js')) {
return false
}
return (
p.info && CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL in p.info
)
})
.map((v) => v.name)
assetMap.devFiles = getEntrypointFiles(
entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH)
).filter((file) => !mainFiles.has(file))
assetMap.ampDevFiles = getEntrypointFiles(
entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_AMP)
)
for (const entrypoint of compilation.entrypoints.values()) {
if (SYSTEM_ENTRYPOINTS.has(entrypoint.name)) continue
const pagePath = getRouteFromEntrypoint(entrypoint.name)
if (!pagePath) {
continue
}
const filesForPage = getEntrypointFiles(entrypoint)
assetMap.pages[pagePath] = [...new Set([...mainFiles, ...filesForPage])]
}
if (!this.isDevFallback) {
// Add the runtime build manifest file (generated later in this file)
// as a dependency for the app. If the flag is false, the file won't be
// downloaded by the client.
const buildManifestPath = buildNodejsLowPriorityPath(
'_buildManifest.js',
this.buildId
)
const ssgManifestPath = buildNodejsLowPriorityPath(
'_ssgManifest.js',
this.buildId
)
assetMap.lowPriorityFiles.push(buildManifestPath, ssgManifestPath)
assets[ssgManifestPath] = new sources.RawSource(srcEmptySsgManifest)
}
assetMap.pages = Object.keys(assetMap.pages)
.sort()
.reduce(
// eslint-disable-next-line
(a, c) => ((a[c] = assetMap.pages[c]), a),
{} as typeof assetMap.pages
)
let buildManifestName = BUILD_MANIFEST
if (this.isDevFallback) {
buildManifestName = `fallback-${BUILD_MANIFEST}`
}
assets[buildManifestName] = new sources.RawSource(
JSON.stringify(assetMap, null, 2)
)
assets[`server/${MIDDLEWARE_BUILD_MANIFEST}.js`] = new sources.RawSource(
`${createEdgeRuntimeManifest(assetMap)}`
)
if (!this.isDevFallback) {
const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`
assets[clientManifestPath] = new sources.RawSource(
`self.__BUILD_MANIFEST = ${generateClientManifest(
assetMap,
this.rewrites,
this.clientRouterFilters,
compiler,
compilation
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
)
}
return assets
})
}
apply(compiler: webpack.Compiler) {
compiler.hooks.make.tap('NextJsBuildManifest', (compilation) => {
compilation.hooks.processAssets.tap(
{
name: 'NextJsBuildManifest',
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
this.createAssets(compiler, compilation, assets)
}
)
})
return
}
}
``` | /content/code_sandbox/packages/next/src/build/webpack/plugins/build-manifest-plugin.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 2,686 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Nextcloud Talk - Android Client
~
-->
<lint>
<issue id="UnusedAttribute">
<ignore regexp="importantForAutofill"/>
<ignore regexp="autofillHints"/>
</issue>
<issue id="InvalidPackage">
<ignore path="**/freemarker-2.*.*.jar" />
<ignore path="**/nnio-0.2.jar"/>
<ignore path="**/bcpkix-jdk15on-1.69.jar" />
</issue>
<issue id="UnusedResources">
<ignore regexp="store_short_desc|store_full_desc|store_short_dev_desc|store_full_dev_desc" />
<ignore
regexp="screenshot_01_gridView|screenshot_02_listView|screenshot_03_drawer|screenshot_04_accounts|screenshot_05_autoUpload|screenshot_06_davdroid"/>
<ignore path="**/raw/encryption_key_words.txt" />
</issue>
<issue id="MissingQuantity">
<ignore path="**/values-ka-rGE/strings.xml"/>
<ignore path="**/values-ar/strings.xml" />
</issue>
<issue id="UnusedQuantity">
<ignore path="**/values-**/strings.xml" />
</issue>
<issue id="ExtraTranslation">
<ignore path="**/strings.xml"/>
<ignore path="**/values-b+en+001/strings.xml"/>
</issue>
<issue id="UnusedResources">
<ignore path="**/values-**/strings.xml" />
<ignore path="**/values/setup.xml" />
</issue>
<issue id="TypographyEllipsis">
<ignore path="**/values-**/strings.xml" />
</issue>
<issue id="Typos">
<ignore path="**/values-**/strings.xml" />
<ignore path="**/values/setup.xml" />
</issue>
<issue id="TrustAllX509TrustManager">
<ignore path="**/bouncycastle/est/jcajce/*.class" />
<ignore path="**/bcpkix-jdk15to18-1.**.jar" />
<ignore path="**/bcpkix-jdk18on-1.**.jar" />
</issue>
<issue id="RestrictedApi" severity="error">
<ignore path="build" />
</issue>
<issue id="NewApi" severity="error">
<ignore path="build" />
</issue>
<issue id="ObsoleteLintCustomCheck" severity="warning">
<ignore path="**/fragment-1.2.5/**/lint.jar" />
<ignore path="**/work-runtime-2.**/**/lint.jar" />
<ignore path="**/jetified-butterknife-runtime-10.**/**/lint.jar" />
<ignore path="**/jetified-dagger-lint-aar-2.**.**/**/lint.jar" />
<ignore path="**/jetified-annotation-experimental-1.**/**/lint.jar" />
<ignore path="**/jetified-firebase-installations**/**/lint.jar" />
<ignore path="**/appcompat-1.**/**/lint.jar" />
</issue>
</lint>
``` | /content/code_sandbox/app/lint.xml | xml | 2016-06-06T21:23:36 | 2024-08-16T18:22:36 | android | nextcloud/android | 4,122 | 749 |
```xml
<clickhouse>
<shutdown_wait_unfinished>30</shutdown_wait_unfinished>
<shutdown_wait_unfinished_queries>1</shutdown_wait_unfinished_queries>
</clickhouse>
``` | /content/code_sandbox/tests/integration/test_shutdown_wait_unfinished_queries/configs/config_wait.xml | xml | 2016-06-02T08:28:18 | 2024-08-16T18:39:33 | ClickHouse | ClickHouse/ClickHouse | 36,234 | 39 |
```xml
import type { LexicalEditor, RangeSelection, TextNode } from 'lexical'
import {
$isTextNode,
$createTextNode,
COMMAND_PRIORITY_LOW,
SELECTION_CHANGE_COMMAND,
$getSelection,
$isRangeSelection,
$insertNodes,
} from 'lexical'
import { useCallback, useEffect, useMemo, useState } from 'react'
import type { getSelectedNode } from '../../Utils/getSelectedNode'
import type { LinkNode } from '@lexical/link'
import { $createLinkNode, $isLinkNode, TOGGLE_LINK_COMMAND } from '@lexical/link'
import { getDOMRangeRect } from '../../Utils/getDOMRangeRect'
import { sanitizeUrl } from '../../Utils/sanitizeUrl'
import { createPortal } from 'react-dom'
import { Button, Input } from '@proton/atoms'
import { Icon } from '@proton/components'
import { mergeRegister } from '@lexical/utils'
import { c } from 'ttag'
export const $isLinkTextNode = (
node: ReturnType<typeof getSelectedNode>,
selection: RangeSelection,
): node is TextNode => {
const parent = node.getParent()
return (
$isLinkNode(parent) &&
parent.getChildrenSize() === 1 &&
$isTextNode(node) &&
parent.getFirstChild() === node &&
selection.anchor.getNode() === selection.focus.getNode()
)
}
export function LinkInfoEditor({
editor,
setIsEditingLink,
linkNode,
linkTextNode,
}: {
editor: LexicalEditor
setIsEditingLink: (isEditMode: boolean) => void
linkNode: LinkNode | null
linkTextNode: TextNode | null
}) {
const [position, setPosition] = useState<{
top: number
left: number
} | null>(null)
const [shouldShowLinkTextInput, setShouldShowLinkTextInput] = useState(() => linkTextNode !== null || !linkNode)
const [url, setURL] = useState('')
const [text, setText] = useState('')
useEffect(() => {
editor.getEditorState().read(() => {
if (linkNode) {
setURL(linkNode.getURL())
}
if (linkTextNode) {
setText(linkTextNode.getTextContent())
}
if (!linkNode && !linkTextNode) {
const selection = $getSelection()
if (!$isRangeSelection(selection)) {
return
}
if (!selection.isCollapsed()) {
setShouldShowLinkTextInput(false)
return
}
}
})
}, [editor, linkNode, linkTextNode])
const handleSubmission = useCallback(() => {
editor.update(() => {
const selection = $getSelection()
if (!$isRangeSelection(selection)) {
return
}
const sanitizedURL = sanitizeUrl(url.startsWith('http') ? url : 'path_to_url + url)
const isSelectionCollapsed = selection.isCollapsed()
if (isSelectionCollapsed && !!url && !linkNode) {
if (!sanitizedURL) {
return
}
const linkNode = $createLinkNode(sanitizedURL)
const textNode = $createTextNode(text || url)
linkNode.append(textNode)
$insertNodes([linkNode])
linkNode.selectEnd()
return
}
if (!sanitizedURL) {
return
}
editor.dispatchCommand(TOGGLE_LINK_COMMAND, sanitizedURL || null)
if (linkTextNode !== null && text !== '') {
linkTextNode.setTextContent(text)
}
})
setIsEditingLink(false)
}, [editor, linkNode, linkTextNode, setIsEditingLink, text, url])
const linkNodeDOM = useMemo(() => {
if (!linkNode) {
return null
}
return editor.getElementByKey(linkNode.getKey())
}, [editor, linkNode])
const updatePosition = useCallback(() => {
const rootElement = editor.getRootElement()
const rootParent = rootElement?.parentElement
if (!rootElement || !rootParent) {
return
}
if (linkNodeDOM) {
const linkNodeRect = linkNodeDOM.getBoundingClientRect()
setPosition({
top: linkNodeRect.bottom + rootParent.scrollTop - rootParent.getBoundingClientRect().top + 10,
left: linkNodeRect.left,
})
} else {
const nativeSelection = window.getSelection()
const rootElement = editor.getRootElement()
if (nativeSelection !== null && rootElement !== null && rootElement.contains(nativeSelection.anchorNode)) {
const rangeRect = getDOMRangeRect(nativeSelection, rootElement)
setPosition({
top: rangeRect.bottom + rootParent.scrollTop - rootParent.getBoundingClientRect().top + 10,
left: rangeRect.left,
})
}
}
}, [editor, linkNodeDOM])
useEffect(() => {
updatePosition()
return mergeRegister(
editor.registerUpdateListener(() => {
updatePosition()
}),
editor.registerCommand(
SELECTION_CHANGE_COMMAND,
(_payload) => {
updatePosition()
return false
},
COMMAND_PRIORITY_LOW,
),
)
}, [editor, updatePosition])
const containerElement = editor.getRootElement()?.parentElement
const focusInputOnMount = useCallback((input: HTMLInputElement | null) => {
if (input) {
input.focus()
}
}, [])
const cancelLinkEdit = useCallback(() => {
setIsEditingLink(false)
editor.focus()
}, [editor, setIsEditingLink])
if (!position) {
return null
}
return createPortal(
<div
className="bg-norm shadow-norm border-weak absolute left-0 top-0 rounded border px-3 py-1.5 text-sm"
style={{
top: position.top,
left: position.left,
}}
data-testid="hyperlink-form"
>
{/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */}
<form
className="flex flex-col gap-2 py-1"
onSubmit={(event) => {
event.preventDefault()
handleSubmission()
}}
onKeyDown={(event) => {
if (event.key === 'Escape') {
cancelLinkEdit()
}
}}
>
{shouldShowLinkTextInput && (
<div className="flex items-center gap-3">
<Icon name="info-circle" className="flex-shrink-0" />
<Input
aria-label={c('Label').t`Link text`}
placeholder={c('Placeholder').t`Text`}
value={text}
onChange={(event) => {
setText(event.target.value)
}}
/>
</div>
)}
<div className="flex items-center gap-3">
<Icon name="link" className="flex-shrink-0" />
<Input
value={url}
aria-label={c('Label').t`Link URL`}
placeholder={c('Placeholder').t`Paste link`}
onChange={(event) => {
setURL(event.target.value)
}}
ref={focusInputOnMount}
/>
</div>
<div className="flex items-center justify-end gap-1.5">
<Button shape="ghost" onClick={cancelLinkEdit}>{c('Action').t`Cancel`}</Button>
<Button onClick={handleSubmission}>{c('Action').t`Apply`}</Button>
</div>
</form>
</div>,
containerElement ?? document.body,
)
}
``` | /content/code_sandbox/applications/docs-editor/src/app/Plugins/Link/LinkInfoEditor.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 1,583 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.10.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/Source/IntegrationTests/TestFiles/LitTests/LitTest/DafnyTests/TestAttribute/TestAttribute.csproj | xml | 2016-04-16T20:05:38 | 2024-08-16T13:55:18 | dafny | dafny-lang/dafny | 2,863 | 136 |
```xml
import * as React from 'react';
import { IPersonaProps } from '@fluentui/react/lib/Persona';
import {
IBaseFloatingPicker,
IBaseFloatingPickerSuggestionProps,
FloatingPeoplePicker,
SuggestionsStore,
} from '@fluentui/react/lib/FloatingPicker';
import { SearchBox } from '@fluentui/react/lib/SearchBox';
import { people } from '@fluentui/example-data';
import { useConst } from '@fluentui/react-hooks';
const searchBoxWrapperStyling = { width: 208 };
const getTextFromItem = (persona: IPersonaProps): string => {
return persona.text || '';
};
const listContainsPersona = (persona: IPersonaProps, personas?: IPersonaProps[]): boolean => {
return !!personas && personas.some((item: IPersonaProps) => item.text === persona.text);
};
const validateInput = (input: string): boolean => {
return input.indexOf('@') !== -1;
};
const startsWith = (text: string, filterText: string): boolean => {
return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0;
};
export const FloatingPeoplePickerTypesExample: React.FunctionComponent = () => {
const inputElementRef = React.useRef<HTMLInputElement>(null);
const suggestionsStore = useConst(() => new SuggestionsStore<IPersonaProps>());
const [peopleList, setPeopleList] = React.useState(people);
const [searchValue, setSearchValue] = React.useState('');
const picker = React.useRef<IBaseFloatingPicker>(null);
const onFocus = (): void => {
if (picker.current) {
picker.current.showPicker();
}
};
const onSearchChange = (ev: React.ChangeEvent<HTMLInputElement>, newValue: string): void => {
if (newValue !== searchValue && picker.current) {
setSearchValue(newValue);
picker.current.onQueryStringChanged(newValue);
}
};
const onPickerChange = (selectedSuggestion: IPersonaProps): void => {
setSearchValue(selectedSuggestion.text || '');
if (picker.current) {
picker.current.hidePicker();
}
};
const onRemoveSuggestion = (item: any): void => {
const itemIndex = peopleList.indexOf(item);
if (itemIndex >= 0) {
setPeopleList(peopleList.slice(0, itemIndex).concat(peopleList.slice(itemIndex + 1)));
}
};
const suggestionProps: IBaseFloatingPickerSuggestionProps = useConst(() => {
return {
footerItemsProps: [
{
renderItem: () => {
return <>Showing {picker.current ? picker.current.suggestions.length : 0} results</>;
},
shouldShow: () => {
return !!picker.current && picker.current.suggestions.length > 0;
},
},
],
};
});
const onFilterChanged = (filterText: string, currentPersonas?: IPersonaProps[]): IPersonaProps[] => {
if (filterText) {
// Filter by items starting with the current filter text, then remove duplicates
return peopleList
.filter((item: IPersonaProps) => startsWith(item.text || '', filterText))
.filter((persona: IPersonaProps) => !listContainsPersona(persona, currentPersonas));
}
return [];
};
return (
<>
<div style={searchBoxWrapperStyling} ref={inputElementRef}>
<SearchBox
placeholder="Search for person"
// eslint-disable-next-line react/jsx-no-bind
onChange={onSearchChange}
value={searchValue}
// eslint-disable-next-line react/jsx-no-bind
onFocus={onFocus}
/>
</div>
<FloatingPeoplePicker
suggestionsStore={suggestionsStore}
// eslint-disable-next-line react/jsx-no-bind
onResolveSuggestions={onFilterChanged}
getTextFromItem={getTextFromItem}
pickerSuggestionsProps={suggestionProps}
key="normal"
// eslint-disable-next-line react/jsx-no-bind
onRemoveSuggestion={onRemoveSuggestion}
onValidateInput={validateInput}
componentRef={picker}
// eslint-disable-next-line react/jsx-no-bind
onChange={onPickerChange}
inputElement={inputElementRef.current}
resolveDelay={300}
/>
</>
);
};
``` | /content/code_sandbox/packages/react-examples/src/react/FloatingPeoplePicker/FloatingPeoplePicker.Basic.Example.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 931 |
```xml
import type { TooltipStyleProps } from '@antv/component';
import { BBox, InteractionComponent } from '../runtime';
import { FisheyeCoordinate } from './coordinateTransform';
import { TooltipItemValue } from './component';
export type Interaction =
| ElementHighlightInteraction
| ElementHighlightByColorInteraction
| ElementHighlightByXInteraction
| ElementSelectByColorInteraction
| ElementSelectByXInteraction
| ElementSelectInteraction
| TooltipInteraction
| FisheyeInteraction
| ChartIndexInteraction
| CustomInteraction
| LegendFilterInteraction
| LegendHighlightInteraction
| BrushHighlightInteraction
| BrushXHighlightInteraction
| BrushYHighlightInteraction
| BrushAxisHighlightInteraction
| BrushFilterInteraction
| BrushYFilterInteraction
| BrushXFilterInteraction
| SliderFilterInteraction
| PoptipInteraction;
export type InteractionTypes =
| 'elementHighlight'
| 'elementHighlightByX'
| 'elementHighlightByColor'
| 'fisheye'
| 'chartIndex'
| 'elementSelect'
| 'elementSelectByX'
| 'elementSelectByColor'
| 'fisheye'
| 'tooltip'
| 'legendFilter'
| 'legendHighlight'
| 'brushXHighlight'
| 'brushYHighlight'
| 'brushHighlight'
| 'brushFilter'
| 'brushXFilter'
| 'brushYFilter'
| 'sliderFilter'
| 'poptip'
| InteractionComponent;
export type BrushHighlightInteraction = {
type?: 'brushHighlight';
brushKey?: string;
reverse?: boolean;
series?: boolean;
facet?: boolean;
} & Record<`${'mask'}${any}`, any>;
export type BrushXHighlightInteraction = {
type?: 'brushXHighlight';
brushKey?: string;
reverse?: boolean;
series?: boolean;
facet?: boolean;
} & Record<`${'mask'}${any}`, any>;
export type BrushYHighlightInteraction = {
type?: 'brushYHighlight';
brushKey?: string;
reverse?: boolean;
series?: boolean;
facet?: boolean;
} & Record<`${'mask'}${any}`, any>;
export type BrushAxisHighlightInteraction = {
type?: 'brushAxisHighlight';
reverse?: boolean;
brushKey?: string;
} & Record<`${'mask'}${any}`, any>;
export type BrushFilterInteraction = {
type?: 'brushFilter';
reverse?: boolean;
} & Record<`${'mask'}${any}`, any>;
export type BrushXFilterInteraction = {
type?: 'brushXFilter';
reverse?: boolean;
} & Record<`${'mask'}${any}`, any>;
export type BrushYFilterInteraction = {
type?: 'brushYFilter';
reverse?: boolean;
} & Record<`${'mask'}${any}`, any>;
export type ElementHighlightInteraction = {
type?: 'elementHighlight';
// @todo: Style supported by G.
link?: boolean;
background?: boolean;
offset?: number;
} & Record<`${'link' | 'background'}${any}`, any>;
export type ElementSelectInteraction = {
type?: 'elementSelect';
single?: boolean;
background?: boolean;
offset?: number;
} & Record<`${'link' | 'background'}${any}`, any>;
export type ElementSelectByColorInteraction = {
type?: 'elementSelectByColor';
single?: boolean;
offset?: number;
background?: boolean;
} & Record<`${'link' | 'background'}${any}`, any>;
export type ElementSelectByXInteraction = {
type?: 'elementSelectByX';
single?: boolean;
background?: boolean;
offset?: number;
} & Record<`${'link' | 'background'}${any}`, any>;
export type ElementHighlightByXInteraction = {
type?: 'elementHighlightByX';
link?: boolean;
background?: boolean;
offset?: number;
delay?: number;
} & Record<`${'link' | 'background'}${any}`, any>;
export type ElementHighlightByColorInteraction = {
type?: 'elementHighlightByColor';
color?: string;
background?: boolean;
link?: boolean;
offset?: number;
delay?: number;
} & Record<`${'link' | 'background'}${any}`, any>;
export type PoptipInteraction = {
type?: 'poptip';
offsetX?: number;
offsetY?: number;
} & Record<`tip${any}`, any>;
export type LegendFilterInteraction = {
type?: 'legendFilter';
};
export type LegendHighlightInteraction = {
type?: 'legendHighlight';
};
export type ChartIndexInteraction = {
type?: 'chartIndex';
wait?: number;
leading?: boolean;
trailing?: boolean;
} & Record<`${'rule' | 'label'}${any}`, any>;
export type SliderFilterInteraction = {
type?: 'sliderFilter';
wait?: number;
leading?: boolean;
trailing?: boolean;
};
export type TooltipInteraction = {
type?: 'tooltip';
shared?: boolean;
series?: boolean;
facet?: boolean;
body?: boolean;
crosshairs?: boolean;
marker?: boolean;
groupName?: boolean;
disableNative?: boolean;
offset?: [number, number];
position?: TooltipStyleProps['position'];
bounding?: BBox;
mount?: string | HTMLElement;
css?: Record<string, any>; // @todo
enterable?: boolean;
sort?: (d: TooltipItemValue) => any;
filter?: (d: TooltipItemValue) => any;
render?: (
event, // @todo
options: { title: 'string'; items: TooltipItemValue[] },
) => HTMLElement | string;
} & Record<`crosshairs${any}`, any> &
Record<`marker${any}`, any>;
export type FisheyeInteraction = {
type?: 'fisheye';
wait?: number;
leading?: boolean;
trailing?: boolean;
} & Omit<FisheyeCoordinate, 'type'>;
export type CustomInteraction = {
type?: InteractionComponent;
[key: string]: any;
};
``` | /content/code_sandbox/src/spec/interaction.ts | xml | 2016-05-26T09:21:04 | 2024-08-15T16:11:17 | G2 | antvis/G2 | 12,060 | 1,342 |
```xml
import { Localized } from "@fluent/react/compat";
import React, { FunctionComponent } from "react";
import { Field } from "react-final-form";
import { PasswordField } from "coral-framework/components";
import { colorFromMeta, ValidationMessage } from "coral-framework/lib/form";
import {
composeValidators,
required,
validatePassword,
} from "coral-framework/lib/validation";
import {
FormField,
InputDescription,
InputLabel,
} from "coral-ui/components/v2";
interface Props {
disabled: boolean;
}
const SetPasswordField: FunctionComponent<Props> = (props) => (
<Field
name="password"
validate={composeValidators(required, validatePassword)}
>
{({ input, meta }) => (
<FormField>
<Localized id="createPassword-passwordLabel">
<InputLabel htmlFor={input.name}>Password</InputLabel>
</Localized>
<Localized
id="createPassword-passwordDescription"
vars={{ minLength: 8 }}
>
<InputDescription>
{"Must be at least {$minLength} characters"}
</InputDescription>
</Localized>
<Localized
id="createPassword-passwordTextField"
attrs={{ placeholder: true }}
>
<PasswordField
{...input}
id={input.name}
placeholder="Password"
color={colorFromMeta(meta)}
disabled={props.disabled}
fullWidth
/>
</Localized>
<ValidationMessage meta={meta} fullWidth />
</FormField>
)}
</Field>
);
export default SetPasswordField;
``` | /content/code_sandbox/client/src/core/client/admin/routes/Login/views/CreatePassword/SetPasswordField.tsx | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 330 |
```xml
import { LOCALE_ID, Provider } from '@angular/core';
import { differentLocales } from '../constants/different-locales';
import { LocalizationService } from '../services/localization.service';
import { checkHasProp } from '../utils/common-utils';
export class LocaleId extends String {
constructor(private localizationService: LocalizationService) {
super();
}
toString(): string {
const { currentLang } = this.localizationService;
if (checkHasProp(differentLocales, currentLang)) {
return differentLocales[currentLang];
}
return currentLang;
}
valueOf(): string {
return this.toString();
}
}
export const LocaleProvider: Provider = {
provide: LOCALE_ID,
useClass: LocaleId,
deps: [LocalizationService],
};
``` | /content/code_sandbox/npm/ng-packs/packages/core/src/lib/providers/locale.provider.ts | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 165 |
```xml
import { useState } from 'react';
import { parse } from 'papaparse';
import { getValuesFromRecords, RaRecord, useDataProvider } from 'react-admin';
import set from 'lodash/set';
import {
useResourcesConfiguration,
getFieldDefinitionsFromRecords,
} from '../ResourceConfiguration';
/**
* This hooks returns a tuple with its first element being a boolean indicating whether an import is ongoing, and the second element a function to call with a resource name and a file to import.
*
* @param onImportCompleted A function called once the import is completed. Receive an object containing the resource imported and the resourceAlreadyExists boolean.
* @returns {[boolean, ImportResource]}
*/
export const useImportResourceFromCsv = (): [boolean, ImportResource] => {
const [parsing, setParsing] = useState(false);
const dataProvider = useDataProvider();
const [resources, { addResource }] = useResourcesConfiguration();
const importResource = async (resource: string, file: File) => {
setParsing(true);
const resourceAlreadyExists = !!resources[resource];
const { data, meta } = await parseCSV(file);
const records = sanitizeRecords(
data.filter(record => !!record.id),
meta
);
await Promise.all(
records.map(record => {
return dataProvider
.create(resource, {
data: record,
})
.catch(() => {
// Ignore errors while adding a single record
console.error(
`Error while importing record ${JSON.stringify(
record,
null,
4
)}`
);
});
})
);
setParsing(false);
const fields = getFieldDefinitionsFromRecords(records);
addResource({ name: resource, fields });
return { resource, resourceAlreadyExists };
};
return [parsing, importResource];
};
const parseCSV = (file: File): Promise<{ data: RaRecord[]; meta: any }> =>
new Promise((resolve, reject) => {
parse<RaRecord>(file, {
header: true,
skipEmptyLines: true,
complete: async ({ data, meta }) => {
resolve({ data, meta });
},
error: error => {
reject(error);
},
});
});
type ImportResource = (
resource: string,
file: File
) => Promise<{
resourceAlreadyExists: boolean;
resource: string;
}>;
const sanitizeRecords = (
records: RaRecord[],
{ fields }: { fields: string[] }
): RaRecord[] => {
const values = getValuesFromRecords(records);
return fields.reduce(
(newRecords, field) => sanitizeRecord(newRecords, values, field),
[...records]
);
};
const sanitizeRecord = (records, values, field) => {
if (field.split('.').length > 1) {
return records.map(record => {
let { [field]: pathField, ...newRecord } = record;
return set(newRecord, field, record[field]);
});
}
const fieldValues = values[field];
if (
fieldValues.some(value =>
['false', 'true'].includes(value.toString().toLowerCase())
)
) {
return records.map(record =>
set(record, field, Boolean(record[field]))
);
}
return records;
};
``` | /content/code_sandbox/packages/ra-no-code/src/ui/useImportResourceFromCsv.tsx | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 700 |
```xml
export { ApplicationSummaryWidget } from './ApplicationSummaryWidget';
export { ApplicationDetailsWidget } from './ApplicationDetailsWidget/ApplicationDetailsWidget';
export { ApplicationEventsDatatable } from './ApplicationEventsDatatable';
``` | /content/code_sandbox/app/react/kubernetes/applications/DetailsView/index.ts | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 42 |
```xml
import { FileBrowserItemContextMenuProvider } from './useItemContextMenu';
import { SelectionProvider } from './useSelection';
export const FileBrowserStateProvider = ({ itemIds, children }: { children: React.ReactNode; itemIds: string[] }) => {
return (
<SelectionProvider itemIds={itemIds}>
<FileBrowserItemContextMenuProvider>{children}</FileBrowserItemContextMenuProvider>
</SelectionProvider>
);
};
``` | /content/code_sandbox/packages/drive-store/components/FileBrowser/state/index.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 89 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="path_to_url"
android:shape="rectangle" >
<solid android:color="#ffF0F0F0" />
<corners
android:bottomLeftRadius="0.0dip"
android:bottomRightRadius="0.0dip"
android:topLeftRadius="3.0dip"
android:topRightRadius="3.0dip" />
<padding
android:bottom="1.0px"
android:left="1.0px"
android:right="1.0px"
android:top="1.0px" />
</shape>
``` | /content/code_sandbox/app/src/main/res/drawable/setting_up_pressed.xml | xml | 2016-04-09T15:47:45 | 2024-08-14T04:30:04 | MusicLake | caiyonglong/MusicLake | 2,654 | 153 |
```xml
// See LICENSE.txt for license information.
import Database from '@nozbe/watermelondb/Database';
import {ActionType} from '@app/constants';
import {SYSTEM_IDENTIFIERS} from '@app/constants/database';
import DatabaseManager from '@database/manager';
import TestHelper from '@test/test_helper';
import {
storeConfig,
storeDataRetentionPolicies,
updateLastDataRetentionRun,
dataRetentionCleanup,
setLastServerVersionCheck,
setGlobalThreadsTab,
dismissAnnouncement,
} from './systems';
import type {DataRetentionPoliciesRequest} from '@actions/remote/systems';
import type ServerDataOperator from '@database/operator/server_data_operator';
import type SystemModel from '@typings/database/models/servers/system';
const serverUrl = 'baseHandler.test.com';
let operator: ServerDataOperator;
jest.mock('@init/credentials', () => {
const original = jest.requireActual('@init/credentials');
return {
...original,
getServerCredentials: jest.fn(async (url: string) => ({serverUrl: url})),
};
});
beforeEach(async () => {
await DatabaseManager.init([serverUrl]);
operator = DatabaseManager.serverDatabases[serverUrl]!.operator;
});
afterEach(async () => {
await DatabaseManager.destroyServerDatabase(serverUrl);
});
it('handle not found database - storeConfig', async () => {
const models = await storeConfig('foo', {} as ClientConfig);
expect(models).toBeDefined();
expect(models.length).toBe(0);
});
it('handle not found database', async () => {
expect(models).toBeDefined();
expect(models.length).toBe(0);
});
it('base case', async () => {
expect(models).toBeDefined();
expect(models.length).toBe(1); // config
});
});
describe('dataRetention', () => {
it('handle not found database - storeDataRetentionPolicies', async () => {
const models = await storeDataRetentionPolicies('foo', {} as DataRetentionPoliciesRequest);
expect(models).toBeDefined();
expect(models.length).toBe(0);
});
it('base case - storeDataRetentionPolicies', async () => {
const models = await storeDataRetentionPolicies(serverUrl, {globalPolicy: {} as GlobalDataRetentionPolicy, teamPolicies: [], channelPolicies: []} as DataRetentionPoliciesRequest);
expect(models).toBeDefined();
expect(models.length).toBe(2); // data retention and granular data retention policies
});
it('handle not found database - updateLastDataRetentionRun', async () => {
const {error} = await updateLastDataRetentionRun('foo', 0) as {error: unknown};
expect(error).toBeDefined();
});
it('base case - updateLastDataRetentionRun', async () => {
const models = await updateLastDataRetentionRun(serverUrl, 10) as SystemModel[];
expect(models).toBeDefined();
expect(models.length).toBe(1); // data retention
});
it('handle not found database - dataRetentionCleanup', async () => {
const {error} = await dataRetentionCleanup('foo');
expect(error).toBeDefined();
});
it('rentention off - dataRetentionCleanup', async () => {
const post = {...TestHelper.fakePost('channelid1'), id: 'postid', create_at: 1};
await operator.handlePosts({
actionType: ActionType.POSTS.RECEIVED_IN_CHANNEL,
order: [post.id],
posts: [post],
prepareRecordsOnly: false,
});
const spy = jest.spyOn(Database.prototype, 'unsafeVacuum').mockImplementation(jest.fn());
const {error} = await dataRetentionCleanup(serverUrl);
expect(error).toBeDefined(); // unsafeExecute loki error
spy.mockRestore();
});
it('retention on - dataRetentionCleanup', async () => {
const channel: Channel = {
id: 'channelid1',
team_id: 'teamid1',
total_msg_count: 0,
} as Channel;
await operator.handleConfigs({
configs: [
{id: 'DataRetentionEnableMessageDeletion', value: 'true'},
],
configsToDelete: [],
prepareRecordsOnly: false,
});
await operator.handleSystem({systems:
[
{id: SYSTEM_IDENTIFIERS.GRANULAR_DATA_RETENTION_POLICIES, value: {team: [{team_id: 'teamid1', post_duration: 100}], channel: [{channel_id: 'channelid1', post_duration: 100}]}},
],
prepareRecordsOnly: false});
await operator.handleChannel({channels: [channel], prepareRecordsOnly: false});
const spy = jest.spyOn(Database.prototype, 'unsafeVacuum').mockImplementation(jest.fn());
const {error} = await dataRetentionCleanup(serverUrl);
expect(error).toBeDefined(); // LokiJSAdapter doesn't support unsafeSqlQuery
spy.mockRestore();
});
});
describe('setLastServerVersionCheck', () => {
it('handle not found database', async () => {
const {error} = await setLastServerVersionCheck('foo');
expect(error).toBeDefined();
});
it('base case', async () => {
const {error} = await setLastServerVersionCheck(serverUrl);
expect(error).toBeUndefined();
});
});
describe('setGlobalThreadsTab', () => {
it('handle not found database', async () => {
const {error} = await setGlobalThreadsTab('foo', 'all');
expect(error).toBeDefined();
});
it('base case', async () => {
const {error} = await setGlobalThreadsTab(serverUrl, 'all');
expect(error).toBeUndefined();
});
});
describe('dismissAnnouncement', () => {
it('handle not found database', async () => {
const {error} = await dismissAnnouncement('foo', 'text');
expect(error).toBeDefined();
});
it('base case', async () => {
const {error} = await dismissAnnouncement(serverUrl, 'text');
expect(error).toBeUndefined();
});
});
``` | /content/code_sandbox/app/actions/local/systems.test.ts | xml | 2016-10-07T16:52:32 | 2024-08-16T12:08:38 | mattermost-mobile | mattermost/mattermost-mobile | 2,155 | 1,303 |
```xml
import path = require("path");
import e2e = require("./e2e");
import { FeatureSet, waitForHttp } from "./testutil"
import { dockerComposeHooks, startApplicationHooks, restartApplication } from "./shared"
import { backendHooks } from "./shared/backend.hook";
import { TorrentClient } from "../src/scripts/bittorrent"
import magnet from "magnet-uri"
interface TestSuiteOptionsOptional {
client: TorrentClient
fixture: string,
username: string,
password: string,
host?: string,
port: number,
proxyPort?: number,
acceptHttpStatus?: number,
timeout?: number,
stopLabel?: string,
downloadLabel?: string,
unsupportedFeatures: FeatureSet[]
}
const TEST_SUITE_OPTIONS_DEFAULTS = {
username: "admin",
password: "admin",
host: "localhost",
port: 8080,
acceptHttpStatus: 200,
timeout: 10*1000,
stopLabel: "Stopped",
downloadLabel: "Downloading",
}
/**
* Options given to a test suite execution with information about the backend bittorrent service
* to be tested, login information, features etc.
*/
export type TestSuiteOptions = TestSuiteOptionsOptional & (typeof TEST_SUITE_OPTIONS_DEFAULTS)
/**
* Make sure the current test suite defined in `options` supports a certain `feature`. If not,
* skip all test in the current mocha context
* @param options test suite options
* @param feature the feature that is required to continue
*/
function requireFeatureHook(options: TestSuiteOptions, feature: FeatureSet) {
before(function() {
if (options.unsupportedFeatures.includes(feature)) {
this.skip()
}
})
}
export function createTestSuite(optionsArg: TestSuiteOptionsOptional) {
const options: TestSuiteOptions = Object.assign({}, TEST_SUITE_OPTIONS_DEFAULTS, optionsArg)
describe(`given ${options.client.id} service is running (docker-compose)`, function () {
backendHooks([__dirname, options.fixture])
before(async function () {
this.timeout(20 * 1000)
await waitForHttp({ url: `path_to_url{options.host}:${options.port}`, statusCode: options.acceptHttpStatus})
});
describe("given tls/ssl reverse proxy is running (docker-compose)", function() {
// The service name in the docker-compose.yml must be equal to the name of the folder in which it resides
const backendServiceName = path.basename(options.fixture)
dockerComposeHooks([__dirname, "shared", "nginx"], {
env: {
... process.env,
"PROXY_HOST": backendServiceName,
"PROXY_PORT": (options.proxyPort || options.port).toString(),
},
})
describe("given application is running", function() {
startApplicationHooks()
it("user is logging in with https", async function() {
this.retries(3)
await this.app.login({ ...options, https: true, port: 8443 })
await this.app.certificateModalIsVisible()
})
it("self signed certificate is accepted", async function() {
await this.app.acceptCertificate()
await this.app.torrentsPageIsVisible()
})
})
})
describe("given application is running", function() {
startApplicationHooks()
describe("given user is logged in", function() {
before(async function() {
this.retries(3)
await this.app.login(options)
await this.app.torrentsPageIsVisible()
})
it("automatically connect when restarting app", async function() {
await restartApplication(this)
await this.app.torrentsPageIsVisible()
})
it("show settings when connection error after restarting app", async function() {
this.timeout(25 * 1000)
await this.backend.pause()
await restartApplication(this)
await this.app.settingsPageIsVisible({ timeout: 10 * 1000})
await this.app.settingsPageConnectionIsVisible()
await this.backend.unpause()
await restartApplication(this)
await this.app.torrentsPageIsVisible()
})
describe("when a magnet link is uploaded", async function() {
let torrent: e2e.Torrent
requireFeatureHook(options, FeatureSet.MagnetLinks)
before(async function() {
let filename = path.join(__dirname, 'shared/opentracker/data/shared/test-100k.bin.torrent')
torrent = await this.app.uploadMagnetLink({ filename })
})
after(async function() {
if (torrent && await torrent.isExisting()) {
await torrent.delete()
}
})
it("torrent should be visible in table", () => {
return torrent.waitForExist()
})
it("torrent should begin downloading", () => {
return torrent.waitForState(options.downloadLabel)
})
})
describe("given new torrent is uploaded", async function() {
let torrent: e2e.Torrent
before(async function() {
let filename = path.join(__dirname, 'shared/opentracker/data/shared/test-100k.bin.torrent')
torrent = await this.app.uploadTorrent({ filename: filename });
})
after(async function() {
if (torrent) {
await torrent.clickContextMenu("delete");
await torrent.waitForGone();
}
})
it("torrent should be visible in table", () => {
return torrent.waitForExist();
})
it("wait for download to begin", () => {
return torrent.waitForState(options.downloadLabel);
});
it("torrent should be in downloading tab", () => {
return torrent.checkInState(["all", "downloading"]);
});
it("torrent is stopped and resumed", async function() {
this.timeout(25 * 1000)
await torrent.stop({ state: options.stopLabel });
await torrent.waitForState(options.stopLabel)
await torrent.checkInState(["all", "stopped"]);
await torrent.resume({ state: options.downloadLabel });
await torrent.waitForState(options.downloadLabel)
await torrent.checkInState(["all", "downloading"])
})
describe("given labels are supported", function () {
requireFeatureHook(options, FeatureSet.Labels)
it("apply new label", async function () {
const label = "testlabel123";
await torrent.newLabel(label);
await this.app.waitForLabelInDropdown(label);
await this.app.getAllSidebarLabels().should.eventually.have.length(1);
});
it("apply another new label", async function () {
const label = "someotherlabel123";
await torrent.newLabel(label);
await this.app.waitForLabelInDropdown(label);
await torrent.checkInFilterLabel(label);
await this.app.getAllSidebarLabels().should.eventually.have.length(2);
});
it("change back to previous label", async function () {
const label = "testlabel123";
await torrent.changeLabel(label);
await torrent.checkInFilterLabel(label);
});
});
})
})
})
describe("given advanced upload options are supported", async function() {
describe("given application is running", function() {
startApplicationHooks()
describe("given user is logged in", function() {
this.timeout(20 * 1000)
before(async function() {
this.retries(3)
await this.app.login(options)
await this.app.torrentsPageIsVisible()
})
const filename = path.join(__dirname, 'shared/opentracker/data/shared/test-100k.bin.torrent')
it("torrent uploaded with default options", async function() {
let torrent = await this.app.uploadTorrent({ filename: filename, askUploadOptions: true });
await this.app.uploadTorrentModalSubmit()
await torrent.waitForExist()
await torrent.waitForState(options.downloadLabel)
await torrent.delete()
})
it("torent uploaded with preexisting label", async function() {
if (!options.client.uploadOptionsEnable?.category) return this.skip()
const labelName = "mylabel#1"
let torrent = await this.app.uploadTorrent({ filename: filename });
await torrent.newLabel(labelName)
await torrent.delete()
torrent = await this.app.uploadTorrent({ filename: filename, askUploadOptions: true });
await this.app.uploadTorrentModalSubmit({ label: labelName })
await torrent.waitForExist()
await torrent.getLabel().should.eventually.equal(labelName)
await torrent.delete()
})
it("torrent uploaded in stopped state", async function() {
if (!options.client.uploadOptionsEnable?.startTorrent) return this.skip()
let torrent = await this.app.uploadTorrent({ filename: filename, askUploadOptions: true });
await this.app.uploadTorrentModalSubmit({ start: false })
await torrent.isExisting()
await torrent.waitForState(options.stopLabel)
await torrent.delete()
})
it("torrent uploaded with name", async function() {
if (!options.client.uploadOptionsEnable?.renameTorrent) return this.skip()
const torrentName = "my awesome torrent"
let torrent = await this.app.uploadTorrent({ filename: filename, askUploadOptions: true });
await this.app.uploadTorrentModalSubmit({ name: torrentName })
await torrent.isExisting()
await torrent.getColumn("decodedName").should.eventually.equal(torrentName)
await torrent.delete()
})
it("torrent uploaded with save location", async function() {
if (!options.client.uploadOptionsEnable?.saveLocation) return this.skip()
const saveLocation = "/tmp/custom/save/location"
await this.backend.exec(["test", "!", "-e", saveLocation])
let torrent = await this.app.uploadTorrent({ filename: filename, askUploadOptions: true });
await this.app.uploadTorrentModalSubmit({ saveLocation: saveLocation })
await torrent.isExisting()
await torrent.waitForState(options.downloadLabel)
await this.backend.waitForExec(["test", "-e", saveLocation])
await torrent.delete()
})
})
})
})
})
};
``` | /content/code_sandbox/test/testlib.ts | xml | 2016-06-18T15:04:41 | 2024-08-16T07:12:27 | Electorrent | tympanix/Electorrent | 1,016 | 2,094 |
```xml
import { combineReducers } from 'redux';
import {
makeCommunicationReducerFromEnum,
makeResetCommunicationReducer,
} from 'shared/utils/redux/communication';
import composeReducers from 'shared/utils/redux/composeReducers';
import {
createProjectActionTypes,
IProjectCreationState,
resetCreateProjectCommunicationActionTypes,
} from '../types';
export default combineReducers<IProjectCreationState['communications']>({
creatingProject: composeReducers([
makeCommunicationReducerFromEnum(createProjectActionTypes),
makeResetCommunicationReducer(
resetCreateProjectCommunicationActionTypes.RESET_CREATE_PROJECT_COMMUNICATION
),
]),
});
``` | /content/code_sandbox/webapp/client/src/features/projectCreation/store/reducer/communications.ts | xml | 2016-10-19T01:07:26 | 2024-08-14T03:53:55 | modeldb | VertaAI/modeldb | 1,689 | 123 |
```xml
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
``` | /content/code_sandbox/openvidu-components-angular/src/environments/environment.ts | xml | 2016-10-10T13:31:27 | 2024-08-15T12:14:04 | openvidu | OpenVidu/openvidu | 1,859 | 144 |
```xml
// src/jQuery.d.ts
declare function jQuery(selector: string): any;
declare namespace jQuery {
function ajax(url: string, settings?: any): void;
}
``` | /content/code_sandbox/examples/declaration-files/14-declaration-merging/src/jQuery.d.ts | xml | 2016-05-11T03:02:41 | 2024-08-16T12:59:57 | typescript-tutorial | xcatliu/typescript-tutorial | 10,361 | 35 |
```xml
export { DeriveDefinition } from "./derive-definition";
export { DerivedStateProvider } from "./derived-state.provider";
export { DerivedState } from "./derived-state";
export { GlobalState } from "./global-state";
export { StateProvider } from "./state.provider";
export { GlobalStateProvider } from "./global-state.provider";
export { ActiveUserState, SingleUserState, CombinedState } from "./user-state";
export { ActiveUserStateProvider, SingleUserStateProvider } from "./user-state.provider";
export { KeyDefinition, KeyDefinitionOptions } from "./key-definition";
export { StateUpdateOptions } from "./state-update-options";
export { UserKeyDefinitionOptions, UserKeyDefinition } from "./user-key-definition";
export { StateEventRunnerService } from "./state-event-runner.service";
export * from "./state-definitions";
``` | /content/code_sandbox/libs/common/src/platform/state/index.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 167 |
```xml
import { gql } from '@apollo/client';
import * as compose from 'lodash.flowright';
import BrandFilter from '@erxes/ui/src/brands/components/BrandFilter';
import { queries } from '@erxes/ui/src/brands/graphql';
import React from 'react';
import { graphql } from '@apollo/client/react/hoc';
import { withProps } from '@erxes/ui/src/utils';
import { BrandsQueryResponse } from '@erxes/ui/src/brands/types';
import { Counts } from '@erxes/ui/src/types';
type Props = {
counts: Counts;
};
type FinalProps = {
brandsQuery?: BrandsQueryResponse;
} & Props;
class BrandFilterContainer extends React.Component<FinalProps> {
render() {
const { brandsQuery, counts } = this.props;
const updatedProps = {
...this.props,
brands: (brandsQuery ? brandsQuery.brands : null) || [],
loading: (brandsQuery ? brandsQuery.loading : null) || false,
counts: counts || {},
emptyText: 'Now easier to find forms according to your brand'
};
return <BrandFilter {...updatedProps} />;
}
}
export default withProps<Props>(
compose(
graphql<Props, BrandsQueryResponse>(gql(queries.brands), {
name: 'brandsQuery'
})
)(BrandFilterContainer)
);
``` | /content/code_sandbox/packages/ui-leads/src/containers/filters/BrandFilter.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 284 |
```xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>true</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Orleans.Server" Version="8.0.0" />
<PackageReference Include="Microsoft.Orleans.Persistence.Redis" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/projects/orleans/orleans-3/orleans-3.csproj | xml | 2016-07-27T08:23:40 | 2024-08-16T19:15:21 | practical-aspnetcore | dodyg/practical-aspnetcore | 9,106 | 126 |
```xml
<project xmlns="path_to_url" xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<groupId>LoginExample</groupId>
<artifactId>LoginExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
``` | /content/code_sandbox/ServletJSP/Google-Recaptcha-Java-Example/pom.xml | xml | 2016-05-02T05:43:21 | 2024-08-16T06:51:39 | journaldev | WebJournal/journaldev | 1,314 | 359 |
```xml
/*
* Squidex Headless CMS
*
* @license
*/
export interface Resource {
_links: ResourceLinks;
_meta?: Metadata;
}
export type ResourceLinks = { [rel: string]: ResourceLink };
export type ResourceLink = { href: string; method: ResourceMethod; metadata?: string };
export type Metadata = { [rel: string]: string };
export function getLinkUrl(value: Resource | ResourceLinks, ...rels: ReadonlyArray<string>) {
if (!value) {
return false;
}
const links = (value._links || value) as ResourceLinks;
for (const rel of rels) {
const link = links[rel];
if (link && link.method && link.href) {
return link.href;
}
}
return undefined;
}
export function hasAnyLink(value: Resource | ResourceLinks, ...rels: ReadonlyArray<string>) {
return !!getLinkUrl(value, ...rels);
}
export type ResourceMethod =
'GET' |
'DELETE' |
'PATCH' |
'POST' |
'PUT';
``` | /content/code_sandbox/frontend/src/app/framework/utils/hateos.ts | xml | 2016-08-29T05:53:40 | 2024-08-16T17:39:38 | squidex | Squidex/squidex | 2,222 | 231 |
```xml
import { breakpoints } from "@shared/styles";
import useMediaQuery from "~/hooks/useMediaQuery";
export default function useMobile(): boolean {
return useMediaQuery(`(max-width: ${breakpoints.tablet - 1}px)`);
}
``` | /content/code_sandbox/app/hooks/useMobile.ts | xml | 2016-05-22T21:31:47 | 2024-08-16T19:57:22 | outline | outline/outline | 26,751 | 51 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="path_to_url">
<PropertyGroup Label="Globals">
<ProjectGuid>{ECA6B435-B4FA-4F9F-BF95-F451D078FC47}</ProjectGuid>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseOfMfc>false</UseOfMfc>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<!-- The following import will include the 'default' configuration options for VS projects. -->
<Import Project="..\..\allinone\Build.Windows.ProjectConfiguration.props" />
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir>.\$(Platform)\$(Configuration)\</OutDir>
<IntDir>.\$(Platform)\$(Configuration)\</IntDir>
<!-- The ICU projects use "Win32" to mean "x86", so we need to special case it. -->
<OutDir Condition="'$(Platform)'=='Win32'">.\x86\$(Configuration)\</OutDir>
<IntDir Condition="'$(Platform)'=='Win32'">.\x86\$(Configuration)\</IntDir>
<!-- Disable Incremental Linking for Release builds as it prevents Link-time Code Generation -->
<LinkIncremental Condition="'$(Configuration)'=='Debug'">true</LinkIncremental>
<LinkIncremental Condition="'$(Configuration)'=='Release'">false</LinkIncremental>
</PropertyGroup>
<!-- Options that are common to *all* project configurations -->
<ItemDefinitionGroup>
<Midl>
<TypeLibraryName>$(OutDir)/icutest.tlb</TypeLibraryName>
</Midl>
<ClCompile>
<AdditionalIncludeDirectories>..\..\..\include;..\..\common;..\toolutil;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>T_CTEST_IMPLEMENTATION;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<WarningLevel>Level3</WarningLevel>
<CompileAs>Default</CompileAs>
<PrecompiledHeaderOutputFile>$(OutDir)/icutest.pch</PrecompiledHeaderOutputFile>
<AssemblerListingLocation>$(OutDir)/</AssemblerListingLocation>
<ObjectFileName>$(OutDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(OutDir)/icutest.pdb</ProgramDataBaseFileName>
</ClCompile>
<Link>
<AdditionalLibraryDirectories>..\..\..\$(IcuLibOutputDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<!-- Options that are common to all 'Debug' project configurations -->
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<BrowseInformation>true</BrowseInformation>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
</ClCompile>
<Link>
<OutputFile>..\..\..\$(IcuBinOutputDir)\icutest$(IcuMajorVersion)d.exe</OutputFile>
<ProgramDatabaseFile>.\..\..\..\$(IcuLibOutputDir)\icutestd.pdb</ProgramDatabaseFile>
<ImportLibrary>.\..\..\..\$(IcuLibOutputDir)\icutestd.lib</ImportLibrary>
<AdditionalDependencies>icuucd.lib;icutud.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<!-- Options that are common to all 'Release' project configurations -->
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
</ClCompile>
<Link>
<OutputFile>..\..\..\$(IcuBinOutputDir)\icutest$(IcuMajorVersion).exe</OutputFile>
<ProgramDatabaseFile>.\..\..\..\$(IcuLibOutputDir)\icutest.pdb</ProgramDatabaseFile>
<ImportLibrary>.\..\..\..\$(IcuLibOutputDir)\icutest.lib</ImportLibrary>
<AdditionalDependencies>icuuc.lib;icutu.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="ctest.c" />
<ClCompile Include="datamap.cpp" />
<ClCompile Include="testdata.cpp" />
<ClCompile Include="tstdtmod.cpp" />
<ClCompile Include="ucln_ct.c" />
<ClCompile Include="uperf.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="unicode\ctest.h" />
<ClInclude Include="unicode\datamap.h" />
<ClInclude Include="unicode\testdata.h" />
<ClInclude Include="unicode\testlog.h" />
<ClInclude Include="unicode\testtype.h" />
<ClInclude Include="unicode\tstdtmod.h" />
<ClInclude Include="unicode\uperf.h" />
<ClInclude Include="unicode\utimer.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
``` | /content/code_sandbox/icu4c/source/tools/ctestfw/ctestfw.vcxproj | xml | 2016-01-08T02:42:32 | 2024-08-16T18:14:55 | icu | unicode-org/icu | 2,693 | 1,229 |
```xml
export const STORIES_REGEX = /(?<!node_modules.*)\.(story|stories)\.[tj]sx?$/;
``` | /content/code_sandbox/code/lib/csf-plugin/src/constants.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 27 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UIRequiresFullScreen</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
``` | /content/code_sandbox/JsonDemo/Supporting Files/Info.plist | xml | 2016-03-15T05:44:49 | 2024-08-12T19:21:54 | SwiftTheme | wxxsw/SwiftTheme | 2,514 | 405 |
```xml
import * as React from 'react';
import styles from './UploadFile.module.scss';
import {IUploadFileProps} from './IUploadFileProps';
import {IUploadFileState} from './IUploadFileState';
import { Dialog, Stack, Icon, IconType, Label, ProgressIndicator } from 'office-ui-fabric-react';
import * as tsStyles from './UploadStyles';
import { ChunkedFileUploadProgressData, Web } from '@pnp/sp';
import * as strings from 'MyTasksWebPartStrings';
let file :File = undefined;
export interface IUploadFileState {}
export class UploadFile extends React.Component<IUploadFileProps, IUploadFileState> {
private fileInput;
constructor(props: IUploadFileProps) {
super(props);
this.state = {
isUploading:false,
percent:0,
};
this.fileInput = React.createRef();
}
private _fireUploadFile = () => {
// fire click event
this.fileInput.current.value = '';
this.fileInput.current.click();
}
public async componentDidMount(): Promise<void> {
this._fireUploadFile();
}
public componentDidUpdate(prevProps: IUploadFileProps, prevState: IUploadFileState): void {
this._fireUploadFile();
}
/**
* Add a new attachment
*/
private uploadFile = async (e: React.ChangeEvent<HTMLInputElement>) =>{
e.preventDefault();
const reader = new FileReader();
file = e.target.files[0];
console.log("file name",file.name);
try {
// this.props.onFileUpload(file);
const groupUrl = await this.props.spservice.getGrouoUrl(this.props.groupId);
const groupDefaultLibrary = await this.props.spservice.getGroupDocumentLibraryUrl(this.props.groupId);
const web = new Web(groupUrl);
const serverRelativedocumentLibrary = groupDefaultLibrary.replace(location.origin, '');
const rs = await web.getFolderByServerRelativeUrl(serverRelativedocumentLibrary).files.addChunked(
file.name,
file,
(data: ChunkedFileUploadProgressData) => {
this.setState({percent: data.currentPointer / data.fileSize, isUploading:true});
console.log('File Upload chunked %', (data.currentPointer / data.fileSize) );
},
true
);
this.setState({percent: 1, isUploading:true});
setTimeout(() => {
this.setState({isUploading:false});
this.props.onFileUpload(file, groupDefaultLibrary);
}, 500);
} catch (error) {
console.log('rs-e', error);
}
}
public render(): React.ReactElement<IUploadFileProps> {
return (
<div>
<input id="file-picker"
style={{ display: 'none' }}
type="file"
onChange={(event) => this.uploadFile(event)}
ref={this.fileInput} />
{
this.state.isUploading &&
<Stack horizontalAlign="start" horizontal gap="10" style={{width:'100%'}}>
<Icon iconType={IconType.Default} iconName={"CloudUpload"} className={tsStyles.classNames.iconUploadStyles} />
<ProgressIndicator className={tsStyles.classNames.progressIndicatorStyles} label={file.name} description={`${strings.Uploading} ${Math.round(this.state.percent * 100)} %`} percentComplete={(this.state.percent)}></ProgressIndicator>
</Stack>
}
</div>
);
}
}
``` | /content/code_sandbox/samples/react-mytasks/src/Controls/UploadFile/UploadFile.tsx | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 747 |
```xml
export * from 'rxjs-compat/operator/concatMapTo';
``` | /content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/operator/concatMapTo.d.ts | xml | 2016-09-05T10:18:44 | 2024-08-11T13:21:40 | LiquidCore | LiquidPlayer/LiquidCore | 1,010 | 14 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="path_to_url"
xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<groupId>com.microsoft.bot.sample</groupId>
<artifactId>bot-servlet-echo</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>
<name>${project.groupId}:${project.artifactId}</name>
<url>path_to_url
<licenses>
<license>
<url>path_to_url
</license>
</licenses>
<developers>
<developer>
<name>Bot Framework Development</name>
<email></email>
<organization>Microsoft</organization>
<organizationUrl>path_to_url
</developer>
</developers>
<properties>
<maven.deploy.skip>false</maven.deploy.skip>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<repositories>
<repository>
<id>oss-sonatype</id>
<name>oss-sonatype</name>
<url> path_to_url </url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.22</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.microsoft.bot</groupId>
<artifactId>bot-integration-core</artifactId>
<version>4.14.1</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>build</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-webapp-maven-plugin</artifactId>
<version>1.12.0</version>
<configuration>
<schemaVersion>V2</schemaVersion>
<resourceGroup>${groupname}</resourceGroup>
<appName>${botname}</appName>
<appSettings>
<property>
<name>JAVA_OPTS</name>
<value>-Dserver.port=80</value>
</property>
</appSettings>
<runtime>
<os>windows</os>
<javaVersion>Java 8</javaVersion>
<webContainer>tomcat 9.0</webContainer>
</runtime>
<deployment>
<resources>
<resource>
<directory>${project.basedir}/target</directory>
<includes>
<include>*.war</include>
</includes>
</resource>
</resources>
</deployment>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>publish</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</version>
<extensions>true</extensions>
<configuration>
<skipRemoteStaging>true</skipRemoteStaging>
<serverId>ossrh</serverId>
<nexusUrl>path_to_url
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<source>8</source>
<failOnError>false</failOnError>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
``` | /content/code_sandbox/samples/java_springboot/servlet-echo/pom.xml | xml | 2016-09-20T16:17:28 | 2024-08-16T02:44:00 | BotBuilder-Samples | microsoft/BotBuilder-Samples | 4,323 | 1,741 |
```xml
import { assert, assertExists } from "../util.js";
import { InputStream } from "./stream.js";
import { AABB } from '../Geometry.js';
import { ReadonlyVec3, vec3 } from 'gl-matrix';
import { rayTriangleIntersect } from "../MathHelpers.js";
export enum CollisionMaterial {
Solid = 0x1,
FlippedTri = 0x2,
ShootThru = 0x4,
SeeThru = 0x8,
}
export class CollisionEdge {
// defined with 2 vertex indices
public v0: number;
public v1: number;
}
export class CollisionTri {
// defined with 3 edge indices
public e0: number;
public e1: number;
public e2: number;
}
export class CollisionIndexData {
public materials: CollisionMaterial[] = [];
public vertexMaterialIDs: number[] = [];
public edgeMaterialIDs: number[] = [];
public triMaterialIDs: number[] = [];
public vertices: vec3[] = [];
public edges: CollisionEdge[] = [];
public tris: CollisionTri[] = [];
}
export const enum CollisionOctreeNodeType {
None = 0, Branch = 1, Leaf = 2
}
export class CollisionOctreeLeaf {
public type: CollisionOctreeNodeType = CollisionOctreeNodeType.Leaf;
public bounds: AABB;
public triangles: number[] = [];
}
export class CollisionOctreeBranch {
public type: CollisionOctreeNodeType = CollisionOctreeNodeType.Branch;
public children: CollisionOctreeNode[] = [null, null, null, null, null, null, null, null];
}
export type CollisionOctreeNode = CollisionOctreeBranch | CollisionOctreeLeaf | null;
export class CollisionOctree {
public bounds: AABB;
public rootNode: CollisionOctreeNode;
}
export interface AreaCollision {
octree: CollisionOctree;
indexData: CollisionIndexData;
};
function readAABB(stream: InputStream): AABB {
const out = new AABB;
out.minX = stream.readFloat32();
out.minY = stream.readFloat32();
out.minZ = stream.readFloat32();
out.maxX = stream.readFloat32();
out.maxY = stream.readFloat32();
out.maxZ = stream.readFloat32();
return out;
}
function parseCollisionIndexData(stream: InputStream, version: number): CollisionIndexData {
const indexData = new CollisionIndexData;
const numMaterials = stream.readUint32();
for (let i = 0; i < numMaterials; i++) {
// MP1
if (version === 3) {
let flags = 0;
const material = stream.readUint32();
if (material & 0x00040000) flags |= CollisionMaterial.ShootThru;
if (material & 0x00080000) flags |= CollisionMaterial.Solid;
if (material & 0x02000000) flags |= CollisionMaterial.FlippedTri;
if (material & 0x04000000) flags |= CollisionMaterial.SeeThru;
indexData.materials.push(flags);
}
// MP2/3
else {
let flags = CollisionMaterial.Solid;
const materialHi = stream.readUint32();
const materialLo = stream.readUint32();
if (materialLo & 0x00100000) flags |= CollisionMaterial.ShootThru;
if (materialLo & 0x01000000) flags |= CollisionMaterial.FlippedTri;
if (materialLo & 0x04000000) flags |= CollisionMaterial.SeeThru;
indexData.materials.push(flags);
}
}
const numVertexMatIDs = stream.readUint32();
for (let i = 0; i < numVertexMatIDs; i++) indexData.vertexMaterialIDs.push( stream.readUint8() );
const numEdgeMatIDs = stream.readUint32();
for (let i = 0; i < numEdgeMatIDs; i++) indexData.edgeMaterialIDs.push( stream.readUint8() );
const numTriMatIDs = stream.readUint32();
for (let i = 0; i < numTriMatIDs; i++) indexData.triMaterialIDs.push( stream.readUint8() );
const numEdges = stream.readUint32();
for (let i = 0; i < numEdges; i++) {
let edge = new CollisionEdge;
edge.v0 = stream.readUint16();
edge.v1 = stream.readUint16();
indexData.edges.push(edge);
}
const numTris = stream.readUint32() / 3;
for (let i = 0; i < numTris; i++) {
let tri = new CollisionTri;
tri.e0 = stream.readUint16();
tri.e1 = stream.readUint16();
tri.e2 = stream.readUint16();
indexData.tris.push(tri);
}
// Echoes has an extra chunk of data here idk what it is
if (version >= 0x4) {
const unkIdxCount = stream.readUint32();
stream.skip(unkIdxCount*2);
}
const numVerts = stream.readUint32();
for (let i = 0; i < numVerts; i++) {
let vert = vec3.create();
const x = stream.readFloat32();
const y = stream.readFloat32();
const z = stream.readFloat32();
vec3.set(vert, x, y, z);
indexData.vertices.push(vert);
}
return indexData;
}
function parseOctreeNode(stream: InputStream, type: CollisionOctreeNodeType): CollisionOctreeNode {
if (type === CollisionOctreeNodeType.None) {
return null;
}
else if (type === CollisionOctreeNodeType.Branch) {
const node = new CollisionOctreeBranch;
let childTypes = stream.readUint16();
stream.skip(2);
const childOffsets = [];
for (let i = 0; i < 8; i++) {
childOffsets.push(stream.readUint32());
}
const childrenStart = stream.tell();
for (let i = 0; i < 8; i++) {
const childType = childTypes & 0x3;
childTypes >>= 2;
stream.goTo(childrenStart + childOffsets[i]);
node.children[i] = parseOctreeNode(stream, childType);
}
return node;
}
else if (type === CollisionOctreeNodeType.Leaf) {
const node = new CollisionOctreeLeaf;
node.bounds = readAABB(stream);
const numTris = stream.readUint16();
for (let i = 0; i < numTris; i++) {
node.triangles.push(stream.readUint16());
}
return node;
}
else {
throw new Error(`Invalid octree node type: ${type}`);
}
}
function parseOctree(stream: InputStream): CollisionOctree {
const octree = new CollisionOctree;
octree.bounds = readAABB(stream);
const rootNodeType = stream.readUint32();
const octreeSize = stream.readUint32();
const octreeEnd = stream.tell() + octreeSize;
octree.rootNode = parseOctreeNode(stream, rootNodeType);
stream.goTo(octreeEnd);
return octree;
}
export function parseAreaCollision(stream: InputStream): AreaCollision | null {
assert(stream.readUint32() === 0x01000000);
const size = stream.readUint32();
const magic = stream.readUint32();
const version = stream.readUint32();
assert(magic === 0xdeafbabe);
if (version >= 5) {
return null;
}
const octree = parseOctree(stream);
const indexData = parseCollisionIndexData(stream, version);
return { octree, indexData };;
}
// Line check
const epsilon = 1.192092896e-07;
const scratchVec3a = vec3.create();
const scratchVec3b = vec3.create();
const scratchVec3c = vec3.create();
const scratchVec3d = vec3.create();
function aabbLineCheck(p0: ReadonlyVec3, dir: ReadonlyVec3, aabb: AABB): boolean {
// Box center-point
const c = scratchVec3a;
vec3.set(c, (aabb.minX + aabb.maxX)/2, (aabb.minY + aabb.maxY)/2, (aabb.minZ + aabb.maxZ)/2);
// Box halflength extents
const e = scratchVec3b;
vec3.set(e, aabb.maxX - c[0], aabb.maxY - c[1], aabb.maxZ - c[2]);
// Segment midpoint
const m = scratchVec3c;
vec3.scaleAndAdd(m, p0, dir, 0.5);
// Segment halflength vector
const d = scratchVec3d;
vec3.scale(d, dir, 0.5);
vec3.sub(m, m, c); // Translate box and segment to origin
// Try world coordinate axes as separating axes
let adx = Math.abs(d[0]);
if (Math.abs(m[0]) > e[0] + adx) return false;
let ady = Math.abs(d[1]);
if (Math.abs(m[1]) > e[1] + ady) return false;
let adz = Math.abs(d[2]);
if (Math.abs(m[2]) > e[2] + adz) return false;
// Add in an epsilon term to counteract arithmetic errors when segment is
// (near) parallel to a coordinate axis (see text for detail)
adx += epsilon; ady += epsilon; adz += epsilon;
// Try cross products of segment direction vector with coordinate axes
if (Math.abs(m[1] * d[2] - m[2] * d[1]) > e[1] * adz + e[2] * ady) return false;
if (Math.abs(m[2] * d[0] - m[0] * d[2]) > e[0] * adz + e[2] * adx) return false;
if (Math.abs(m[0] * d[1] - m[1] * d[0]) > e[0] * ady + e[1] * adx) return false;
// No separating axis found; segment must be overlapping AABB
return true;
}
const scratchAABB = new AABB();
function octreeNodeLineCheck(p0: ReadonlyVec3, dir: ReadonlyVec3, node: CollisionOctreeNode, bounds: AABB, collision: AreaCollision): boolean {
if (node === null) return false;
if (!aabbLineCheck(p0, dir, bounds)) return false;
if (node.type === CollisionOctreeNodeType.Branch) {
const branch = node as CollisionOctreeBranch;
const minX = bounds.minX; const minY = bounds.minY; const minZ = bounds.minZ;
const maxX = bounds.maxX; const maxY = bounds.maxY; const maxZ = bounds.maxZ;
const midX = (minX+maxX)/2; const midY = (minY+maxY)/2; const midZ = (minZ+maxZ)/2;
for (let i = 0; i < 8; i++) {
// build child AABB
const bb = scratchAABB;
bb.minX = (i & 1) ? midX : minX;
bb.maxX = (i & 1) ? maxX : midX;
bb.minY = (i & 2) ? midY : minY;
bb.maxY = (i & 2) ? maxY : midY;
bb.minZ = (i & 4) ? midZ : minZ;
bb.maxZ = (i & 4) ? maxZ : midZ;
if (octreeNodeLineCheck(p0, dir, branch.children[i], bb, collision)) {
return true;
}
}
// No children had intersections
return false;
} else {
const leaf = node as CollisionOctreeLeaf;
if (!aabbLineCheck(p0, dir, leaf.bounds)) return false;
// test tris
const indexData = collision.indexData;
for (let i = 0; i < leaf.triangles.length; i++) {
const triID = leaf.triangles[i];
const triangle = indexData.tris[triID];
const matID = indexData.triMaterialIDs[triID];
const material = indexData.materials[matID];
const isSolid = (material & CollisionMaterial.Solid) != 0;
const isFlipped = (material & CollisionMaterial.FlippedTri) != 0;
if (!isSolid)
continue;
const e0 = indexData.edges[triangle.e0];
const e1 = indexData.edges[triangle.e1];
let i0 = e0.v0;
let i1 = e0.v1;
let i2 = (e1.v0 !== i0 && e1.v0 !== i1 ? e1.v0 : e1.v1);
if (isFlipped) {
const tmp = i0;
i0 = i2;
i2 = tmp;
}
const v0 = indexData.vertices[i0];
const v1 = indexData.vertices[i1];
const v2 = indexData.vertices[i2];
const t = rayTriangleIntersect(null, p0, dir, v0, v1, v2);
if (t >= 0.0 && t <= 1.0)
return true;
}
// No triangle intersection
return false;
}
}
export function areaCollisionLineCheck(p0: ReadonlyVec3, dir: ReadonlyVec3, collision: AreaCollision): boolean {
return octreeNodeLineCheck(p0, dir, collision.octree.rootNode, collision.octree.bounds, collision);
}
``` | /content/code_sandbox/src/MetroidPrime/collision.ts | xml | 2016-10-06T21:43:45 | 2024-08-16T17:03:52 | noclip.website | magcius/noclip.website | 3,206 | 3,070 |
```xml
/*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import {
Observable,
Subject,
asyncScheduler,
bufferCount,
combineLatestWith,
debounceTime,
defer,
distinctUntilChanged,
distinctUntilKeyChanged,
endWith,
filter,
finalize,
ignoreElements,
map,
merge,
observeOn,
of,
repeat,
scan,
share,
skip,
startWith,
switchMap,
takeUntil,
tap,
withLatestFrom
} from "rxjs"
import { feature } from "~/_"
import {
Viewport,
getElement,
getElementContainer,
getElementSize,
getElements,
getLocation,
getOptionalElement,
watchElementSize
} from "~/browser"
import {
Component,
getComponentElement
} from "../_"
import { Header } from "../header"
import { Main } from "../main"
/* your_sha256_hash------------
* Types
* your_sha256_hash--------- */
/**
* Table of contents
*/
export interface TableOfContents {
prev: HTMLAnchorElement[][] /* Anchors (previous) */
next: HTMLAnchorElement[][] /* Anchors (next) */
}
/* your_sha256_hash------------
* Helper types
* your_sha256_hash--------- */
/**
* Watch options
*/
interface WatchOptions {
viewport$: Observable<Viewport> /* Viewport observable */
header$: Observable<Header> /* Header observable */
}
/**
* Mount options
*/
interface MountOptions {
viewport$: Observable<Viewport> /* Viewport observable */
header$: Observable<Header> /* Header observable */
main$: Observable<Main> /* Main area observable */
target$: Observable<HTMLElement> /* Location target observable */
}
/* your_sha256_hash------------
* Functions
* your_sha256_hash--------- */
/**
* Watch table of contents
*
* This is effectively a scroll spy implementation which will account for the
* fixed header and automatically re-calculate anchor offsets when the viewport
* is resized. The returned observable will only emit if the table of contents
* needs to be repainted.
*
* This implementation tracks an anchor element's entire path starting from its
* level up to the top-most anchor element, e.g. `[h3, h2, h1]`. Although the
* Material theme currently doesn't make use of this information, it enables
* the styling of the entire hierarchy through customization.
*
* Note that the current anchor is the last item of the `prev` anchor list.
*
* @param el - Table of contents element
* @param options - Options
*
* @returns Table of contents observable
*/
export function watchTableOfContents(
el: HTMLElement, { viewport$, header$ }: WatchOptions
): Observable<TableOfContents> {
const table = new Map<HTMLAnchorElement, HTMLElement>()
/* Compute anchor-to-target mapping */
const anchors = getElements<HTMLAnchorElement>(".md-nav__link", el)
for (const anchor of anchors) {
const id = decodeURIComponent(anchor.hash.substring(1))
const target = getOptionalElement(`[id="${id}"]`)
if (typeof target !== "undefined")
table.set(anchor, target)
}
/* Compute necessary adjustment for header */
const adjust$ = header$
.pipe(
distinctUntilKeyChanged("height"),
map(({ height }) => {
const main = getComponentElement("main")
const grid = getElement(":scope > :first-child", main)
return height + 0.8 * (
grid.offsetTop -
main.offsetTop
)
}),
share()
)
/* Compute partition of previous and next anchors */
const partition$ = watchElementSize(document.body)
.pipe(
distinctUntilKeyChanged("height"),
/* Build index to map anchor paths to vertical offsets */
switchMap(body => defer(() => {
let path: HTMLAnchorElement[] = []
return of([...table].reduce((index, [anchor, target]) => {
while (path.length) {
const last = table.get(path[path.length - 1])!
if (last.tagName >= target.tagName) {
path.pop()
} else {
break
}
}
/* If the current anchor is hidden, continue with its parent */
let offset = target.offsetTop
while (!offset && target.parentElement) {
target = target.parentElement
offset = target.offsetTop
}
/* Fix anchor offsets in tables - see path_to_url */
let parent = target.offsetParent as HTMLElement
for (; parent; parent = parent.offsetParent as HTMLElement)
offset += parent.offsetTop
/* Map reversed anchor path to vertical offset */
return index.set(
[...path = [...path, anchor]].reverse(),
offset
)
}, new Map<HTMLAnchorElement[], number>()))
})
.pipe(
/* Sort index by vertical offset (see path_to_url */
map(index => new Map([...index].sort(([, a], [, b]) => a - b))),
combineLatestWith(adjust$),
/* Re-compute partition when viewport offset changes */
switchMap(([index, adjust]) => viewport$
.pipe(
scan(([prev, next], { offset: { y }, size }) => {
const last = y + size.height >= Math.floor(body.height)
/* Look forward */
while (next.length) {
const [, offset] = next[0]
if (offset - adjust < y || last) {
prev = [...prev, next.shift()!]
} else {
break
}
}
/* Look backward */
while (prev.length) {
const [, offset] = prev[prev.length - 1]
if (offset - adjust >= y && !last) {
next = [prev.pop()!, ...next]
} else {
break
}
}
/* Return partition */
return [prev, next]
}, [[], [...index]]),
distinctUntilChanged((a, b) => (
a[0] === b[0] &&
a[1] === b[1]
))
)
)
)
)
)
/* Compute and return anchor list migrations */
return partition$
.pipe(
map(([prev, next]) => ({
prev: prev.map(([path]) => path),
next: next.map(([path]) => path)
})),
/* Extract anchor list migrations */
startWith({ prev: [], next: [] }),
bufferCount(2, 1),
map(([a, b]) => {
/* Moving down */
if (a.prev.length < b.prev.length) {
return {
prev: b.prev.slice(Math.max(0, a.prev.length - 1), b.prev.length),
next: []
}
/* Moving up */
} else {
return {
prev: b.prev.slice(-1),
next: b.next.slice(0, b.next.length - a.next.length)
}
}
})
)
}
/* your_sha256_hash--------- */
/**
* Mount table of contents
*
* @param el - Table of contents element
* @param options - Options
*
* @returns Table of contents component observable
*/
export function mountTableOfContents(
el: HTMLElement, { viewport$, header$, main$, target$ }: MountOptions
): Observable<Component<TableOfContents>> {
return defer(() => {
const push$ = new Subject<TableOfContents>()
const done$ = push$.pipe(ignoreElements(), endWith(true))
push$.subscribe(({ prev, next }) => {
/* Look forward */
for (const [anchor] of next) {
anchor.classList.remove("md-nav__link--passed")
anchor.classList.remove("md-nav__link--active")
}
/* Look backward */
for (const [index, [anchor]] of prev.entries()) {
anchor.classList.add("md-nav__link--passed")
anchor.classList.toggle(
"md-nav__link--active",
index === prev.length - 1
)
}
})
/* Set up following, if enabled */
if (feature("toc.follow")) {
/* Toggle smooth scrolling only for anchor clicks */
const smooth$ = merge(
viewport$.pipe(debounceTime(1), map(() => undefined)),
viewport$.pipe(debounceTime(250), map(() => "smooth" as const))
)
/* Bring active anchor into view */ // @todo: refactor
push$
.pipe(
filter(({ prev }) => prev.length > 0),
combineLatestWith(main$.pipe(observeOn(asyncScheduler))),
withLatestFrom(smooth$)
)
.subscribe(([[{ prev }], behavior]) => {
const [anchor] = prev[prev.length - 1]
if (anchor.offsetHeight) {
/* Retrieve overflowing container and scroll */
const container = getElementContainer(anchor)
if (typeof container !== "undefined") {
const offset = anchor.offsetTop - container.offsetTop
const { height } = getElementSize(container)
container.scrollTo({
top: offset - height / 2,
behavior
})
}
}
})
}
/* Set up anchor tracking, if enabled */
if (feature("navigation.tracking"))
viewport$
.pipe(
takeUntil(done$),
distinctUntilKeyChanged("offset"),
debounceTime(250),
skip(1),
takeUntil(target$.pipe(skip(1))),
repeat({ delay: 250 }),
withLatestFrom(push$)
)
.subscribe(([, { prev }]) => {
const url = getLocation()
/* Set hash fragment to active anchor */
const anchor = prev[prev.length - 1]
if (anchor && anchor.length) {
const [active] = anchor
const { hash } = new URL(active.href)
if (url.hash !== hash) {
url.hash = hash
history.replaceState({}, "", `${url}`)
}
/* Reset anchor when at the top */
} else {
url.hash = ""
history.replaceState({}, "", `${url}`)
}
})
/* Create and return component */
return watchTableOfContents(el, { viewport$, header$ })
.pipe(
tap(state => push$.next(state)),
finalize(() => push$.complete()),
map(state => ({ ref: el, ...state }))
)
})
}
``` | /content/code_sandbox/src/templates/assets/javascripts/components/toc/index.ts | xml | 2016-01-28T22:09:23 | 2024-08-16T17:55:06 | mkdocs-material | squidfunk/mkdocs-material | 19,629 | 2,417 |
```xml
import { describe, expect, it, vi } from 'vitest';
import * as models from '../index';
describe('init()', () => {
it('contains all required fields', async () => {
expect(models.protoFile.init()).toEqual({
name: 'New Proto File',
protoText: '',
});
});
});
describe('create()', () => {
it('creates a valid protofile', async () => {
Date.now = vi.fn().mockReturnValue(1478795580200);
const request = await models.protoFile.create({
name: 'My File',
parentId: 'fld_124',
protoText: 'some proto text',
});
const expected = {
_id: 'pf_cc1dd2ca4275747aa88199e8efd42403',
created: 1478795580200,
modified: 1478795580200,
parentId: 'fld_124',
type: 'ProtoFile',
name: 'My File',
protoText: 'some proto text',
};
expect(request).toEqual(expected);
expect(await models.protoFile.getById(expected._id)).toEqual(expected);
});
it('fails when missing parentId', async () => {
Date.now = vi.fn().mockReturnValue(1478795580200);
expect(() =>
models.protoFile.create({
name: 'no parentId',
}),
).toThrow('New ProtoFile missing `parentId`');
});
});
``` | /content/code_sandbox/packages/insomnia/src/models/__tests__/proto-file.test.ts | xml | 2016-04-23T03:54:26 | 2024-08-16T16:50:44 | insomnia | Kong/insomnia | 34,054 | 308 |
```xml
import { filterRulesSlice } from './filter-rules.reducer';
export const { actions, reducer, name } = filterRulesSlice(
'temporaryFilterRules'
);
export { getSelectors } from './filter-rules.reducer';
``` | /content/code_sandbox/src/renderer/store/reducers/temporary-filter-rules.reducer.ts | xml | 2016-05-14T02:18:49 | 2024-08-16T02:46:28 | ElectroCRUD | garrylachman/ElectroCRUD | 1,538 | 47 |
```xml
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<dataset>
<metadata>
<column name="table_schema"/>
<column name="table_name"/>
<column name="index_name"/>
<column name="rows_selected"/>
<column name="select_latency"/>
<column name="rows_inserted"/>
<column name="insert_latency"/>
<column name="rows_updated"/>
<column name="update_latency"/>
<column name="rows_deleted"/>
<column name="delete_latency"/>
</metadata>
</dataset>
``` | /content/code_sandbox/test/e2e/sql/src/test/resources/cases/dql/dataset/empty_storage_units/mysql/select_mysql_sys_schema_index_statistics.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 175 |
```xml
<run>
<desc>Test cases for DouglasPeuckerSimplifier and TopologyPreservingSimplifier</desc>
<precisionModel type="FLOATING"/>
<case>
<desc>P - point</desc>
<a> POINT(10 10)
</a>
<test> <op name="simplifyDP" arg1="A" arg2="1">
POINT(10 10)
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="1">
POINT(10 10)
</op> </test>
</case>
<case>
<desc>mP - point with EMPTY</desc>
<a> MULTIPOINT( EMPTY, (10 10), (20 20))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="1">
MULTIPOINT((10 10), (20 20))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="1">
MULTIPOINT((10 10), (20 20))
</op> </test>
</case>
<case>
<desc>L - empty line</desc>
<a> LINESTRING EMPTY
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
LINESTRING EMPTY
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
LINESTRING EMPTY
</op> </test>
</case>
<case>
<desc>L - line</desc>
<a> LINESTRING (10 10, 20 21, 30 30)
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
LINESTRING (10 10, 30 30)
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
LINESTRING (10 10, 30 30)
</op> </test>
</case>
<case>
<desc>L - short line</desc>
<a> LINESTRING (0 5, 1 5, 2 5, 5 5)
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
LINESTRING (0 5, 5 5)
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
LINESTRING (0 5, 5 5)
</op> </test>
</case>
<case>
<desc>mL - lines with constrained topology</desc>
<a> MULTILINESTRING ((10 60, 39 50, 70 60, 90 50), (35 55, 46 55), (65 55, 75 55), (10 40, 40 30, 70 40, 90 30))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
MULTILINESTRING ((10 60, 90 50), (35 55, 46 55), (65 55, 75 55), (10 40, 90 30))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
MULTILINESTRING ((10 60, 39 50, 70 60, 90 50), (35 55, 46 55), (65 55, 75 55), (10 40, 90 30))
</op> </test>
</case>
<case>
<desc>mL - lines with EMPTY</desc>
<a> MULTILINESTRING(EMPTY, (10 10, 20 21, 30 30), (10 10, 10 30, 30 30))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
MULTILINESTRING ((10 10, 30 30), (10 10, 10 30, 30 30))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
MULTILINESTRING ((10 10, 30 30), (10 10, 10 30, 30 30))
</op> </test>
</case>
<case>
<desc>A - polygon with flat endpoint</desc>
<a> POLYGON ((5 1, 1 1, 1 9, 9 9, 9 1, 5 1))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="1">
POLYGON ((1 1, 1 9, 9 9, 9 1, 1 1))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="1">
POLYGON ((1 1, 1 9, 9 9, 9 1, 1 1))
</op> </test>
</case>
<case>
<desc>A - polygon with multiple flat segments around endpoint</desc>
<a> POLYGON ((5 5, 7 5, 9 5, 9 1, 1 1, 1 5, 3 5, 5 5))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="1">
POLYGON ((9 5, 9 1, 1 1, 1 5, 9 5))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="1">
POLYGON ((9 5, 9 1, 1 1, 1 5, 9 5))
</op> </test>
</case>
<case>
<desc>A - polygon simplification</desc>
<a> POLYGON ((10 10, 10 90, 60.5 87, 90 90, 90 10, 12 12, 10 10))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
POLYGON ((10 10, 10 90, 90 90, 90 10, 10 10))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
POLYGON ((10 10, 10 90, 90 90, 90 10, 10 10))
</op> </test>
</case>
<case>
<desc>A - polygon with edge collapse.
DP: polygon is split
TP: unchanged
</desc>
<a> POLYGON ((40 240, 160 241, 280 240, 280 160, 160 240, 40 140, 40 240))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="1">
MULTIPOLYGON (((40 240, 160 240, 40 140, 40 240)), ((160 240, 280 240, 280 160, 160 240)))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="1">
POLYGON ((40 240, 160 241, 280 240, 280 160, 160 240, 40 140, 40 240))
</op> </test>
</case>
<case>
<desc>A - polygon collapse for DP</desc>
<a> POLYGON ((5 2, 9 1, 1 1, 5 2))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="1">
POLYGON EMPTY
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="1">
POLYGON ((5 2, 9 1, 1 1, 5 2))
</op> </test>
</case>
<case>
<desc>A - polygon with touching hole</desc>
<a> POLYGON ((10 10, 10 90, 90 90, 90 10, 10 10), (80 20, 20 20, 20 80, 50 90, 80 80, 80 20))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
POLYGON ((10 10, 10 90, 90 90, 90 10, 10 10), (80 20, 20 20, 20 80, 80 80, 80 20))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
POLYGON ((10 10, 10 90, 90 90, 90 10, 10 10), (80 20, 20 20, 20 80, 80 80, 80 20))
</op> </test>
</case>
<case>
<desc>A - polygon with large hole near edge.
DP: simplified and fixed
TP: unchanged
</desc>
<a> POLYGON ((10 10, 10 80, 50 90, 90 80, 90 10, 10 10), (80 20, 20 20, 50 90, 80 20))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
POLYGON ((10 10, 10 80, 45.714285714285715 80, 20 20, 80 20, 54.285714285714285 80, 90 80, 90 10, 10 10))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
POLYGON ((10 10, 10 80, 50 90, 90 80, 90 10, 10 10), (80 20, 20 20, 50 90, 80 20))
</op> </test>
</case>
<case>
<desc>A - polygon with small hole near simplified edge
DP: hole is remmoved
TP: hole is preserved
</desc>
<a> POLYGON ((10 10, 10 80, 50 90, 90 80, 90 10, 10 10), (70 81, 30 81, 50 90, 70 81))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
POLYGON ((10 10, 10 80, 90 80, 90 10, 10 10))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
POLYGON ((10 10, 10 80, 50 90, 90 80, 90 10, 10 10), (70 81, 30 81, 50 90, 70 81))
</op> </test>
</case>
<case>
<desc>mA - multipolygon with EMPTY</desc>
<a> MULTIPOLYGON (EMPTY, ((10 90, 10 10, 90 10, 50 60, 10 90)), ((70 90, 90 90, 90 70, 70 70, 70 90)))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
MULTIPOLYGON (((10 90, 10 10, 90 10, 10 90)), ((70 90, 90 90, 90 70, 70 70, 70 90)))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
MULTIPOLYGON (((10 90, 10 10, 90 10, 50 60, 10 90)), ((70 90, 90 90, 90 70, 70 70, 70 90)))
</op> </test>
</case>
<case>
<desc>mA - multipolygon with small element removed</desc>
<a> MULTIPOLYGON (((10 90, 10 10, 40 40, 90 10, 47 57, 10 90)), ((90 90, 90 85, 85 85, 85 90, 90 90)))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
POLYGON ((10 90, 10 10, 40 40, 90 10, 10 90))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
MULTIPOLYGON (((10 90, 10 10, 40 40, 90 10, 10 90)), ((85 90, 90 85, 85 85, 85 90)))
</op> </test>
</case>
<case>
<desc>GC - geometry collection</desc>
<a> GEOMETRYCOLLECTION (POLYGON ((10 90, 10 10, 40 40, 90 10, 47 57, 10 90)), LINESTRING (30 90, 65 65, 90 30), MULTIPOINT ((80 90), (90 90)))
</a>
<test> <op name="simplifyDP" arg1="A" arg2="10">
GEOMETRYCOLLECTION (POLYGON ((10 90, 10 10, 40 40, 90 10, 10 90)), LINESTRING (30 90, 90 30), MULTIPOINT ((80 90), (90 90)))
</op> </test>
<test> <op name="simplifyTP" arg1="A" arg2="10">
GEOMETRYCOLLECTION (POLYGON ((10 90, 10 10, 40 40, 90 10, 10 90)), LINESTRING (30 90, 90 30), MULTIPOINT ((80 90), (90 90)))
</op> </test>
</case>
</run>
``` | /content/code_sandbox/modules/tests/src/test/resources/testxml/general/TestSimplify.xml | xml | 2016-01-25T18:08:41 | 2024-08-15T17:34:53 | jts | locationtech/jts | 1,923 | 3,451 |
```xml
import { Accessibility, buttonBehavior, ButtonBehaviorProps } from '@fluentui/accessibility';
import * as customPropTypes from '@fluentui/react-proptypes';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import * as _ from 'lodash';
import {
childrenExist,
createShorthandFactory,
UIComponentProps,
ChildrenComponentProps,
commonPropTypes,
rtlTextContainer,
ContentComponentProps,
SizeValue,
} from '../../utils';
import { ComponentEventHandler, FluentComponentStaticProps } from '../../types';
import {
ForwardRefWithAs,
getElementType,
useAccessibility,
useFluentContext,
useStyles,
useTelemetry,
useUnhandledProps,
} from '@fluentui/react-bindings';
export interface SplitButtonToggleProps extends UIComponentProps, ContentComponentProps, ChildrenComponentProps {
/** Accessibility behavior if overridden by the user. */
accessibility?: Accessibility<ButtonBehaviorProps>;
/** A split button toggle can show that it cannot be interacted with. */
disabled?: boolean;
/**
* Called after a user clicks the button.
* @param event - React's original SyntheticEvent.
* @param data - All props.
*/
onClick?: ComponentEventHandler<SplitButtonToggleProps>;
/** A split button toggle can emphasize that it represents the primary action. */
primary?: boolean;
/** A split button toggle can emphasize that it represents an alternative action. */
secondary?: boolean;
/** A split button toggle can be sized */
size?: SizeValue;
/** A split button toggle can be elevated or flat. */
flat?: boolean;
}
export type SplitButtonToggleStylesProps = Pick<SplitButtonToggleProps, 'primary' | 'disabled' | 'size' | 'flat'>;
export const splitButtonToggleClassName = 'ui-splitbutton__toggle';
/**
* A SplitToggleButton allows users to customize the toggle button inside the SplitButton.
*
* @accessibility
* Implements [ARIA Button](path_to_url#button) design pattern.
*/
export const SplitButtonToggle = React.forwardRef<HTMLButtonElement, SplitButtonToggleProps & { as: React.ReactNode }>(
(props, ref) => {
const context = useFluentContext();
const { setStart, setEnd } = useTelemetry(SplitButtonToggle.displayName, context.telemetry);
setStart();
const {
accessibility,
as,
children,
content,
disabled,
primary,
className,
size,
flat,
styles,
variables,
design,
} = props;
const hasChildren = childrenExist(children);
const getA11Props = useAccessibility(accessibility, {
debugName: SplitButtonToggle.displayName,
mapPropsToBehavior: () => ({
as: String(as),
disabled,
}),
actionHandlers: {
performClick: event => {
event.preventDefault();
handleClick(event);
},
},
rtl: context.rtl,
});
const { classes } = useStyles<SplitButtonToggleStylesProps>(SplitButtonToggle.displayName, {
className: splitButtonToggleClassName,
mapPropsToStyles: () => ({
primary,
disabled,
size,
flat,
}),
mapPropsToInlineStyles: () => ({
className,
design,
styles,
variables,
}),
rtl: context.rtl,
});
const unhandledProps = useUnhandledProps(SplitButtonToggle.handledProps, props);
const ElementType = getElementType(props);
const handleClick = (e: React.SyntheticEvent) => {
if (disabled) {
e.preventDefault();
return;
}
_.invoke(props, 'onClick', e, props);
};
const result = (
<ElementType
{...rtlTextContainer.getAttributes({ forElements: [children] })}
{...getA11Props('root', {
onClick: handleClick,
disabled,
className: classes.root,
ref,
...unhandledProps,
})}
>
{hasChildren ? children : content}
</ElementType>
);
setEnd();
return result;
},
) as unknown as ForwardRefWithAs<'button', HTMLButtonElement, SplitButtonToggleProps> &
FluentComponentStaticProps<SplitButtonToggleProps>;
SplitButtonToggle.defaultProps = {
as: 'button',
accessibility: buttonBehavior,
};
SplitButtonToggle.displayName = 'SplitButtonToggle';
SplitButtonToggle.propTypes = {
...commonPropTypes.createCommon({}),
disabled: PropTypes.bool,
onClick: PropTypes.func,
primary: customPropTypes.every([customPropTypes.disallow(['secondary']), PropTypes.bool]),
secondary: customPropTypes.every([customPropTypes.disallow(['primary']), PropTypes.bool]),
size: customPropTypes.size,
flat: PropTypes.bool,
};
SplitButtonToggle.handledProps = Object.keys(SplitButtonToggle.propTypes) as any;
SplitButtonToggle.create = createShorthandFactory({ Component: SplitButtonToggle, mappedProp: 'content' });
``` | /content/code_sandbox/packages/fluentui/react-northstar/src/components/SplitButton/SplitButtonToggle.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 1,046 |
```xml
import createOnEventShim from './createOnEventShim';
describe('A shimmed event target', () => {
class MyEventTarget extends EventTarget {
#shim = createOnEventShim<'message'>(this);
get onmessage() {
return this.#shim.get('message');
}
set onmessage(listener: EventListener) {
this.#shim.set('message', listener);
}
}
describe('with an "onmessage" handler', () => {
let eventTarget: MyEventTarget;
let messageEventListener: jest.Mock<void, []>;
beforeEach(() => {
eventTarget = new MyEventTarget();
messageEventListener = jest.fn();
eventTarget.onmessage = messageEventListener;
});
test('"onmessage" getter should return the event listener', () =>
expect(eventTarget.onmessage).toBe(messageEventListener));
describe('when a "message" event is dispatched', () => {
let messageEvent: Event;
beforeEach(() => {
messageEvent = new Event('message');
eventTarget.dispatchEvent(messageEvent);
});
test('"onmessage" handler should be called once', () => expect(messageEventListener).toHaveBeenCalledTimes(1));
test('"onmessage" handler should be called with the event', () =>
expect(messageEventListener).toHaveBeenNthCalledWith(1, messageEvent));
});
describe('replaced with another "onmessage" handler', () => {
let anotherMessageEventListener: jest.Mock<void, []>;
beforeEach(() => {
anotherMessageEventListener = jest.fn();
eventTarget.onmessage = anotherMessageEventListener;
});
test('"onmessage" getter should return the updated event listener', () =>
expect(eventTarget.onmessage).toBe(anotherMessageEventListener));
describe('when a "message" event is dispatched', () => {
let messageEvent: Event;
beforeEach(() => {
messageEvent = new Event('message');
eventTarget.dispatchEvent(messageEvent);
});
test('the previous "onmessage" handler should not be called', () =>
expect(messageEventListener).toHaveBeenCalledTimes(0));
test('the updated "onmessage" handler should be called once', () =>
expect(anotherMessageEventListener).toHaveBeenCalledTimes(1));
test('the updated "onmessage" handler should be called with the event', () =>
expect(anotherMessageEventListener).toHaveBeenNthCalledWith(1, messageEvent));
});
});
describe('when the handler is removed', () => {
beforeEach(() => {
eventTarget.onmessage = null;
});
test('"onmessage" getter should return falsy', () => expect(eventTarget.onmessage).toBeFalsy());
describe('when a "message" event is dispatched', () => {
let messageEvent: Event;
beforeEach(() => {
messageEvent = new Event('message');
eventTarget.dispatchEvent(messageEvent);
});
test('the removed "onmessage" handler should not be called', () =>
expect(messageEventListener).toHaveBeenCalledTimes(0));
});
});
});
});
``` | /content/code_sandbox/packages/component/src/hooks/internal/private/createOnEventShim.spec.ts | xml | 2016-07-07T23:16:57 | 2024-08-16T00:12:37 | BotFramework-WebChat | microsoft/BotFramework-WebChat | 1,567 | 638 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
import styled from 'styled-components';
import {
PAGE_TOP_PADDING,
COLLAPSABLE_PANEL_HEADER_HEIGHT,
} from 'modules/constants';
import {PanelHeader as BasePanelHeader} from 'modules/components/PanelHeader';
import {Stack as BaseStack} from '@carbon/react';
const PanelHeader = styled(BasePanelHeader)`
padding-right: 0;
`;
const Container = styled.div`
display: grid;
grid-template-rows: ${COLLAPSABLE_PANEL_HEADER_HEIGHT} 1fr;
height: calc(100vh - ${PAGE_TOP_PADDING}px);
position: relative;
width: 100%;
background: var(--cds-layer);
.ope-selectable {
cursor: pointer;
&.hover .djs-outline {
stroke: var(--cds-link-inverse);
stroke-width: 2px;
}
}
.ope-selected {
.djs-outline {
stroke: var(--cds-link-inverse);
stroke-width: 2px;
}
.djs-visual rect {
fill: var(--cds-highlight) !important;
}
}
`;
const Stack = styled(BaseStack)`
margin-left: auto;
`;
export {PanelHeader, Container, Stack};
``` | /content/code_sandbox/operate/client/src/App/DecisionInstance/Drd/styled.tsx | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 287 |
```xml
/**
* @license
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import {supportsCssVariables} from '../../mdc-ripple/util';
import {createFixture, html} from '../../../testing/dom';
import {emitEvent} from '../../../testing/dom/events';
import {createMockFoundation} from '../../../testing/helpers/foundation';
import {setUpMdcTestEnvironment} from '../../../testing/helpers/setup';
import {numbers, strings} from '../constants';
import {MDCDialog, MDCDialogFoundation, util} from '../index';
const DEFAULT_CONTENT = html`Let Google help apps determine location.`;
function getFixture(content: ReturnType<typeof html> = DEFAULT_CONTENT) {
return createFixture(html`
<div>
<button class="open-dialog-button">click</button>
<div id="test-dialog"
class="mdc-dialog"
role="alertdialog"
aria-labelledby="test-dialog-label"
aria-describedby="test-dialog-description">
<div class="mdc-dialog__container">
<div class="mdc-dialog__surface">
<h2 class="mdc-dialog__title">
Use Google's location service?
</h2>
<section class="mdc-dialog__content">
${content}
</section>
<div class="mdc-dialog__actions">
<button class="mdc-button mdc-dialog__button" data-mdc-dialog-action="cancel" type="button">
<span class="mdc-button__label">Cancel</span>
</button>
<button class="mdc-button mdc-dialog__button" data-mdc-dialog-action="no" type="button">
<span class="mdc-button__label">No</span>
</button>
<button class="mdc-button mdc-dialog__button" data-mdc-dialog-action="yes" type="button" ${
strings.INITIAL_FOCUS_ATTRIBUTE}>
<span class="mdc-button__label">Yes</span>
</button>
</div>
</div>
</div>
<div class="mdc-dialog__scrim"></div>
</div>
</div>`);
}
function setupTest(fixture = getFixture()) {
const root = fixture.querySelector<HTMLElement>('.mdc-dialog')!;
const component = new MDCDialog(root);
const title = fixture.querySelector<HTMLElement>('.mdc-dialog__title')!;
const content = fixture.querySelector<HTMLElement>('.mdc-dialog__content')!;
const actions = fixture.querySelector<HTMLElement>('.mdc-dialog__actions')!;
const yesButton =
fixture.querySelector<HTMLElement>('[data-mdc-dialog-action="yes"]')!;
const noButton =
fixture.querySelector<HTMLElement>('[data-mdc-dialog-action="no"]')!;
const cancelButton =
fixture.querySelector<HTMLElement>('[data-mdc-dialog-action="cancel"]')!;
return {
root,
component,
title,
content,
actions,
yesButton,
noButton,
cancelButton
};
}
function setupTestWithMocks() {
const root = getFixture();
const mockFoundation = createMockFoundation(MDCDialogFoundation);
const mockFocusTrapInstance =
jasmine.createSpyObj('focusTrap', ['trapFocus', 'releaseFocus']);
const component =
new MDCDialog(root, mockFoundation, () => mockFocusTrapInstance);
return {root, component, mockFoundation, mockFocusTrapInstance};
}
describe('MDCDialog', () => {
setUpMdcTestEnvironment();
it('attachTo returns a component instance', () => {
expect(MDCDialog.attachTo(
getFixture().querySelector<HTMLElement>('.mdc-dialog')!))
.toEqual(jasmine.any(MDCDialog));
});
it('attachTo throws an error when container element is missing', () => {
const fixture = getFixture();
const container =
fixture.querySelector<HTMLElement>('.mdc-dialog__container')!;
container.parentElement!.removeChild(container);
expect(
() => MDCDialog.attachTo(
fixture.querySelector<HTMLElement>('.mdc-dialog')!))
.toThrow();
});
it('#initialSyncWithDOM registers click handler on the root element', () => {
const {root, component, mockFoundation} = setupTestWithMocks();
emitEvent(root, 'click');
expect(mockFoundation.handleClick).toHaveBeenCalledWith(jasmine.any(Event));
expect(mockFoundation.handleClick).toHaveBeenCalledTimes(1);
component.destroy();
});
it('#initialSyncWithDOM registers keydown handler on the root element',
() => {
const {root, component, mockFoundation} = setupTestWithMocks();
emitEvent(root, 'keydown');
expect(mockFoundation.handleKeydown)
.toHaveBeenCalledWith(jasmine.any(Event));
expect(mockFoundation.handleKeydown).toHaveBeenCalledTimes(1);
component.destroy();
});
it('#destroy deregisters click handler on the root element', () => {
const {root, component, mockFoundation} = setupTestWithMocks();
component.destroy();
emitEvent(root, 'click');
expect(mockFoundation.handleClick)
.not.toHaveBeenCalledWith(jasmine.any(Event));
});
it('#destroy deregisters keydown handler on the root element', () => {
const {root, component, mockFoundation} = setupTestWithMocks();
component.destroy();
emitEvent(root, 'keydown');
expect(mockFoundation.handleKeydown)
.not.toHaveBeenCalledWith(jasmine.any(Event));
});
it(`${strings.OPENING_EVENT} registers document keydown handler and ${
strings.CLOSING_EVENT} deregisters it`,
() => {
const {root, mockFoundation} = setupTestWithMocks();
emitEvent(root, strings.OPENING_EVENT);
emitEvent(document, 'keydown');
expect(mockFoundation.handleDocumentKeydown)
.toHaveBeenCalledWith(jasmine.any(Event));
expect(mockFoundation.handleDocumentKeydown).toHaveBeenCalledTimes(1);
emitEvent(root, strings.CLOSING_EVENT);
emitEvent(document, 'keydown');
expect(mockFoundation.handleDocumentKeydown)
.toHaveBeenCalledWith(jasmine.any(Event));
expect(mockFoundation.handleDocumentKeydown).toHaveBeenCalledTimes(1);
});
it('#initialize attaches ripple elements to all footer buttons', () => {
if (!supportsCssVariables(window, true)) {
return;
}
const {yesButton, noButton, cancelButton} = setupTest();
jasmine.clock().tick(1);
expect(yesButton).toHaveClass('mdc-ripple-upgraded');
expect(noButton).toHaveClass('mdc-ripple-upgraded');
expect(cancelButton).toHaveClass('mdc-ripple-upgraded');
});
it('#destroy cleans up all ripples on footer buttons', () => {
if (!supportsCssVariables(window, true)) {
return;
}
const {component, yesButton, noButton, cancelButton} = setupTest();
jasmine.clock().tick(1);
component.destroy();
jasmine.clock().tick(1);
expect(yesButton).not.toHaveClass('mdc-ripple-upgraded');
expect(noButton).not.toHaveClass('mdc-ripple-upgraded');
expect(cancelButton).not.toHaveClass('mdc-ripple-upgraded');
});
it('#open forwards to MDCDialogFoundation#open', () => {
const {component, mockFoundation} = setupTestWithMocks();
component.open();
expect(mockFoundation.open).toHaveBeenCalled();
});
it('#close forwards to MDCDialogFoundation#close', () => {
const {component, mockFoundation} = setupTestWithMocks();
const action = 'action';
component.close(action);
expect(mockFoundation.close).toHaveBeenCalledWith(action);
component.close();
expect(mockFoundation.close).toHaveBeenCalledWith('');
});
it('get isOpen forwards to MDCDialogFoundation#isOpen', () => {
const {component, mockFoundation} = setupTestWithMocks();
component.isOpen;
expect(mockFoundation.isOpen).toHaveBeenCalled();
});
it('get escapeKeyAction forwards to MDCDialogFoundation#getEscapeKeyAction',
() => {
const {component, mockFoundation} = setupTestWithMocks();
component.escapeKeyAction;
expect(mockFoundation.getEscapeKeyAction).toHaveBeenCalled();
});
it('set escapeKeyAction forwards to MDCDialogFoundation#setEscapeKeyAction',
() => {
const {component, mockFoundation} = setupTestWithMocks();
component.escapeKeyAction = 'action';
expect(mockFoundation.setEscapeKeyAction).toHaveBeenCalledWith('action');
});
it('get scrimClickAction forwards to MDCDialogFoundation#getScrimClickAction',
() => {
const {component, mockFoundation} = setupTestWithMocks();
component.scrimClickAction;
expect(mockFoundation.getScrimClickAction).toHaveBeenCalled();
});
it('set scrimClickAction forwards to MDCDialogFoundation#setScrimClickAction',
() => {
const {component, mockFoundation} = setupTestWithMocks();
component.scrimClickAction = 'action';
expect(mockFoundation.setScrimClickAction)
.toHaveBeenCalledWith('action');
});
it('get autoStackButtons forwards to MDCDialogFoundation#getAutoStackButtons',
() => {
const {component, mockFoundation} = setupTestWithMocks();
component.autoStackButtons;
expect(mockFoundation.getAutoStackButtons).toHaveBeenCalled();
});
it('set autoStackButtons forwards to MDCDialogFoundation#setAutoStackButtons',
() => {
const {component, mockFoundation} = setupTestWithMocks();
component.autoStackButtons = false;
expect(mockFoundation.setAutoStackButtons).toHaveBeenCalledWith(false);
});
it('autoStackButtons adds scrollable class', () => {
// Simulate a scrollable content area
const contentChildren =
new Array(100).join(html`<p>${DEFAULT_CONTENT}</p>`);
const fixture = getFixture(contentChildren);
const root = fixture.querySelector<HTMLElement>('.mdc-dialog')!;
const content = root.querySelector<HTMLElement>('.mdc-dialog__content')!;
content.style.height = '50px';
content.style.overflow = 'auto';
document.body.appendChild(fixture);
try {
const component = new MDCDialog(root);
component.autoStackButtons = false;
component.open();
jasmine.clock().tick(1);
jasmine.clock().tick(1);
expect(root).toHaveClass('mdc-dialog--scrollable');
} finally {
document.body.removeChild(fixture);
}
});
it('adapter#addClass adds a class to the root element', () => {
const {root, component} = setupTest();
(component.getDefaultFoundation() as any).adapter.addClass('foo');
expect(root).toHaveClass('foo');
});
it('adapter#removeClass removes a class from the root element', () => {
const {root, component} = setupTest();
root.classList.add('foo');
(component.getDefaultFoundation() as any).adapter.removeClass('foo');
expect(root).not.toHaveClass('foo');
});
it('adapter#hasClass returns whether a class exists on the root element',
() => {
const {root, component} = setupTest();
root.classList.add('foo');
expect((component.getDefaultFoundation() as any).adapter.hasClass('foo'))
.toBe(true);
expect((component.getDefaultFoundation() as any)
.adapter.hasClass('does-not-exist'))
.toBe(false);
});
it('adapter#addBodyClass adds a class to the body', () => {
const {component} = setupTest();
(component.getDefaultFoundation() as any)
.adapter.addBodyClass('mdc-dialog--scroll-lock');
expect((document.querySelector<HTMLElement>('body')!))
.toHaveClass('mdc-dialog--scroll-lock');
});
it('adapter#removeBodyClass removes a class from the body', () => {
const {component} = setupTest();
const body = document.querySelector<HTMLElement>('body')!;
body.classList.add('mdc-dialog--scroll-lock');
(component.getDefaultFoundation() as any)
.adapter.removeBodyClass('mdc-dialog--scroll-lock');
expect(body).not.toHaveClass('mdc-dialog--scroll-lock');
});
it('adapter#eventTargetMatches returns whether or not the target matches the selector',
() => {
const {component} = setupTest();
const target = document.createElement('div');
target.classList.add('existent-class');
const {adapter: adapter} = component.getDefaultFoundation() as any;
expect(adapter.eventTargetMatches(target, '.existent-class')).toBe(true);
expect(adapter.eventTargetMatches(target, '.non-existent-class'))
.toBe(false);
expect(adapter.eventTargetMatches(null, '.existent-class')).toBe(false);
});
it(`adapter#notifyOpening emits ${strings.OPENING_EVENT}`, () => {
const {component} = setupTest();
const handler = jasmine.createSpy('notifyOpeningHandler');
component.listen(strings.OPENING_EVENT, handler);
(component.getDefaultFoundation() as any).adapter.notifyOpening();
component.unlisten(strings.OPENING_EVENT, handler);
expect(handler).toHaveBeenCalledWith(jasmine.anything());
});
it(`adapter#notifyOpened emits ${strings.OPENED_EVENT}`, () => {
const {component} = setupTest();
const handler = jasmine.createSpy('notifyOpenedHandler');
component.listen(strings.OPENED_EVENT, handler);
(component.getDefaultFoundation() as any).adapter.notifyOpened();
component.unlisten(strings.OPENED_EVENT, handler);
expect(handler).toHaveBeenCalledWith(jasmine.anything());
});
it(`adapter#notifyClosing emits ${
strings
.CLOSING_EVENT} without action if passed action is empty string`,
() => {
const {component} = setupTest();
const handler = jasmine.createSpy('notifyClosingHandler');
component.listen(strings.CLOSING_EVENT, handler);
(component.getDefaultFoundation() as any).adapter.notifyClosing('');
component.unlisten(strings.CLOSING_EVENT, handler);
expect(handler).toHaveBeenCalledWith(
jasmine.objectContaining({detail: {}}));
});
it(`adapter#notifyClosing emits ${strings.CLOSING_EVENT} with action`, () => {
const {component} = setupTest();
const action = 'action';
const handler = jasmine.createSpy('notifyClosingHandler');
component.listen(strings.CLOSING_EVENT, handler);
(component.getDefaultFoundation() as any).adapter.notifyClosing(action);
component.unlisten(strings.CLOSING_EVENT, handler);
expect(handler).toHaveBeenCalledWith(
jasmine.objectContaining({detail: {action}}));
});
it(`adapter#notifyClosed emits ${
strings.CLOSED_EVENT} without action if passed action is empty string`,
() => {
const {component} = setupTest();
const handler = jasmine.createSpy('notifyClosedHandler');
component.listen(strings.CLOSED_EVENT, handler);
(component.getDefaultFoundation() as any).adapter.notifyClosed('');
component.unlisten(strings.CLOSED_EVENT, handler);
expect(handler).toHaveBeenCalledWith(
jasmine.objectContaining({detail: {}}));
});
it(`adapter#notifyClosed emits ${strings.CLOSED_EVENT} with action`, () => {
const {component} = setupTest();
const action = 'action';
const handler = jasmine.createSpy('notifyClosedHandler');
component.listen(strings.CLOSED_EVENT, handler);
(component.getDefaultFoundation() as any).adapter.notifyClosed(action);
component.unlisten(strings.CLOSED_EVENT, handler);
expect(handler).toHaveBeenCalledWith(
jasmine.objectContaining({detail: {action}}));
});
it('adapter#trapFocus calls trapFocus() on a properly configured focus trap instance',
() => {
const {component, mockFocusTrapInstance} = setupTestWithMocks();
component.initialize();
(component.getDefaultFoundation() as any).adapter.trapFocus();
expect(mockFocusTrapInstance.trapFocus).toHaveBeenCalled();
});
it('adapter#releaseFocus calls releaseFocus() on a properly configured focus trap instance',
() => {
const {component, mockFocusTrapInstance} = setupTestWithMocks();
component.initialize();
(component.getDefaultFoundation() as any).adapter.releaseFocus();
expect(mockFocusTrapInstance.releaseFocus).toHaveBeenCalled();
});
it('adapter#isContentScrollable returns false when there is no content element',
() => {
const {component, content} = setupTest();
content.parentElement!.removeChild(content);
const isContentScrollable = (component.getDefaultFoundation() as any)
.adapter.isContentScrollable();
expect(isContentScrollable).toBe(false);
});
it('adapter#isContentScrollable returns result of util.isScrollable', () => {
const {component, content} = setupTest();
expect(
(component.getDefaultFoundation() as any).adapter.isContentScrollable())
.toBe(util.isScrollable(content));
});
it('adapter#areButtonsStacked returns result of util.areTopsMisaligned',
() => {
const {component, yesButton, noButton, cancelButton} = setupTest();
expect((component.getDefaultFoundation() as any)
.adapter.areButtonsStacked())
.toBe(util.areTopsMisaligned([yesButton, noButton, cancelButton]));
});
it('adapter#getActionFromEvent returns an empty string when no event target is present',
() => {
const {component} = setupTest();
const action = (component.getDefaultFoundation() as any)
.adapter.getActionFromEvent({});
expect(action).toEqual('');
});
it('adapter#getActionFromEvent returns attribute value on event target',
() => {
const {component, yesButton} = setupTest();
const action = (component.getDefaultFoundation() as any)
.adapter.getActionFromEvent({target: yesButton});
expect(action).toEqual('yes');
});
it('adapter#getActionFromEvent returns attribute value on parent of event target',
() => {
const {component, yesButton} = setupTest();
const childEl = document.createElement('span');
yesButton.appendChild(childEl);
const action = (component.getDefaultFoundation() as any)
.adapter.getActionFromEvent({target: childEl});
expect(action).toEqual('yes');
});
it('adapter#getActionFromEvent returns null when attribute is not present',
() => {
const {component, title} = setupTest();
const action = (component.getDefaultFoundation() as any)
.adapter.getActionFromEvent({target: title});
expect(action).toBe(null);
});
it(`adapter#clickDefaultButton invokes click() on button matching ${
strings.BUTTON_DEFAULT_ATTRIBUTE}`,
() => {
const fixture = getFixture();
const yesButton = fixture.querySelector<HTMLElement>(
'[data-mdc-dialog-action="yes"]')!;
yesButton.setAttribute(strings.BUTTON_DEFAULT_ATTRIBUTE, 'true');
const {component} = setupTest(fixture);
yesButton.click = jasmine.createSpy('click');
(component.getDefaultFoundation() as any).adapter.clickDefaultButton();
expect(yesButton.click).toHaveBeenCalled();
});
it(`adapter#clickDefaultButton does nothing if nothing matches ${
strings.BUTTON_DEFAULT_ATTRIBUTE}`,
() => {
const {component, yesButton, noButton} = setupTest();
yesButton.click = jasmine.createSpy('click');
noButton.click = jasmine.createSpy('click');
expect(
() => (component.getDefaultFoundation() as any)
.adapter.clickDefaultButton)
.not.toThrow();
expect(yesButton.click).not.toHaveBeenCalled();
expect(noButton.click).not.toHaveBeenCalled();
});
it('adapter#reverseButtons reverses the order of children under the actions element',
() => {
const {component, actions, yesButton, noButton, cancelButton} =
setupTest();
(component.getDefaultFoundation() as any).adapter.reverseButtons();
expect(actions.children[0]).toEqual(yesButton);
expect(actions.children[1]).toEqual(noButton);
expect(actions.children[2]).toEqual(cancelButton);
});
it('#layout proxies to foundation', () => {
const {component} = setupTest();
(component as any).foundation.layout =
jasmine.createSpy('component.foundation.layout');
component.layout();
expect((component as any).foundation.layout).toHaveBeenCalled();
});
it(`Button with ${
strings
.INITIAL_FOCUS_ATTRIBUTE} will be focused when the dialog is opened, with multiple initial focus buttons in DOM`,
() => {
const {root: root1, component: component1, yesButton: yesButton1} =
setupTest();
const {root: root2, component: component2, yesButton: yesButton2} =
setupTest();
expect(yesButton1.hasAttribute(strings.INITIAL_FOCUS_ATTRIBUTE))
.toBe(true);
expect(yesButton2.hasAttribute(strings.INITIAL_FOCUS_ATTRIBUTE))
.toBe(true);
try {
document.body.appendChild(root1);
document.body.appendChild(root2);
component1.open();
jasmine.clock().tick(numbers.DIALOG_ANIMATION_OPEN_TIME_MS + 10);
expect(document.activeElement).toEqual(yesButton1);
component1.close();
jasmine.clock().tick(numbers.DIALOG_ANIMATION_CLOSE_TIME_MS);
component2.open();
jasmine.clock().tick(numbers.DIALOG_ANIMATION_OPEN_TIME_MS + 10);
expect(document.activeElement).toEqual(yesButton2);
component2.close();
jasmine.clock().tick(numbers.DIALOG_ANIMATION_CLOSE_TIME_MS);
} finally {
document.body.removeChild(root1);
document.body.removeChild(root2);
}
});
});
``` | /content/code_sandbox/packages/mdc-dialog/test/component.test.ts | xml | 2016-12-05T16:04:09 | 2024-08-16T15:42:22 | material-components-web | material-components/material-components-web | 17,119 | 4,755 |
```xml
import type { Label, UserModel } from '@proton/shared/lib/interfaces';
import orderBy from '@proton/utils/orderBy';
import range from '@proton/utils/range';
import { FREE_USER_FOLDERS_LIMIT, FREE_USER_LABELS_LIMIT, ROOT_FOLDER } from '../constants';
import type { Folder, FolderWithSubFolders } from '../interfaces/Folder';
export const order = (folders: Folder[] = []) => orderBy(folders, 'Order');
export const getParents = (folders: Folder[] = []) => {
return folders.reduce<{ [key: string]: Folder[] }>((acc, item) => {
const { ParentID = ROOT_FOLDER } = item;
acc[ParentID] = acc[ParentID] || [];
acc[ParentID].push(item);
return acc;
}, {});
};
export const buildTreeview = (folders: FolderWithSubFolders[] = []) => {
const parents = getParents(folders);
const build = (parentID: string | number = ROOT_FOLDER): FolderWithSubFolders[] => {
if (!Array.isArray(parents[parentID])) {
return [];
}
return order(parents[parentID]).map((item) => ({
...item,
subfolders: build(item.ID),
}));
};
return build();
};
export const formatFolderName = (time = 0, name = '', separator = ' ') =>
`${range(0, time)
.map(() => separator)
.join('')}${name}`;
export const hasReachedFolderLimit = (user: UserModel, userFolders: Folder[]) => {
const { hasPaidMail } = user;
return !hasPaidMail && userFolders.length >= FREE_USER_FOLDERS_LIMIT;
};
export const hasReachedLabelLimit = (user: UserModel, userLabels: Label[]) => {
const { hasPaidMail } = user;
return !hasPaidMail && userLabels.length >= FREE_USER_LABELS_LIMIT;
};
``` | /content/code_sandbox/packages/shared/lib/helpers/folder.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 408 |
```xml
import type { FieldContextValue, FieldControlProps } from '../Field';
import { useFieldContext_unstable } from './FieldContext';
/**
* Options for `useFieldControlProps_unstable`.
*/
export type FieldControlPropsOptions = {
/**
* Skips setting `aria-labelledby` on the control if the `label.htmlFor` refers to the control.
*
* This should be used with controls that can be the target of a label's `for` prop:
* `<button>`, `<input>`, `<progress>`, `<select>`, `<textarea>`.
*/
supportsLabelFor?: boolean;
/**
* Sets `required` instead of `aria-required` when the Field is marked required.
*
* This should be used with controls that support the `required` prop:
* `<input>` (except `range` or `color`), `<select>`, `<textarea>`.
*/
supportsRequired?: boolean;
/**
* Sets the size prop on the control to match the Field's size: `'small' | 'medium' | 'large'`.
*
* This should be used with controls that have a custom size prop that matches the Field's size prop.
*/
supportsSize?: boolean;
};
/**
* Gets the control props from the field context, if this inside a `<Field>`.
*
* When called with no arguments, returns the FieldControlProps that should be applied to the control.
*
* @returns A FieldControlProps object if inside a `<Field>`, otherwise undefined.
*/
export function useFieldControlProps_unstable(): FieldControlProps | undefined;
/**
* Copies and merges the FieldControlProps with the given props, if this inside a `<Field>`.
*
* @param props - The existing props for the control. These will be merged with the control props from the field context.
* @param options - Option to include the size prop.
* @returns Merged props if inside a `<Field>`, otherwise the original props, or undefined if no props given.
*/
export function useFieldControlProps_unstable<Props extends FieldControlProps>(
props: Props,
options?: FieldControlPropsOptions,
): Props;
export function useFieldControlProps_unstable<Props extends FieldControlProps>(
props?: Props,
options?: FieldControlPropsOptions,
): Props | undefined {
return getFieldControlProps(useFieldContext_unstable(), props, options);
}
/**
* @internal
* Implementation of useFieldControlProps_unstable.
* Split out so it can be used directly in renderField_unstable.
*/
export function getFieldControlProps<Props extends FieldControlProps>(
context: FieldContextValue | undefined,
props?: Props,
options?: FieldControlPropsOptions,
): Props | undefined {
if (!context) {
return props;
}
// Create a copy of props so we don't modify the original
props = { ...props } as Props;
const { generatedControlId, hintId, labelFor, labelId, required, validationMessageId, validationState } = context;
if (generatedControlId) {
props.id ??= generatedControlId;
}
// Set aria-labelledby if the control doesn't support label.htmlFor, or if the label's htmlFor doesn't refer
// to this control (i.e. the user set this control's id prop without also setting the Field's label.htmlFor).
if (labelId && (!options?.supportsLabelFor || labelFor !== props.id)) {
props['aria-labelledby'] ??= labelId;
}
// The control is described by the validation message, or hint, or both.
// We also preserve and append any aria-describedby from props.
// For reference: path_to_url#discussion_r1017259933
if (validationMessageId || hintId) {
// NOTE: Not using ??= since we're merging and overriding the user-provided value.
props['aria-describedby'] = [validationMessageId, hintId, props?.['aria-describedby']].filter(Boolean).join(' ');
}
if (validationState === 'error') {
props['aria-invalid'] ??= true;
}
if (required) {
if (options?.supportsRequired) {
(props as { required?: boolean }).required ??= true;
} else {
props['aria-required'] ??= true;
}
}
// Include the size prop if this control supports it
if (options?.supportsSize) {
(props as { size?: FieldContextValue['size'] }).size ??= context.size;
}
return props;
}
``` | /content/code_sandbox/packages/react-components/react-field/library/src/contexts/useFieldControlProps.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 964 |
```xml
export const types = `
extend type User @key(fields: "_id") {
_id: String! @external
}
type Template {
_id: String!
name: String
description: String
contentType: String
content: String
categories: [Category]
createdAt:Date
createdBy: User
updatedAt:Date
updatedBy: User
}
type TemplateListResponse {
list: [Template]
totalCount: Int
}
type Category {
_id: String!
name: String
parentId: String
order: String
code: String
contentType: String
templateCount: Int
isRoot: Boolean
createdAt:Date
createdBy: User
updatedAt:Date
updatedBy: User
}
type TemplateCategoryListResponse {
list: [Category]
totalCount: Int
}
`;
export const queries = `
templatesGetTypes: [JSON]
templateList(searchValue: String, categoryIds: [String], page: Int, perPage: Int, contentType: String): TemplateListResponse
templateDetail(_id: String!): Template
categoryList(type: String): TemplateCategoryListResponse
`;
// templatePreview(serviceName: String!, contentType: String!, contentId: String!): JSON
const templateParams = `
name: String,
description: String,
content: String,
contentType: String,
categoryIds: [String]
`;
const categoryParams = `
name: String,
parentId: String,
code: String,
contentType: String
`;
export const mutations = `
templateAdd(${templateParams}): Template
templateEdit(_id: String!, ${templateParams}): Template
templateRemove(_id: String!): JSON
templateUse(serviceName: String!, contentType: String!, template: JSON): JSON
categoryAdd(${categoryParams}): Category
categoryEdit(_id: String!, ${categoryParams}): Category
categoryRemove(_id: String!): JSON
`;
``` | /content/code_sandbox/packages/plugin-template-api/src/graphql/schema/template.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 440 |
```xml
export * from './Results';
``` | /content/code_sandbox/samples/react-multipage/src/webparts/poll/components/Results/index.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 7 |
```xml
<local:ProfileTabPage x:Class="Telegram.Views.Profile.ProfileLinksTabPage"
xmlns="path_to_url"
xmlns:d="path_to_url"
xmlns:x="path_to_url"
xmlns:mc="path_to_url"
xmlns:common="using:Telegram.Common"
xmlns:controls="using:Telegram.Controls"
xmlns:cells="using:Telegram.Controls.Cells"
xmlns:messages="using:Telegram.Controls.Messages"
xmlns:local="using:Telegram.Views.Profile"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<controls:TableListView x:Name="ScrollingHost"
ItemsSource="{x:Bind ViewModel.Links, Mode=OneWay}"
SelectionMode="None"
ChoosingItemContainer="OnChoosingItemContainer"
ContainerContentChanging="OnContainerContentChanging">
<common:SelectedItemsBinder.Attached>
<common:SelectedItemsBinder SelectionMode="Auto"
SelectedItems="{x:Bind ViewModel.SelectedItems}" />
</common:SelectedItemsBinder.Attached>
<ListView.Template>
<ControlTemplate TargetType="ListView">
<Border BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}">
<ItemsPresenter Header="{TemplateBinding Header}"
HeaderTemplate="{TemplateBinding HeaderTemplate}"
HeaderTransitions="{TemplateBinding HeaderTransitions}"
Footer="{TemplateBinding Footer}"
FooterTemplate="{TemplateBinding FooterTemplate}"
FooterTransitions="{TemplateBinding FooterTransitions}"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</ListView.Template>
<ListView.Header>
<StackPanel>
<Border Height="{x:Bind ViewModel.HeaderHeight, Mode=OneWay}" />
<Grid MaxWidth="1000"
Margin="24,0">
<TextBox x:Name="Search"
Text="{x:Bind ViewModel.Links.Query, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
PlaceholderText="{CustomResource Search}"
BorderBrush="{ThemeResource ControlStrokeColorDefaultBrush}"
Margin="0,4,0,2"
Padding="34,5,6,6"
InputScope="Search" />
<controls:GlyphButton Glyph=""
FontSize="16"
Width="36"
Height="32"
IsTabStop="False"
AutomationProperties.AccessibilityView="Raw"
HorizontalAlignment="Left"
VerticalAlignment="Center" />
</Grid>
</StackPanel>
</ListView.Header>
<ListView.Footer>
<Border Height="60" />
</ListView.Footer>
<ListView.ItemTemplate>
<DataTemplate>
<cells:SharedLinkCell />
</DataTemplate>
</ListView.ItemTemplate>
</controls:TableListView>
</Grid>
</local:ProfileTabPage>
``` | /content/code_sandbox/Telegram/Views/Profile/ProfileLinksTabPage.xaml | xml | 2016-05-23T09:03:33 | 2024-08-16T16:17:48 | Unigram | UnigramDev/Unigram | 3,744 | 618 |
```xml
type Props = {
categories: string[];
};
export default function Categories({ categories }: Props) {
return (
<span className="ml-1">
under
{categories.length > 0 ? (
categories.map((category, index) => (
<span key={index} className="ml-1">
{category}
</span>
))
) : (
<span className="ml-1">{categories}</span>
)}
</span>
);
}
``` | /content/code_sandbox/examples/cms-enterspeed/components/categories.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 104 |
```xml
/*
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cloneDeep = require('lodash.clonedeep');
export * from './buffer_array';
export * from './merge_deep';
export { cloneDeep };
``` | /content/code_sandbox/elements/lisk-utils/src/objects/index.ts | xml | 2016-02-01T21:45:35 | 2024-08-15T19:16:48 | lisk-sdk | LiskArchive/lisk-sdk | 2,721 | 131 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!--
~
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<resources>
<item name="view_offset_helper" type="id"/>
</resources>
``` | /content/code_sandbox/lib/java/com/google/android/material/appbar/res/values/ids.xml | xml | 2016-12-05T16:11:29 | 2024-08-16T17:51:42 | material-components-android | material-components/material-components-android | 16,176 | 82 |
```xml
import { createRequire } from 'module';
import type jestConfig from 'jest-config';
import { pluginTokens } from '../plugin-di.js';
const require = createRequire(import.meta.url);
export class JestConfigWrapper {
private readonly jestConfig: typeof jestConfig;
public static readonly inject = [pluginTokens.resolveFromDirectory] as const;
constructor(resolveFromDirectory: string) {
// Use requireResolve, that way you can use this plugin from a different directory
const requireFromJest = createRequire(require.resolve('jest', { paths: [resolveFromDirectory] }));
const requireFromJestCli = createRequire(requireFromJest.resolve('jest-cli'));
this.jestConfig = requireFromJestCli('jest-config');
}
public readInitialOptions(...args: Parameters<typeof jestConfig.readInitialOptions>): ReturnType<typeof jestConfig.readInitialOptions> {
return this.jestConfig.readInitialOptions(...args);
}
}
``` | /content/code_sandbox/packages/jest-runner/src/utils/jest-config-wrapper.ts | xml | 2016-02-12T13:14:28 | 2024-08-15T18:38:25 | stryker-js | stryker-mutator/stryker-js | 2,561 | 197 |
```xml
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="path_to_url">
<channel>
<title>Categories on Mail For Good</title>
<link>path_to_url
<description>Recent content in Categories on Mail For Good</description>
<generator>Hugo -- gohugo.io</generator>
<language>en-us</language>
<atom:link href="path_to_url" rel="self" type="application/rss+xml" />
</channel>
</rss>
``` | /content/code_sandbox/docs/categories/index.xml | xml | 2016-09-01T20:34:38 | 2024-08-01T16:50:36 | mail-for-good | freeCodeCamp/mail-for-good | 3,833 | 128 |
```xml
import {BrepOutputData} from "engine/data/brepOutputData";
export function CallCommand(command: string, args: any[]): number;
export function Interrogate(shapeName: string, structOnly?: boolean): BrepOutputData;
export function GetRef(shapeName: string): number;
export function ClassifyPointToFace(facePtr: number, x: number, y: number, z: number, tol: number): number;
export function ClassifyFaceToFace(face1Ptr: number, face2Ptr: number, tol: number): number;
export function ClassifyEdgeToFace(edgePtr: number, facePtr: number, tol: number): number;
export function IsEdgesOverlap(e1Ptr: number, e2Ptr: number, tol: number): boolean;
export function UpdateTessellation(shapePtr: number, deflection: number): number;
export function SetLocation(shapeName: string, matrixArray: number[]);
export function AddLocation(shapeName: string, matrixArray: number[]);
export function importStepFile(shapeName: string, fileName: string, oneOnly: boolean): number;
``` | /content/code_sandbox/web/app/cad/craft/e0/interact.d.ts | xml | 2016-08-26T21:55:19 | 2024-08-15T01:02:53 | jsketcher | xibyte/jsketcher | 1,461 | 231 |
```xml
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import { NgModule } from '@angular/core';
import { DelonFormModule, WidgetRegistry } from '@delon/form';
import { SharedModule } from '../shared.module';
import { TestWidget } from './test/test.widget';
export const SCHEMA_THIRDS_COMPONENTS = [TestWidget];
@NgModule({
declarations: SCHEMA_THIRDS_COMPONENTS,
imports: [SharedModule, DelonFormModule.forRoot()],
exports: SCHEMA_THIRDS_COMPONENTS
})
export class JsonSchemaModule {
constructor(widgetRegistry: WidgetRegistry) {
widgetRegistry.register(TestWidget.KEY, TestWidget);
}
}
``` | /content/code_sandbox/maxkey-web-frontend/maxkey-web-app/src/app/shared/json-schema/json-schema.module.ts | xml | 2016-11-16T03:06:50 | 2024-08-16T09:22:42 | MaxKey | dromara/MaxKey | 1,423 | 166 |
```xml
/*
* Wire
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see path_to_url
*
*/
import {$getSelection, $isRangeSelection, $isTextNode, LexicalNode, RangeSelection} from 'lexical';
export const LENGTH_LIMIT = 75;
const PUNCTUATION = '\\.,\\*\\?\\$\\|#{}\\(\\)\\^\\[\\]\\\\/!%\'"~=<>_:;\\s';
const VALID_CHARS = (triggers: string[]) => `(?!${triggers.join('|')})[^${PUNCTUATION}]`;
export function getNextSibling(node: LexicalNode) {
let nextSibling = node.getNextSibling();
while (nextSibling !== null && nextSibling.getType() === 'zeroWidth') {
nextSibling = nextSibling.getNextSibling();
}
return nextSibling;
}
export function getPreviousSibling(node: LexicalNode) {
let previousSibling = node.getPreviousSibling();
while (previousSibling !== null && previousSibling.getType() === 'zeroWidth') {
previousSibling = previousSibling.getPreviousSibling();
}
return previousSibling;
}
function isWordChar(char: string, triggers: string[]) {
return new RegExp(VALID_CHARS(triggers)).test(char);
}
type SelectionInfo = {
node: LexicalNode;
offset: number;
isTextNode: boolean;
textContent: string;
selection: RangeSelection;
prevNode: LexicalNode | null;
nextNode: LexicalNode | null;
cursorAtStartOfNode: boolean;
cursorAtEndOfNode: boolean;
wordCharBeforeCursor: boolean;
wordCharAfterCursor: boolean;
};
export function getSelectionInfo(triggers: string[]): SelectionInfo | undefined {
const selection = $getSelection();
if (!selection || !$isRangeSelection(selection)) {
return undefined;
}
const anchor = selection.anchor;
const focus = selection.focus;
const nodes = selection.getNodes();
if (anchor.key !== focus.key || anchor.offset !== focus.offset || nodes.length === 0) {
return undefined;
}
const [node] = nodes;
const isTextNode = $isTextNode(node) && node.isSimpleText();
const offset = anchor.type === 'text' ? anchor.offset : 0;
const textContent = node.getTextContent();
const cursorAtStartOfNode = offset === 0;
const cursorAtEndOfNode = textContent.length === offset;
const charBeforeCursor = textContent.charAt(offset - 1);
const charAfterCursor = textContent.charAt(offset);
const wordCharBeforeCursor = isWordChar(charBeforeCursor, triggers);
const wordCharAfterCursor = isWordChar(charAfterCursor, triggers);
const prevNode = getPreviousSibling(node);
const nextNode = getNextSibling(node);
return {
node,
offset,
isTextNode,
textContent,
selection,
prevNode,
nextNode,
cursorAtStartOfNode,
cursorAtEndOfNode,
wordCharBeforeCursor,
wordCharAfterCursor,
};
}
``` | /content/code_sandbox/src/script/components/RichTextEditor/utils/getSelectionInfo.ts | xml | 2016-07-21T15:34:05 | 2024-08-16T11:40:13 | wire-webapp | wireapp/wire-webapp | 1,125 | 720 |
```xml
<test>
<substitutions>
<substitution>
<name>func</name>
<values>
<value>bitCount</value>
<value>bitNot</value>
<value>abs</value>
<value>intExp2</value>
<value>intExp10</value>
<value>negate</value>
<value>roundAge</value>
<value>roundDuration</value>
<value>roundToExp2</value>
<value>sign</value>
</values>
</substitution>
<substitution>
<name>expr</name>
<values>
<value>number</value>
<value>toUInt32(number)</value>
<value>toUInt16(number)</value>
<value>toUInt8(number)</value>
<value>toInt64(number)</value>
<value>toInt32(number)</value>
<value>toInt16(number)</value>
<value>toInt8(number)</value>
<value>toFloat64(number)</value>
<value>toFloat32(number)</value>
</values>
</substitution>
</substitutions>
<query>SELECT {func}({expr}) FROM numbers(100000000) FORMAT Null</query>
</test>
``` | /content/code_sandbox/tests/performance/unary_arithmetic_functions.xml | xml | 2016-06-02T08:28:18 | 2024-08-16T18:39:33 | ClickHouse | ClickHouse/ClickHouse | 36,234 | 285 |
```xml
import { SiteInfo } from "@sitecore-jss/sitecore-jss-nextjs";
import { editingDataService } from "@sitecore-jss/sitecore-jss-nextjs/editing";
import { SitecorePageProps } from "lib/page-props";
import { GetServerSidePropsContext, GetStaticPropsContext } from "next";
import { Plugin } from "..";
class PreviewModePlugin implements Plugin {
order = 1;
async exec(
props: SitecorePageProps,
context: GetServerSidePropsContext | GetStaticPropsContext,
) {
if (!context.preview) return props;
// If we're in preview (editing) mode, use data already sent along with the editing request
const data = await editingDataService.getEditingData(context.previewData);
if (!data) {
throw new Error(
`Unable to get editing data for preview ${JSON.stringify(
context.previewData,
)}`,
);
}
props.site = data.layoutData.sitecore.context.site as SiteInfo;
props.locale = data.language;
props.layoutData = data.layoutData;
props.dictionary = data.dictionary;
return props;
}
}
export const previewModePlugin = new PreviewModePlugin();
``` | /content/code_sandbox/examples/cms-sitecore-xmcloud/src/lib/page-props-factory/plugins/preview-mode.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 256 |
```xml
// See LICENSE.txt for license information.
import {withDatabase, withObservables} from '@nozbe/watermelondb/react';
import {of as of$} from 'rxjs';
import {switchMap} from 'rxjs/operators';
import {Preferences} from '@constants';
import {queryEmojiPreferences} from '@queries/servers/preference';
import PickerHeader from './header';
import type {WithDatabaseArgs} from '@typings/database/database';
const enhanced = withObservables([], ({database}: WithDatabaseArgs) => ({
skinTone: queryEmojiPreferences(database, Preferences.EMOJI_SKINTONE).
observeWithColumns(['value']).pipe(
switchMap((prefs) => of$(prefs?.[0]?.value ?? 'default')),
),
}));
export default withDatabase(enhanced(PickerHeader));
``` | /content/code_sandbox/app/screens/emoji_picker/picker/header/index.ts | xml | 2016-10-07T16:52:32 | 2024-08-16T12:08:38 | mattermost-mobile | mattermost/mattermost-mobile | 2,155 | 169 |
```xml
import { lorem } from './lorem';
const DATA = {
color: ['red', 'blue', 'green', 'yellow'],
shape: ['circle', 'square', 'triangle'],
location: ['Seattle', 'New York', 'Chicago', 'Los Angeles', 'Portland'],
};
/** @internal */
export interface IExampleItem {
thumbnail: string;
key: string;
name: string;
description: string;
color: string;
shape: string;
location: string;
width: number;
height: number;
}
/** @internal */
export function createListItems(count: number, startIndex: number = 0): IExampleItem[] {
return [...Array(count)].map((item: number, index: number) => {
const size = 150 + Math.round(Math.random() * 100);
return {
thumbnail: `//via.placeholder.com/${size}x${size}`,
key: 'item-' + (index + startIndex) + ' ' + lorem(4),
name: lorem(5),
description: lorem(10 + Math.round(Math.random() * 50)),
color: _randWord(DATA.color),
shape: _randWord(DATA.shape),
location: _randWord(DATA.location),
width: size,
height: size,
};
});
}
/**
* For use in this package only.
* Partial mirror of IGroup from DetailsList avoid a circular dependency.
* If the real interface changes and this one starts causing compiler errors, update it.
* @internal
*/
export interface IExampleGroup {
count: number;
key: string;
name: string;
startIndex: number;
level?: number;
isCollapsed?: boolean;
children?: IExampleGroup[];
}
/** @internal */
export function createGroups(
groupCount: number,
groupDepth: number,
startIndex: number,
itemsPerGroup: number,
level: number = 0,
key: string = '',
isCollapsed?: boolean,
): IExampleGroup[] {
if (key !== '') {
key = key + '-';
}
const count = Math.pow(itemsPerGroup, groupDepth);
return [...Array(groupCount)].map((value: number, index: number) => {
return {
count: count,
key: 'group' + key + index,
name: 'group ' + key + index,
startIndex: index * count + startIndex,
level: level,
isCollapsed: isCollapsed,
children:
groupDepth > 1
? createGroups(groupCount, groupDepth - 1, index * count + startIndex, itemsPerGroup, level + 1, key + index)
: [],
};
});
}
/** @internal */
export function isGroupable(key: string): boolean {
return key === 'color' || key === 'shape' || key === 'location';
}
function _randWord(array: string[]): string {
const index = Math.floor(Math.random() * array.length);
return array[index];
}
``` | /content/code_sandbox/packages/example-data/src/listItems.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 641 |
```xml
import * as React from 'react';
import { DrawerBody, DrawerHeader, DrawerHeaderTitle, OverlayDrawer, Button } from '@fluentui/react-components';
import { Dismiss24Regular } from '@fluentui/react-icons';
export const OverlayNoModal = () => {
const [isOpen, setIsOpen] = React.useState(false);
return (
<div>
<OverlayDrawer modalType="non-modal" open={isOpen} onOpenChange={(_, { open }) => setIsOpen(open)}>
<DrawerHeader>
<DrawerHeaderTitle
action={
<Button
appearance="subtle"
aria-label="Close"
icon={<Dismiss24Regular />}
onClick={() => setIsOpen(false)}
/>
}
>
Overlay Drawer
</DrawerHeaderTitle>
</DrawerHeader>
<DrawerBody>
<p>Drawer content</p>
</DrawerBody>
</OverlayDrawer>
<Button appearance="primary" onClick={() => setIsOpen(!isOpen)}>
Toggle
</Button>
</div>
);
};
OverlayNoModal.parameters = {
docs: {
description: {
story: [
"An overlay is optional depending on whether or not interacting with the background content is beneficial to the user's context/scenario.",
'By setting the `modalType` prop to `non-modal`, the Drawer will not be blocking and the user can interact with the background content.',
].join('\n'),
},
},
};
``` | /content/code_sandbox/packages/react-components/react-drawer/stories/src/Drawer/OverlayDrawerNoModal.stories.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 310 |
```xml
<launch>
<arg name="voxblox_file_path" default="/Users/helen/data/euroc_datasets/voxblox/v1/const_0_05.vxblx" />
<arg name="gt_file_path" default="/Users/helen/data/euroc_datasets/v1_gt_subsampled.ply"/>
<node name="voxblox_eval" pkg="voxblox_ros" type="voxblox_eval" output="screen" args="-alsologtostderr" clear_params="true">
<param name="color_mode" value="normals" />
<param name="frame_id" value="world" />
<param name="verbose" value="true" />
<param name="visualize" value="false" />
<param name="recolor_by_error" value="false" />
<rosparam file="$(find voxblox_ros)/cfg/euroc_dataset.yaml"/>
<param name="voxblox_file_path" value="$(arg voxblox_file_path)" />
<param name="gt_file_path" value="$(arg gt_file_path)" />
</node>
</launch>
``` | /content/code_sandbox/voxblox_ros/launch/eval/eval_euroc.launch | xml | 2016-04-13T09:07:07 | 2024-08-14T22:14:51 | voxblox | ethz-asl/voxblox | 1,313 | 243 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.fragments.ParallaxFragment">
</androidx.appcompat.widget.LinearLayoutCompat>
``` | /content/code_sandbox/imitate/src/main/res/layout/fragment_di.xml | xml | 2016-08-08T08:52:10 | 2024-08-12T19:24:13 | AndroidAnimationExercise | REBOOTERS/AndroidAnimationExercise | 1,868 | 83 |
```xml
/*your_sha256_hash-----------------------------
*your_sha256_hash----------------------------*/
import { testTokenization } from '../test/testRunner';
testTokenization('sb', [
// Comments
[
{
line: "'",
tokens: [{ startIndex: 0, type: 'comment.sb' }]
}
],
[
{
line: " ' a comment",
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 4, type: 'comment.sb' }
]
}
],
[
{
line: "' a comment",
tokens: [{ startIndex: 0, type: 'comment.sb' }]
}
],
[
{
line: "'sticky comment",
tokens: [{ startIndex: 0, type: 'comment.sb' }]
}
],
[
{
line: "1 ' 2< ' comment",
tokens: [
{ startIndex: 0, type: 'number.sb' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'comment.sb' }
]
}
],
[
{
line: "x=1 ' my comment '' is a nice one",
tokens: [
{ startIndex: 0, type: 'variable.name.sb' }, // x
{ startIndex: 1, type: 'operator.sb' }, // =
{ startIndex: 2, type: 'number.sb' }, // 1
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'comment.sb' }
]
}
],
// Numbers
[
{
line: '0',
tokens: [{ startIndex: 0, type: 'number.sb' }]
}
],
[
{
line: '0.0',
tokens: [{ startIndex: 0, type: 'number.float.sb' }]
}
],
[
{
line: '23.5',
tokens: [{ startIndex: 0, type: 'number.float.sb' }]
}
],
[
{
line: '1 -0',
tokens: [
{ startIndex: 0, type: 'number.sb' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'operator.sb' },
{ startIndex: 3, type: 'number.sb' }
]
}
],
[
{
line: '100+10',
tokens: [
{ startIndex: 0, type: 'number.sb' },
{ startIndex: 3, type: 'operator.sb' },
{ startIndex: 4, type: 'number.sb' }
]
}
],
[
{
line: '0 + 0',
tokens: [
{ startIndex: 0, type: 'number.sb' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'operator.sb' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'number.sb' }
]
}
],
// Keywords
[
{
line: 'For i = 0 To 10 Step 2',
tokens: [
{ startIndex: 0, type: 'keyword.for.sb' }, // For
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'variable.name.sb' }, // i
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'operator.sb' }, // =
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'number.sb' }, // 0
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'keyword.to.sb' }, // To
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'number.sb' }, // 10
{ startIndex: 15, type: '' },
{ startIndex: 16, type: 'keyword.step.sb' }, // Step
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'number.sb' } // 2
]
}
],
[
{
line: 'if x <> 23.7 thEn',
tokens: [
{ startIndex: 0, type: 'keyword.if.sb' }, // if
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'variable.name.sb' }, // x
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'operator.sb' }, // <>
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'number.float.sb' }, // 23.7
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'keyword.then.sb' } // thEn
]
}
],
[
{
line: 'ElseIf b[i] And col Then',
tokens: [
{ startIndex: 0, type: 'keyword.elseif.sb' }, // ElseIf
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'variable.name.sb' }, // b
{ startIndex: 8, type: 'delimiter.array.sb' }, // [
{ startIndex: 9, type: 'variable.name.sb' }, // i
{ startIndex: 10, type: 'delimiter.array.sb' }, // ]
{ startIndex: 11, type: '' },
{ startIndex: 12, type: 'operator.sb' }, // And
{ startIndex: 15, type: '' },
{ startIndex: 16, type: 'variable.name.sb' }, // col
{ startIndex: 19, type: '' },
{ startIndex: 20, type: 'keyword.then.sb' } // Then
]
}
],
[
{
line: 'GoTo location',
tokens: [
{ startIndex: 0, type: 'keyword.goto.sb' }, // GoTo
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'variable.name.sb' } // location
]
}
],
// Strings
[
{
line: 's = "string"',
tokens: [
{ startIndex: 0, type: 'variable.name.sb' }, // s
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'operator.sb' }, // =
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'string.sb' } // "string"
]
}
],
[
{
line: '"use strict";',
tokens: [
{ startIndex: 0, type: 'string.sb' }, // "use strict"
{ startIndex: 12, type: '' } // ;
]
}
],
// Tags
[
{
line: 'sub ToString',
tokens: [
{ startIndex: 0, type: 'keyword.sub.sb' }, // sub
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'variable.name.sb' } // ToString
]
}
],
[
{
line: 'While For If Sub EndWhile EndFor EndIf endsub',
tokens: [
{ startIndex: 0, type: 'keyword.while.sb' }, // While
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'keyword.for.sb' }, // For
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'keyword.if.sb' }, // If
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'keyword.sub.sb' }, // Sub
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'keyword.endwhile.sb' }, // EndWhile
{ startIndex: 25, type: '' },
{ startIndex: 26, type: 'keyword.endfor.sb' }, // EndFor
{ startIndex: 32, type: '' },
{ startIndex: 33, type: 'keyword.endif.sb' }, // EndIf
{ startIndex: 38, type: '' },
{ startIndex: 39, type: 'keyword.endsub.sb' } //endsub
]
}
],
[
{
line: 'While while WHILE WHile whiLe',
tokens: [
{ startIndex: 0, type: 'keyword.while.sb' }, // While
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'keyword.while.sb' }, // while
{ startIndex: 11, type: '' },
{ startIndex: 12, type: 'keyword.while.sb' }, // WHILE
{ startIndex: 17, type: '' },
{ startIndex: 18, type: 'keyword.while.sb' }, // WHile
{ startIndex: 23, type: '' },
{ startIndex: 24, type: 'keyword.while.sb' } // whiLe
]
}
],
// types and members
[
{
line: 'Else TextWindow.Write("text")',
tokens: [
{ startIndex: 0, type: 'keyword.else.sb' }, // Else
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'type.sb' }, // TextWindow
{ startIndex: 15, type: 'delimiter.sb' }, // .
{ startIndex: 16, type: 'type.member.sb' }, // Write
{ startIndex: 21, type: 'delimiter.parenthesis.sb' }, // (
{ startIndex: 22, type: 'string.sb' }, // "text"
{ startIndex: 28, type: 'delimiter.parenthesis.sb' } // )
]
}
],
[
{
line: 'class.method (x, y)',
tokens: [
{ startIndex: 0, type: 'type.sb' }, // class
{ startIndex: 5, type: 'delimiter.sb' }, // .
{ startIndex: 6, type: 'type.member.sb' }, // method
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'delimiter.parenthesis.sb' }, // (
{ startIndex: 14, type: 'variable.name.sb' }, // x
{ startIndex: 15, type: 'delimiter.sb' }, // ,
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'variable.name.sb' }, // y
{ startIndex: 18, type: 'delimiter.parenthesis.sb' } // )
]
}
],
[
{
line: 'const = Math.PI',
tokens: [
{ startIndex: 0, type: 'variable.name.sb' }, // const
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'operator.sb' }, // =
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'type.sb' }, // Math
{ startIndex: 12, type: 'delimiter.sb' }, // .
{ startIndex: 13, type: 'type.member.sb' } // PI
]
}
]
]);
``` | /content/code_sandbox/src/basic-languages/sb/sb.test.ts | xml | 2016-06-07T16:56:31 | 2024-08-16T17:17:05 | monaco-editor | microsoft/monaco-editor | 39,508 | 2,731 |
```xml
import glob from 'glob'
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import {
fetchViaHTTP,
findPort,
initNextServerScript,
killApp,
} from 'next-test-utils'
import { ChildProcess } from 'child_process'
describe('required server files app router', () => {
let next: NextInstance
let server: ChildProcess
let appPort: number | string
let delayedPostpone
let rewritePostpone
const setupNext = async ({
nextEnv,
minimalMode,
}: {
nextEnv?: boolean
minimalMode?: boolean
}) => {
// test build against environment with next support
process.env.NOW_BUILDER = nextEnv ? '1' : ''
next = await createNext({
files: {
app: new FileRef(join(__dirname, 'app')),
lib: new FileRef(join(__dirname, 'lib')),
'cache-handler.js': new FileRef(join(__dirname, 'cache-handler.js')),
'middleware.js': new FileRef(join(__dirname, 'middleware.js')),
'data.txt': new FileRef(join(__dirname, 'data.txt')),
'.env': new FileRef(join(__dirname, '.env')),
'.env.local': new FileRef(join(__dirname, '.env.local')),
'.env.production': new FileRef(join(__dirname, '.env.production')),
},
nextConfig: {
cacheHandler: './cache-handler.js',
experimental: {
ppr: true,
},
eslint: {
ignoreDuringBuilds: true,
},
output: 'standalone',
},
})
await next.stop()
delayedPostpone = (await next.readJSON('.next/server/app/delayed.meta'))
.postponed
rewritePostpone = (
await next.readJSON('.next/server/app/rewrite/first-cookie.meta')
).postponed
await fs.move(
join(next.testDir, '.next/standalone'),
join(next.testDir, 'standalone')
)
for (const file of await fs.readdir(next.testDir)) {
if (file !== 'standalone') {
await fs.remove(join(next.testDir, file))
console.log('removed', file)
}
}
const files = glob.sync('**/*', {
cwd: join(next.testDir, 'standalone/.next/server/pages'),
dot: true,
})
for (const file of files) {
if (file.endsWith('.json') || file.endsWith('.html')) {
await fs.remove(join(next.testDir, '.next/server', file))
}
}
const testServer = join(next.testDir, 'standalone/server.js')
await fs.writeFile(
testServer,
(await fs.readFile(testServer, 'utf8')).replace(
'port:',
`minimalMode: ${minimalMode},port:`
)
)
appPort = await findPort()
server = await initNextServerScript(
testServer,
/- Local:/,
{
...process.env,
PORT: `${appPort}`,
},
undefined,
{
cwd: next.testDir,
}
)
}
beforeAll(async () => {
await setupNext({ nextEnv: true, minimalMode: true })
})
afterAll(async () => {
await next.destroy()
if (server) await killApp(server)
})
it('should not fail caching', async () => {
expect(next.cliOutput).not.toContain('ERR_INVALID_URL')
})
it('should properly stream resume', async () => {
const res = await fetchViaHTTP(appPort, '/delayed', undefined, {
headers: {
'x-matched-path': '/_next/postponed/resume/delayed',
},
method: 'POST',
body: delayedPostpone,
})
let chunks = []
for await (const chunk of res.body) {
chunks.push({
time: Date.now(),
chunk: chunk.toString(),
})
}
const firstSuspense = chunks.find((item) => item.chunk.includes('time'))
const secondSuspense = chunks.find((item) => item.chunk.includes('random'))
console.log({
firstSuspense,
secondSuspense,
})
expect(secondSuspense.time - firstSuspense.time).toBeGreaterThanOrEqual(
2 * 1000
)
})
it('should properly handle prerender for bot request', async () => {
const res = await fetchViaHTTP(appPort, '/isr/first', undefined, {
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +path_to_url
'x-matched-path': '/isr/first',
},
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#page').text()).toBe('/isr/[slug]')
const rscRes = await fetchViaHTTP(appPort, '/isr/first.rsc', undefined, {
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +path_to_url
'x-matched-path': '/isr/first',
},
})
expect(rscRes.status).toBe(200)
})
it('should properly handle fallback for bot request', async () => {
const res = await fetchViaHTTP(appPort, '/isr/[slug]', undefined, {
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +path_to_url
'x-now-route-matches': '1=second&nxtPslug=new',
'x-matched-path': '/isr/[slug]',
},
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#page').text()).toBe('/isr/[slug]')
const rscRes = await fetchViaHTTP(appPort, '/isr/[slug].rsc', undefined, {
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +path_to_url
'x-now-route-matches': '1=second&nxtPslug=new',
'x-matched-path': '/isr/[slug]',
},
})
expect(rscRes.status).toBe(200)
})
describe('middleware rewrite', () => {
it('should work with a dynamic path', async () => {
const res = await fetchViaHTTP(
appPort,
'/rewrite-with-cookie',
undefined,
{
method: 'POST',
headers: {
'x-matched-path': '/_next/postponed/resume/rewrite/first-cookie',
},
body: rewritePostpone,
}
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#page').text()).toBe('/rewrite/[slug]')
expect($('#params').text()).toBe(JSON.stringify({ slug: 'first-cookie' }))
})
})
it('should still render when postponed is corrupted', async () => {
const random = Math.random().toString(36).substring(2)
const res = await fetchViaHTTP(appPort, '/dyn/' + random, undefined, {
method: 'POST',
headers: {
'x-matched-path': '/_next/postponed/resume/dyn/' + random,
},
// This is a corrupted postponed JSON payload.
body: '{',
})
expect(res.status).toBe(200)
const html = await res.text()
// Expect that the closing HTML tag is still present, indicating a
// successful render.
expect(html).toContain('</html>')
})
it('should send cache tags in minimal mode for ISR', async () => {
for (const [path, tags] of [
[
'/isr/first',
'isr-page,_N_T_/layout,_N_T_/isr/layout,_N_T_/isr/[slug]/layout,_N_T_/isr/[slug]/page,_N_T_/isr/first',
],
[
'/isr/second',
'isr-page,_N_T_/layout,_N_T_/isr/layout,_N_T_/isr/[slug]/layout,_N_T_/isr/[slug]/page,_N_T_/isr/second',
],
[
'/api/isr/first',
'isr-page,_N_T_/layout,_N_T_/api/layout,_N_T_/api/isr/layout,_N_T_/api/isr/[slug]/layout,_N_T_/api/isr/[slug]/route,_N_T_/api/isr/first',
],
[
'/api/isr/second',
'isr-page,_N_T_/layout,_N_T_/api/layout,_N_T_/api/isr/layout,_N_T_/api/isr/[slug]/layout,_N_T_/api/isr/[slug]/route,_N_T_/api/isr/second',
],
]) {
require('console').error('checking', { path, tags })
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBe(tags)
}
})
it('should not send cache tags in minimal mode for SSR', async () => {
for (const path of [
'/ssr/first',
'/ssr/second',
'/api/ssr/first',
'/api/ssr/second',
]) {
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBeFalsy()
}
})
it('should not send invalid soft tags to cache handler', async () => {
for (const path of [
'/ssr/first',
'/ssr/second',
'/api/ssr/first',
'/api/ssr/second',
]) {
const res = await fetchViaHTTP(
appPort,
path,
{ hello: 'world' },
{
redirect: 'manual',
}
)
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBeFalsy()
}
})
it('should handle RSC requests', async () => {
const res = await fetchViaHTTP(appPort, '/dyn/first.rsc', undefined, {
headers: {
'x-matched-path': '/dyn/first',
},
})
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toEqual('text/x-component')
expect(res.headers.has('x-nextjs-postponed')).toBeFalse()
})
it('should handle prefetch RSC requests', async () => {
const res = await fetchViaHTTP(
appPort,
'/dyn/first.prefetch.rsc',
undefined,
{
headers: {
'x-matched-path': '/dyn/first',
},
}
)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toEqual('text/x-component')
expect(res.headers.has('x-nextjs-postponed')).toBeTrue()
})
})
``` | /content/code_sandbox/test/production/standalone-mode/required-server-files/required-server-files-ppr.test.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 2,707 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.