hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 0,
"code_window": [
"import { globalSceneState } from \"../scene\";\n",
"\n",
"export class LinearElementEditor {\n",
" public elementId: ExcalidrawElement[\"id\"];\n",
" public activePointIndex: number | null;\n",
" public draggingElementPointIndex: number | null;\n",
" public lastUncommittedPoint: Point | null;\n",
"\n",
" constructor(element: NonDeleted<ExcalidrawLinearElement>) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" public elementId: ExcalidrawElement[\"id\"] & {\n",
" _brand: \"excalidrawLinearElementId\";\n",
" };\n"
],
"file_path": "src/element/linearElementEditor.ts",
"type": "replace",
"edit_start_line_idx": 14
}
|
import React, { useState, useLayoutEffect } from "react";
import ReactDOM from "react-dom";
import * as Sentry from "@sentry/browser";
import * as SentryIntegrations from "@sentry/integrations";
import { EVENT } from "./constants";
import { TopErrorBoundary } from "./components/TopErrorBoundary";
import { InitializeApp } from "./components/InitializeApp";
import { IsMobileProvider } from "./is-mobile";
import App from "./components/App";
import { register as registerServiceWorker } from "./serviceWorker";
import "./css/styles.scss";
import { loadFromBlob } from "./data";
// On Apple mobile devices add the proprietary app icon and splashscreen markup.
// No one should have to do this manually, and eventually this annoyance will
// go away once https://bugs.webkit.org/show_bug.cgi?id=183937 is fixed.
if (
/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent) &&
!matchMedia("(display-mode: standalone)").matches
) {
import(/* webpackChunkName: "pwacompat" */ "pwacompat");
}
const SentryEnvHostnameMap: { [key: string]: string } = {
"excalidraw.com": "production",
"vercel.app": "staging",
};
const REACT_APP_DISABLE_SENTRY =
process.env.REACT_APP_DISABLE_SENTRY === "true";
const REACT_APP_GIT_SHA = process.env.REACT_APP_GIT_SHA as string;
// Disable Sentry locally or inside the Docker to avoid noise/respect privacy
const onlineEnv =
!REACT_APP_DISABLE_SENTRY &&
Object.keys(SentryEnvHostnameMap).find(
(item) => window.location.hostname.indexOf(item) >= 0,
);
Sentry.init({
dsn: onlineEnv
? "https://[email protected]/5179260"
: undefined,
environment: onlineEnv ? SentryEnvHostnameMap[onlineEnv] : undefined,
release: REACT_APP_GIT_SHA,
ignoreErrors: [
"undefined is not an object (evaluating 'window.__pad.performLoop')", // Only happens on Safari, but spams our servers. Doesn't break anything
],
integrations: [
new SentryIntegrations.CaptureConsole({
levels: ["error"],
}),
],
beforeSend(event) {
if (event.request?.url) {
event.request.url = event.request.url.replace(/#.*$/, "");
}
return event;
},
});
window.__EXCALIDRAW_SHA__ = REACT_APP_GIT_SHA;
// Block pinch-zooming on iOS outside of the content area
document.addEventListener(
"touchmove",
(event) => {
// @ts-ignore
if (event.scale !== 1) {
event.preventDefault();
}
},
{ passive: false },
);
function ExcalidrawApp() {
const [dimensions, setDimensions] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
const onResize = () => {
setDimensions({
width: window.innerWidth,
height: window.innerHeight,
});
};
useLayoutEffect(() => {
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
const { width, height } = dimensions;
return (
<TopErrorBoundary>
<IsMobileProvider>
<InitializeApp>
<App width={width} height={height} />
</InitializeApp>
</IsMobileProvider>
</TopErrorBoundary>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<ExcalidrawApp />, rootElement);
registerServiceWorker({
onUpdate: (registration) => {
const waitingServiceWorker = registration.waiting;
if (waitingServiceWorker) {
waitingServiceWorker.addEventListener(
EVENT.STATE_CHANGE,
(event: Event) => {
const target = event.target as ServiceWorker;
const state = target.state as ServiceWorkerState;
if (state === "activated") {
window.location.reload();
}
},
);
waitingServiceWorker.postMessage({ type: "SKIP_WAITING" });
}
},
});
if ("launchQueue" in window && "LaunchParams" in window) {
(window as any).launchQueue.setConsumer(
async (launchParams: { files: any[] }) => {
if (!launchParams.files.length) {
return;
}
const fileHandle = launchParams.files[0];
const blob = await fileHandle.getFile();
loadFromBlob(blob);
},
);
}
|
src/index.tsx
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.005102013237774372,
0.0005096099921502173,
0.00016641632828395814,
0.00017303091590292752,
0.0012276312336325645
] |
{
"id": 0,
"code_window": [
"import { globalSceneState } from \"../scene\";\n",
"\n",
"export class LinearElementEditor {\n",
" public elementId: ExcalidrawElement[\"id\"];\n",
" public activePointIndex: number | null;\n",
" public draggingElementPointIndex: number | null;\n",
" public lastUncommittedPoint: Point | null;\n",
"\n",
" constructor(element: NonDeleted<ExcalidrawLinearElement>) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" public elementId: ExcalidrawElement[\"id\"] & {\n",
" _brand: \"excalidrawLinearElementId\";\n",
" };\n"
],
"file_path": "src/element/linearElementEditor.ts",
"type": "replace",
"edit_start_line_idx": 14
}
|
import { NonDeletedExcalidrawElement } from "./types";
import { getCommonBounds } from "./bounds";
import { mutateElement } from "./mutateElement";
import { SHAPES } from "../shapes";
import { getPerfectElementSize } from "./sizeHelpers";
export const dragSelectedElements = (
selectedElements: NonDeletedExcalidrawElement[],
pointerX: number,
pointerY: number,
) => {
const [x1, y1] = getCommonBounds(selectedElements);
selectedElements.forEach((element) => {
mutateElement(element, {
x: pointerX + element.x - x1,
y: pointerY + element.y - y1,
});
});
};
export const getDragOffsetXY = (
selectedElements: NonDeletedExcalidrawElement[],
x: number,
y: number,
): [number, number] => {
const [x1, y1] = getCommonBounds(selectedElements);
return [x - x1, y - y1];
};
export const dragNewElement = (
draggingElement: NonDeletedExcalidrawElement,
elementType: typeof SHAPES[number]["value"],
originX: number,
originY: number,
x: number,
y: number,
width: number,
height: number,
isResizeWithSidesSameLength: boolean,
isResizeCenterPoint: boolean,
) => {
if (isResizeWithSidesSameLength) {
({ width, height } = getPerfectElementSize(
elementType,
width,
y < originY ? -height : height,
));
if (height < 0) {
height = -height;
}
}
let newX = x < originX ? originX - width : originX;
let newY = y < originY ? originY - height : originY;
if (isResizeCenterPoint) {
width += width;
height += height;
newX = originX - width / 2;
newY = originY - height / 2;
}
if (width !== 0 && height !== 0) {
mutateElement(draggingElement, {
x: newX,
y: newY,
width: width,
height: height,
});
}
};
|
src/element/dragElements.ts
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.01195084024220705,
0.002303533023223281,
0.00016763099119998515,
0.0002583040331955999,
0.00381185719743371
] |
{
"id": 1,
"code_window": [
" public lastUncommittedPoint: Point | null;\n",
"\n",
" constructor(element: NonDeleted<ExcalidrawLinearElement>) {\n",
" LinearElementEditor.normalizePoints(element);\n",
"\n",
" this.elementId = element.id;\n",
" this.activePointIndex = null;\n",
" this.lastUncommittedPoint = null;\n",
" this.draggingElementPointIndex = null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.elementId = element.id as string & {\n",
" _brand: \"excalidrawLinearElementId\";\n",
" };\n"
],
"file_path": "src/element/linearElementEditor.ts",
"type": "replace",
"edit_start_line_idx": 22
}
|
import {
NonDeleted,
ExcalidrawLinearElement,
ExcalidrawElement,
} from "./types";
import { distance2d, rotate, isPathALoop } from "../math";
import { getElementAbsoluteCoords } from ".";
import { getElementPointsCoords } from "./bounds";
import { Point, AppState } from "../types";
import { mutateElement } from "./mutateElement";
import { SceneHistory } from "../history";
import { globalSceneState } from "../scene";
export class LinearElementEditor {
public elementId: ExcalidrawElement["id"];
public activePointIndex: number | null;
public draggingElementPointIndex: number | null;
public lastUncommittedPoint: Point | null;
constructor(element: NonDeleted<ExcalidrawLinearElement>) {
LinearElementEditor.normalizePoints(element);
this.elementId = element.id;
this.activePointIndex = null;
this.lastUncommittedPoint = null;
this.draggingElementPointIndex = null;
}
// ---------------------------------------------------------------------------
// static methods
// ---------------------------------------------------------------------------
static POINT_HANDLE_SIZE = 20;
static getElement(id: ExcalidrawElement["id"]) {
const element = globalSceneState.getNonDeletedElement(id);
if (element) {
return element as NonDeleted<ExcalidrawLinearElement>;
}
return null;
}
/** @returns whether point was dragged */
static handlePointDragging(
appState: AppState,
setState: React.Component<any, AppState>["setState"],
scenePointerX: number,
scenePointerY: number,
lastX: number,
lastY: number,
): boolean {
if (!appState.editingLinearElement) {
return false;
}
const { editingLinearElement } = appState;
let { draggingElementPointIndex, elementId } = editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return false;
}
const clickedPointIndex =
draggingElementPointIndex ??
LinearElementEditor.getPointIndexUnderCursor(
element,
appState.zoom,
scenePointerX,
scenePointerY,
);
draggingElementPointIndex = draggingElementPointIndex ?? clickedPointIndex;
if (draggingElementPointIndex > -1) {
if (
editingLinearElement.draggingElementPointIndex !==
draggingElementPointIndex ||
editingLinearElement.activePointIndex !== clickedPointIndex
) {
setState({
editingLinearElement: {
...editingLinearElement,
draggingElementPointIndex,
activePointIndex: clickedPointIndex,
},
});
}
const [deltaX, deltaY] = rotate(
scenePointerX - lastX,
scenePointerY - lastY,
0,
0,
-element.angle,
);
const targetPoint = element.points[clickedPointIndex];
LinearElementEditor.movePoint(element, clickedPointIndex, [
targetPoint[0] + deltaX,
targetPoint[1] + deltaY,
]);
return true;
}
return false;
}
static handlePointerUp(
editingLinearElement: LinearElementEditor,
): LinearElementEditor {
const { elementId, draggingElementPointIndex } = editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return editingLinearElement;
}
if (
draggingElementPointIndex !== null &&
(draggingElementPointIndex === 0 ||
draggingElementPointIndex === element.points.length - 1) &&
isPathALoop(element.points)
) {
LinearElementEditor.movePoint(
element,
draggingElementPointIndex,
draggingElementPointIndex === 0
? element.points[element.points.length - 1]
: element.points[0],
);
}
if (draggingElementPointIndex !== null) {
return {
...editingLinearElement,
draggingElementPointIndex: null,
};
}
return editingLinearElement;
}
static handlePointerDown(
event: React.PointerEvent<HTMLCanvasElement>,
appState: AppState,
setState: React.Component<any, AppState>["setState"],
history: SceneHistory,
scenePointerX: number,
scenePointerY: number,
): {
didAddPoint: boolean;
hitElement: ExcalidrawElement | null;
} {
const ret: ReturnType<typeof LinearElementEditor["handlePointerDown"]> = {
didAddPoint: false,
hitElement: null,
};
if (!appState.editingLinearElement) {
return ret;
}
const { elementId } = appState.editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return ret;
}
if (event.altKey) {
if (!appState.editingLinearElement.lastUncommittedPoint) {
mutateElement(element, {
points: [
...element.points,
LinearElementEditor.createPointAt(
element,
scenePointerX,
scenePointerY,
),
],
});
}
history.resumeRecording();
setState({
editingLinearElement: {
...appState.editingLinearElement,
activePointIndex: element.points.length - 1,
lastUncommittedPoint: null,
},
});
ret.didAddPoint = true;
return ret;
}
const clickedPointIndex = LinearElementEditor.getPointIndexUnderCursor(
element,
appState.zoom,
scenePointerX,
scenePointerY,
);
// if we clicked on a point, set the element as hitElement otherwise
// it would get deselected if the point is outside the hitbox area
if (clickedPointIndex > -1) {
ret.hitElement = element;
}
setState({
editingLinearElement: {
...appState.editingLinearElement,
activePointIndex: clickedPointIndex > -1 ? clickedPointIndex : null,
},
});
return ret;
}
static handlePointerMove(
event: React.PointerEvent<HTMLCanvasElement>,
scenePointerX: number,
scenePointerY: number,
editingLinearElement: LinearElementEditor,
): LinearElementEditor {
const { elementId, lastUncommittedPoint } = editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return editingLinearElement;
}
const { points } = element;
const lastPoint = points[points.length - 1];
if (!event.altKey) {
if (lastPoint === lastUncommittedPoint) {
LinearElementEditor.movePoint(element, points.length - 1, "delete");
}
return editingLinearElement;
}
const newPoint = LinearElementEditor.createPointAt(
element,
scenePointerX,
scenePointerY,
);
if (lastPoint === lastUncommittedPoint) {
LinearElementEditor.movePoint(
element,
element.points.length - 1,
newPoint,
);
} else {
LinearElementEditor.movePoint(element, "new", newPoint);
}
return {
...editingLinearElement,
lastUncommittedPoint: element.points[element.points.length - 1],
};
}
static getPointsGlobalCoordinates(
element: NonDeleted<ExcalidrawLinearElement>,
) {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
const cx = (x1 + x2) / 2;
const cy = (y1 + y2) / 2;
return element.points.map((point) => {
let { x, y } = element;
[x, y] = rotate(x + point[0], y + point[1], cx, cy, element.angle);
return [x, y];
});
}
static getPointIndexUnderCursor(
element: NonDeleted<ExcalidrawLinearElement>,
zoom: AppState["zoom"],
x: number,
y: number,
) {
const pointHandles = this.getPointsGlobalCoordinates(element);
let idx = pointHandles.length;
// loop from right to left because points on the right are rendered over
// points on the left, thus should take precedence when clicking, if they
// overlap
while (--idx > -1) {
const point = pointHandles[idx];
if (
distance2d(x, y, point[0], point[1]) * zoom <
// +1px to account for outline stroke
this.POINT_HANDLE_SIZE / 2 + 1
) {
return idx;
}
}
return -1;
}
static createPointAt(
element: NonDeleted<ExcalidrawLinearElement>,
scenePointerX: number,
scenePointerY: number,
): Point {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
const cx = (x1 + x2) / 2;
const cy = (y1 + y2) / 2;
const [rotatedX, rotatedY] = rotate(
scenePointerX,
scenePointerY,
cx,
cy,
-element.angle,
);
return [rotatedX - element.x, rotatedY - element.y];
}
// element-mutating methods
// ---------------------------------------------------------------------------
/**
* Normalizes line points so that the start point is at [0,0]. This is
* expected in various parts of the codebase.
*/
static normalizePoints(element: NonDeleted<ExcalidrawLinearElement>) {
const { points } = element;
const offsetX = points[0][0];
const offsetY = points[0][1];
mutateElement(element, {
points: points.map((point, _idx) => {
return [point[0] - offsetX, point[1] - offsetY] as const;
}),
x: element.x + offsetX,
y: element.y + offsetY,
});
}
static movePoint(
element: NonDeleted<ExcalidrawLinearElement>,
pointIndex: number | "new",
targetPosition: Point | "delete",
) {
const { points } = element;
// in case we're moving start point, instead of modifying its position
// which would break the invariant of it being at [0,0], we move
// all the other points in the opposite direction by delta to
// offset it. We do the same with actual element.x/y position, so
// this hacks are completely transparent to the user.
let offsetX = 0;
let offsetY = 0;
let nextPoints: (readonly [number, number])[];
if (targetPosition === "delete") {
// remove point
if (pointIndex === "new") {
throw new Error("invalid args in movePoint");
}
nextPoints = points.slice();
nextPoints.splice(pointIndex, 1);
if (pointIndex === 0) {
// if deleting first point, make the next to be [0,0] and recalculate
// positions of the rest with respect to it
offsetX = nextPoints[0][0];
offsetY = nextPoints[0][1];
nextPoints = nextPoints.map((point, idx) => {
if (idx === 0) {
return [0, 0];
}
return [point[0] - offsetX, point[1] - offsetY];
});
}
} else if (pointIndex === "new") {
nextPoints = [...points, targetPosition];
} else {
const deltaX = targetPosition[0] - points[pointIndex][0];
const deltaY = targetPosition[1] - points[pointIndex][1];
nextPoints = points.map((point, idx) => {
if (idx === pointIndex) {
if (idx === 0) {
offsetX = deltaX;
offsetY = deltaY;
return point;
}
offsetX = 0;
offsetY = 0;
return [point[0] + deltaX, point[1] + deltaY] as const;
}
return offsetX || offsetY
? ([point[0] - offsetX, point[1] - offsetY] as const)
: point;
});
}
const nextCoords = getElementPointsCoords(element, nextPoints);
const prevCoords = getElementPointsCoords(element, points);
const nextCenterX = (nextCoords[0] + nextCoords[2]) / 2;
const nextCenterY = (nextCoords[1] + nextCoords[3]) / 2;
const prevCenterX = (prevCoords[0] + prevCoords[2]) / 2;
const prevCenterY = (prevCoords[1] + prevCoords[3]) / 2;
const dX = prevCenterX - nextCenterX;
const dY = prevCenterY - nextCenterY;
const rotated = rotate(offsetX, offsetY, dX, dY, element.angle);
mutateElement(element, {
points: nextPoints,
x: element.x + rotated[0],
y: element.y + rotated[1],
});
}
}
|
src/element/linearElementEditor.ts
| 1 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.9987207055091858,
0.16519662737846375,
0.00016532566223759204,
0.0031158572528511286,
0.3536895215511322
] |
{
"id": 1,
"code_window": [
" public lastUncommittedPoint: Point | null;\n",
"\n",
" constructor(element: NonDeleted<ExcalidrawLinearElement>) {\n",
" LinearElementEditor.normalizePoints(element);\n",
"\n",
" this.elementId = element.id;\n",
" this.activePointIndex = null;\n",
" this.lastUncommittedPoint = null;\n",
" this.draggingElementPointIndex = null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.elementId = element.id as string & {\n",
" _brand: \"excalidrawLinearElementId\";\n",
" };\n"
],
"file_path": "src/element/linearElementEditor.ts",
"type": "replace",
"edit_start_line_idx": 22
}
|
import React from "react";
import { t } from "../i18n";
import { NonDeletedExcalidrawElement } from "../element/types";
import { getSelectedElements } from "../scene";
import "./HintViewer.scss";
import { AppState } from "../types";
import { isLinearElement } from "../element/typeChecks";
import { getShortcutKey } from "../utils";
interface Hint {
appState: AppState;
elements: readonly NonDeletedExcalidrawElement[];
}
const getHints = ({ appState, elements }: Hint) => {
const { elementType, isResizing, isRotating, lastPointerDownWith } = appState;
const multiMode = appState.multiElement !== null;
if (elementType === "arrow" || elementType === "line") {
if (!multiMode) {
return t("hints.linearElement");
}
return t("hints.linearElementMulti");
}
if (elementType === "draw") {
return t("hints.freeDraw");
}
const selectedElements = getSelectedElements(elements, appState);
if (
isResizing &&
lastPointerDownWith === "mouse" &&
selectedElements.length === 1
) {
const targetElement = selectedElements[0];
if (isLinearElement(targetElement) && targetElement.points.length > 2) {
return null;
}
return t("hints.resize");
}
if (isRotating && lastPointerDownWith === "mouse") {
return t("hints.rotate");
}
if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) {
if (appState.editingLinearElement) {
return appState.editingLinearElement.activePointIndex
? t("hints.lineEditor_pointSelected")
: t("hints.lineEditor_nothingSelected");
}
return t("hints.lineEditor_info");
}
return null;
};
export const HintViewer = ({ appState, elements }: Hint) => {
let hint = getHints({
appState,
elements,
});
if (!hint) {
return null;
}
hint = getShortcutKey(hint);
return (
<div className="HintViewer">
<span>{hint}</span>
</div>
);
};
|
src/components/HintViewer.tsx
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.0012783135753124952,
0.000428774073952809,
0.00016555897309444845,
0.0002078855031868443,
0.00038070970913395286
] |
{
"id": 1,
"code_window": [
" public lastUncommittedPoint: Point | null;\n",
"\n",
" constructor(element: NonDeleted<ExcalidrawLinearElement>) {\n",
" LinearElementEditor.normalizePoints(element);\n",
"\n",
" this.elementId = element.id;\n",
" this.activePointIndex = null;\n",
" this.lastUncommittedPoint = null;\n",
" this.draggingElementPointIndex = null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.elementId = element.id as string & {\n",
" _brand: \"excalidrawLinearElementId\";\n",
" };\n"
],
"file_path": "src/element/linearElementEditor.ts",
"type": "replace",
"edit_start_line_idx": 22
}
|
import React, { useState } from "react";
import { t } from "../i18n";
import { Dialog } from "./Dialog";
export const ErrorDialog = ({
message,
onClose,
}: {
message: string;
onClose?: () => void;
}) => {
const [modalIsShown, setModalIsShown] = useState(!!message);
const handleClose = React.useCallback(() => {
setModalIsShown(false);
if (onClose) {
onClose();
}
}, [onClose]);
return (
<>
{modalIsShown && (
<Dialog
maxWidth={500}
onCloseRequest={handleClose}
title={t("errorDialog.title")}
>
<div>{message}</div>
</Dialog>
)}
</>
);
};
|
src/components/ErrorDialog.tsx
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.0001751571981003508,
0.0001740702718961984,
0.00017177616246044636,
0.00017467387078795582,
0.0000013393565723163192
] |
{
"id": 1,
"code_window": [
" public lastUncommittedPoint: Point | null;\n",
"\n",
" constructor(element: NonDeleted<ExcalidrawLinearElement>) {\n",
" LinearElementEditor.normalizePoints(element);\n",
"\n",
" this.elementId = element.id;\n",
" this.activePointIndex = null;\n",
" this.lastUncommittedPoint = null;\n",
" this.draggingElementPointIndex = null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.elementId = element.id as string & {\n",
" _brand: \"excalidrawLinearElementId\";\n",
" };\n"
],
"file_path": "src/element/linearElementEditor.ts",
"type": "replace",
"edit_start_line_idx": 22
}
|
export { actionDeleteSelected } from "./actionDeleteSelected";
export {
actionBringForward,
actionBringToFront,
actionSendBackward,
actionSendToBack,
} from "./actionZindex";
export { actionSelectAll } from "./actionSelectAll";
export { actionDuplicateSelection } from "./actionDuplicateSelection";
export {
actionChangeStrokeColor,
actionChangeBackgroundColor,
actionChangeStrokeWidth,
actionChangeFillStyle,
actionChangeSloppiness,
actionChangeOpacity,
actionChangeFontSize,
actionChangeFontFamily,
actionChangeTextAlign,
} from "./actionProperties";
export {
actionChangeViewBackgroundColor,
actionClearCanvas,
actionZoomIn,
actionZoomOut,
actionResetZoom,
actionZoomToFit,
} from "./actionCanvas";
export { actionFinalize } from "./actionFinalize";
export {
actionChangeProjectName,
actionChangeExportBackground,
actionSaveScene,
actionSaveAsScene,
actionLoadScene,
} from "./actionExport";
export { actionCopyStyles, actionPasteStyles } from "./actionStyles";
export {
actionToggleCanvasMenu,
actionToggleEditMenu,
actionFullScreen,
actionShortcuts,
} from "./actionMenu";
export { actionGroup, actionUngroup } from "./actionGroup";
export { actionGoToCollaborator } from "./actionNavigate";
export { actionAddToLibrary } from "./actionAddToLibrary";
|
src/actions/index.ts
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.00017698798910714686,
0.00017550964548718184,
0.00017269994714297354,
0.00017602900334168226,
0.0000014173396039041108
] |
{
"id": 2,
"code_window": [
" // static methods\n",
" // ---------------------------------------------------------------------------\n",
"\n",
" static POINT_HANDLE_SIZE = 20;\n",
"\n",
" static getElement(id: ExcalidrawElement[\"id\"]) {\n",
" const element = globalSceneState.getNonDeletedElement(id);\n",
" if (element) {\n",
" return element as NonDeleted<ExcalidrawLinearElement>;\n",
" }\n",
" return null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * @param id the `elementId` from the instance of this class (so that we can\n",
" * statically guarantee this method returns an ExcalidrawLinearElement)\n",
" */\n",
" static getElement(id: InstanceType<typeof LinearElementEditor>[\"elementId\"]) {\n"
],
"file_path": "src/element/linearElementEditor.ts",
"type": "replace",
"edit_start_line_idx": 34
}
|
import {
NonDeleted,
ExcalidrawLinearElement,
ExcalidrawElement,
} from "./types";
import { distance2d, rotate, isPathALoop } from "../math";
import { getElementAbsoluteCoords } from ".";
import { getElementPointsCoords } from "./bounds";
import { Point, AppState } from "../types";
import { mutateElement } from "./mutateElement";
import { SceneHistory } from "../history";
import { globalSceneState } from "../scene";
export class LinearElementEditor {
public elementId: ExcalidrawElement["id"];
public activePointIndex: number | null;
public draggingElementPointIndex: number | null;
public lastUncommittedPoint: Point | null;
constructor(element: NonDeleted<ExcalidrawLinearElement>) {
LinearElementEditor.normalizePoints(element);
this.elementId = element.id;
this.activePointIndex = null;
this.lastUncommittedPoint = null;
this.draggingElementPointIndex = null;
}
// ---------------------------------------------------------------------------
// static methods
// ---------------------------------------------------------------------------
static POINT_HANDLE_SIZE = 20;
static getElement(id: ExcalidrawElement["id"]) {
const element = globalSceneState.getNonDeletedElement(id);
if (element) {
return element as NonDeleted<ExcalidrawLinearElement>;
}
return null;
}
/** @returns whether point was dragged */
static handlePointDragging(
appState: AppState,
setState: React.Component<any, AppState>["setState"],
scenePointerX: number,
scenePointerY: number,
lastX: number,
lastY: number,
): boolean {
if (!appState.editingLinearElement) {
return false;
}
const { editingLinearElement } = appState;
let { draggingElementPointIndex, elementId } = editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return false;
}
const clickedPointIndex =
draggingElementPointIndex ??
LinearElementEditor.getPointIndexUnderCursor(
element,
appState.zoom,
scenePointerX,
scenePointerY,
);
draggingElementPointIndex = draggingElementPointIndex ?? clickedPointIndex;
if (draggingElementPointIndex > -1) {
if (
editingLinearElement.draggingElementPointIndex !==
draggingElementPointIndex ||
editingLinearElement.activePointIndex !== clickedPointIndex
) {
setState({
editingLinearElement: {
...editingLinearElement,
draggingElementPointIndex,
activePointIndex: clickedPointIndex,
},
});
}
const [deltaX, deltaY] = rotate(
scenePointerX - lastX,
scenePointerY - lastY,
0,
0,
-element.angle,
);
const targetPoint = element.points[clickedPointIndex];
LinearElementEditor.movePoint(element, clickedPointIndex, [
targetPoint[0] + deltaX,
targetPoint[1] + deltaY,
]);
return true;
}
return false;
}
static handlePointerUp(
editingLinearElement: LinearElementEditor,
): LinearElementEditor {
const { elementId, draggingElementPointIndex } = editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return editingLinearElement;
}
if (
draggingElementPointIndex !== null &&
(draggingElementPointIndex === 0 ||
draggingElementPointIndex === element.points.length - 1) &&
isPathALoop(element.points)
) {
LinearElementEditor.movePoint(
element,
draggingElementPointIndex,
draggingElementPointIndex === 0
? element.points[element.points.length - 1]
: element.points[0],
);
}
if (draggingElementPointIndex !== null) {
return {
...editingLinearElement,
draggingElementPointIndex: null,
};
}
return editingLinearElement;
}
static handlePointerDown(
event: React.PointerEvent<HTMLCanvasElement>,
appState: AppState,
setState: React.Component<any, AppState>["setState"],
history: SceneHistory,
scenePointerX: number,
scenePointerY: number,
): {
didAddPoint: boolean;
hitElement: ExcalidrawElement | null;
} {
const ret: ReturnType<typeof LinearElementEditor["handlePointerDown"]> = {
didAddPoint: false,
hitElement: null,
};
if (!appState.editingLinearElement) {
return ret;
}
const { elementId } = appState.editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return ret;
}
if (event.altKey) {
if (!appState.editingLinearElement.lastUncommittedPoint) {
mutateElement(element, {
points: [
...element.points,
LinearElementEditor.createPointAt(
element,
scenePointerX,
scenePointerY,
),
],
});
}
history.resumeRecording();
setState({
editingLinearElement: {
...appState.editingLinearElement,
activePointIndex: element.points.length - 1,
lastUncommittedPoint: null,
},
});
ret.didAddPoint = true;
return ret;
}
const clickedPointIndex = LinearElementEditor.getPointIndexUnderCursor(
element,
appState.zoom,
scenePointerX,
scenePointerY,
);
// if we clicked on a point, set the element as hitElement otherwise
// it would get deselected if the point is outside the hitbox area
if (clickedPointIndex > -1) {
ret.hitElement = element;
}
setState({
editingLinearElement: {
...appState.editingLinearElement,
activePointIndex: clickedPointIndex > -1 ? clickedPointIndex : null,
},
});
return ret;
}
static handlePointerMove(
event: React.PointerEvent<HTMLCanvasElement>,
scenePointerX: number,
scenePointerY: number,
editingLinearElement: LinearElementEditor,
): LinearElementEditor {
const { elementId, lastUncommittedPoint } = editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return editingLinearElement;
}
const { points } = element;
const lastPoint = points[points.length - 1];
if (!event.altKey) {
if (lastPoint === lastUncommittedPoint) {
LinearElementEditor.movePoint(element, points.length - 1, "delete");
}
return editingLinearElement;
}
const newPoint = LinearElementEditor.createPointAt(
element,
scenePointerX,
scenePointerY,
);
if (lastPoint === lastUncommittedPoint) {
LinearElementEditor.movePoint(
element,
element.points.length - 1,
newPoint,
);
} else {
LinearElementEditor.movePoint(element, "new", newPoint);
}
return {
...editingLinearElement,
lastUncommittedPoint: element.points[element.points.length - 1],
};
}
static getPointsGlobalCoordinates(
element: NonDeleted<ExcalidrawLinearElement>,
) {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
const cx = (x1 + x2) / 2;
const cy = (y1 + y2) / 2;
return element.points.map((point) => {
let { x, y } = element;
[x, y] = rotate(x + point[0], y + point[1], cx, cy, element.angle);
return [x, y];
});
}
static getPointIndexUnderCursor(
element: NonDeleted<ExcalidrawLinearElement>,
zoom: AppState["zoom"],
x: number,
y: number,
) {
const pointHandles = this.getPointsGlobalCoordinates(element);
let idx = pointHandles.length;
// loop from right to left because points on the right are rendered over
// points on the left, thus should take precedence when clicking, if they
// overlap
while (--idx > -1) {
const point = pointHandles[idx];
if (
distance2d(x, y, point[0], point[1]) * zoom <
// +1px to account for outline stroke
this.POINT_HANDLE_SIZE / 2 + 1
) {
return idx;
}
}
return -1;
}
static createPointAt(
element: NonDeleted<ExcalidrawLinearElement>,
scenePointerX: number,
scenePointerY: number,
): Point {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
const cx = (x1 + x2) / 2;
const cy = (y1 + y2) / 2;
const [rotatedX, rotatedY] = rotate(
scenePointerX,
scenePointerY,
cx,
cy,
-element.angle,
);
return [rotatedX - element.x, rotatedY - element.y];
}
// element-mutating methods
// ---------------------------------------------------------------------------
/**
* Normalizes line points so that the start point is at [0,0]. This is
* expected in various parts of the codebase.
*/
static normalizePoints(element: NonDeleted<ExcalidrawLinearElement>) {
const { points } = element;
const offsetX = points[0][0];
const offsetY = points[0][1];
mutateElement(element, {
points: points.map((point, _idx) => {
return [point[0] - offsetX, point[1] - offsetY] as const;
}),
x: element.x + offsetX,
y: element.y + offsetY,
});
}
static movePoint(
element: NonDeleted<ExcalidrawLinearElement>,
pointIndex: number | "new",
targetPosition: Point | "delete",
) {
const { points } = element;
// in case we're moving start point, instead of modifying its position
// which would break the invariant of it being at [0,0], we move
// all the other points in the opposite direction by delta to
// offset it. We do the same with actual element.x/y position, so
// this hacks are completely transparent to the user.
let offsetX = 0;
let offsetY = 0;
let nextPoints: (readonly [number, number])[];
if (targetPosition === "delete") {
// remove point
if (pointIndex === "new") {
throw new Error("invalid args in movePoint");
}
nextPoints = points.slice();
nextPoints.splice(pointIndex, 1);
if (pointIndex === 0) {
// if deleting first point, make the next to be [0,0] and recalculate
// positions of the rest with respect to it
offsetX = nextPoints[0][0];
offsetY = nextPoints[0][1];
nextPoints = nextPoints.map((point, idx) => {
if (idx === 0) {
return [0, 0];
}
return [point[0] - offsetX, point[1] - offsetY];
});
}
} else if (pointIndex === "new") {
nextPoints = [...points, targetPosition];
} else {
const deltaX = targetPosition[0] - points[pointIndex][0];
const deltaY = targetPosition[1] - points[pointIndex][1];
nextPoints = points.map((point, idx) => {
if (idx === pointIndex) {
if (idx === 0) {
offsetX = deltaX;
offsetY = deltaY;
return point;
}
offsetX = 0;
offsetY = 0;
return [point[0] + deltaX, point[1] + deltaY] as const;
}
return offsetX || offsetY
? ([point[0] - offsetX, point[1] - offsetY] as const)
: point;
});
}
const nextCoords = getElementPointsCoords(element, nextPoints);
const prevCoords = getElementPointsCoords(element, points);
const nextCenterX = (nextCoords[0] + nextCoords[2]) / 2;
const nextCenterY = (nextCoords[1] + nextCoords[3]) / 2;
const prevCenterX = (prevCoords[0] + prevCoords[2]) / 2;
const prevCenterY = (prevCoords[1] + prevCoords[3]) / 2;
const dX = prevCenterX - nextCenterX;
const dY = prevCenterY - nextCenterY;
const rotated = rotate(offsetX, offsetY, dX, dY, element.angle);
mutateElement(element, {
points: nextPoints,
x: element.x + rotated[0],
y: element.y + rotated[1],
});
}
}
|
src/element/linearElementEditor.ts
| 1 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.9985648989677429,
0.5495860576629639,
0.00016525504179298878,
0.8858627080917358,
0.46385520696640015
] |
{
"id": 2,
"code_window": [
" // static methods\n",
" // ---------------------------------------------------------------------------\n",
"\n",
" static POINT_HANDLE_SIZE = 20;\n",
"\n",
" static getElement(id: ExcalidrawElement[\"id\"]) {\n",
" const element = globalSceneState.getNonDeletedElement(id);\n",
" if (element) {\n",
" return element as NonDeleted<ExcalidrawLinearElement>;\n",
" }\n",
" return null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * @param id the `elementId` from the instance of this class (so that we can\n",
" * statically guarantee this method returns an ExcalidrawLinearElement)\n",
" */\n",
" static getElement(id: InstanceType<typeof LinearElementEditor>[\"elementId\"]) {\n"
],
"file_path": "src/element/linearElementEditor.ts",
"type": "replace",
"edit_start_line_idx": 34
}
|
import {
PointerType,
ExcalidrawLinearElement,
NonDeletedExcalidrawElement,
NonDeleted,
TextAlign,
ExcalidrawElement,
FontFamily,
GroupId,
} from "./element/types";
import { SHAPES } from "./shapes";
import { Point as RoughPoint } from "roughjs/bin/geometry";
import { SocketUpdateDataSource } from "./data";
import { LinearElementEditor } from "./element/linearElementEditor";
export type FlooredNumber = number & { _brand: "FlooredNumber" };
export type Point = Readonly<RoughPoint>;
export type Collaborator = {
pointer?: {
x: number;
y: number;
};
button?: "up" | "down";
selectedElementIds?: AppState["selectedElementIds"];
username?: string | null;
};
export type AppState = {
isLoading: boolean;
errorMessage: string | null;
draggingElement: NonDeletedExcalidrawElement | null;
resizingElement: NonDeletedExcalidrawElement | null;
multiElement: NonDeleted<ExcalidrawLinearElement> | null;
selectionElement: NonDeletedExcalidrawElement | null;
// element being edited, but not necessarily added to elements array yet
// (e.g. text element when typing into the input)
editingElement: NonDeletedExcalidrawElement | null;
editingLinearElement: LinearElementEditor | null;
elementType: typeof SHAPES[number]["value"];
elementLocked: boolean;
exportBackground: boolean;
shouldAddWatermark: boolean;
currentItemStrokeColor: string;
currentItemBackgroundColor: string;
currentItemFillStyle: string;
currentItemStrokeWidth: number;
currentItemStrokeStyle: ExcalidrawElement["strokeStyle"];
currentItemRoughness: number;
currentItemOpacity: number;
currentItemFontFamily: FontFamily;
currentItemFontSize: number;
currentItemTextAlign: TextAlign;
viewBackgroundColor: string;
scrollX: FlooredNumber;
scrollY: FlooredNumber;
cursorX: number;
cursorY: number;
cursorButton: "up" | "down";
scrolledOutside: boolean;
name: string;
username: string;
isCollaborating: boolean;
isResizing: boolean;
isRotating: boolean;
zoom: number;
openMenu: "canvas" | "shape" | null;
lastPointerDownWith: PointerType;
selectedElementIds: { [id: string]: boolean };
previousSelectedElementIds: { [id: string]: boolean };
collaborators: Map<string, Collaborator>;
shouldCacheIgnoreZoom: boolean;
showShortcutsDialog: boolean;
zenModeEnabled: boolean;
gridSize: number | null;
/** top-most selected groups (i.e. does not include nested groups) */
selectedGroupIds: { [groupId: string]: boolean };
/** group being edited when you drill down to its constituent element
(e.g. when you double-click on a group's element) */
editingGroupId: GroupId | null;
width: number;
height: number;
isLibraryOpen: boolean;
};
export type PointerCoords = Readonly<{
x: number;
y: number;
}>;
export type Gesture = {
pointers: Map<number, PointerCoords>;
lastCenter: { x: number; y: number } | null;
initialDistance: number | null;
initialScale: number | null;
};
export declare class GestureEvent extends UIEvent {
readonly rotation: number;
readonly scale: number;
}
export type SocketUpdateData = SocketUpdateDataSource[keyof SocketUpdateDataSource] & {
_brand: "socketUpdateData";
};
export type LibraryItems = readonly NonDeleted<ExcalidrawElement>[][];
export interface ExcalidrawProps {
width: number;
height: number;
}
|
src/types.ts
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.022492121905088425,
0.004521154332906008,
0.00017256876162718982,
0.0001768805377651006,
0.006888039410114288
] |
{
"id": 2,
"code_window": [
" // static methods\n",
" // ---------------------------------------------------------------------------\n",
"\n",
" static POINT_HANDLE_SIZE = 20;\n",
"\n",
" static getElement(id: ExcalidrawElement[\"id\"]) {\n",
" const element = globalSceneState.getNonDeletedElement(id);\n",
" if (element) {\n",
" return element as NonDeleted<ExcalidrawLinearElement>;\n",
" }\n",
" return null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * @param id the `elementId` from the instance of this class (so that we can\n",
" * statically guarantee this method returns an ExcalidrawLinearElement)\n",
" */\n",
" static getElement(id: InstanceType<typeof LinearElementEditor>[\"elementId\"]) {\n"
],
"file_path": "src/element/linearElementEditor.ts",
"type": "replace",
"edit_start_line_idx": 34
}
|
.prettierignore
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.00017293114797212183,
0.00017293114797212183,
0.00017293114797212183,
0.00017293114797212183,
0
] |
|
{
"id": 2,
"code_window": [
" // static methods\n",
" // ---------------------------------------------------------------------------\n",
"\n",
" static POINT_HANDLE_SIZE = 20;\n",
"\n",
" static getElement(id: ExcalidrawElement[\"id\"]) {\n",
" const element = globalSceneState.getNonDeletedElement(id);\n",
" if (element) {\n",
" return element as NonDeleted<ExcalidrawLinearElement>;\n",
" }\n",
" return null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * @param id the `elementId` from the instance of this class (so that we can\n",
" * statically guarantee this method returns an ExcalidrawLinearElement)\n",
" */\n",
" static getElement(id: InstanceType<typeof LinearElementEditor>[\"elementId\"]) {\n"
],
"file_path": "src/element/linearElementEditor.ts",
"type": "replace",
"edit_start_line_idx": 34
}
|
import React from "react";
import { Popover } from "./Popover";
import { render, unmountComponentAtNode } from "react-dom";
import "./ContextMenu.scss";
type ContextMenuOption = {
label: string;
action(): void;
};
type Props = {
options: ContextMenuOption[];
onCloseRequest?(): void;
top: number;
left: number;
};
const ContextMenu = ({ options, onCloseRequest, top, left }: Props) => (
<Popover
onCloseRequest={onCloseRequest}
top={top}
left={left}
fitInViewport={true}
>
<ul
className="context-menu"
onContextMenu={(event) => event.preventDefault()}
>
{options.map((option, idx) => (
<li key={idx} onClick={onCloseRequest}>
<ContextMenuOption {...option} />
</li>
))}
</ul>
</Popover>
);
const ContextMenuOption = ({ label, action }: ContextMenuOption) => (
<button className="context-menu-option" onClick={action}>
{label}
</button>
);
let contextMenuNode: HTMLDivElement;
const getContextMenuNode = (): HTMLDivElement => {
if (contextMenuNode) {
return contextMenuNode;
}
const div = document.createElement("div");
document.body.appendChild(div);
return (contextMenuNode = div);
};
type ContextMenuParams = {
options: (ContextMenuOption | false | null | undefined)[];
top: number;
left: number;
};
const handleClose = () => {
unmountComponentAtNode(getContextMenuNode());
};
export default {
push(params: ContextMenuParams) {
const options = Array.of<ContextMenuOption>();
params.options.forEach((option) => {
if (option) {
options.push(option);
}
});
if (options.length) {
render(
<ContextMenu
top={params.top}
left={params.left}
options={options}
onCloseRequest={handleClose}
/>,
getContextMenuNode(),
);
}
},
};
|
src/components/ContextMenu.tsx
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.0017487736186012626,
0.00034928228706121445,
0.00017018901417031884,
0.0001742147869663313,
0.0004948002751916647
] |
{
"id": 3,
"code_window": [
"import { getSelectedElements } from \"../scene/selection\";\n",
"\n",
"import { renderElement, renderElementToSvg } from \"./renderElement\";\n",
"import { getClientColors } from \"../clients\";\n",
"import { isLinearElement } from \"../element/typeChecks\";\n",
"import { LinearElementEditor } from \"../element/linearElementEditor\";\n",
"import {\n",
" isSelectedViaGroup,\n",
" getSelectedGroupIds,\n",
" getElementsInGroup,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 32
}
|
import { RoughCanvas } from "roughjs/bin/canvas";
import { RoughSVG } from "roughjs/bin/svg";
import oc from "open-color";
import { FlooredNumber, AppState } from "../types";
import {
ExcalidrawElement,
NonDeletedExcalidrawElement,
ExcalidrawLinearElement,
NonDeleted,
GroupId,
} from "../element/types";
import {
getElementAbsoluteCoords,
OMIT_SIDES_FOR_MULTIPLE_ELEMENTS,
handlerRectanglesFromCoords,
handlerRectangles,
getElementBounds,
getCommonBounds,
} from "../element";
import { roundRect } from "./roundRect";
import { SceneState } from "../scene/types";
import {
getScrollBars,
SCROLLBAR_COLOR,
SCROLLBAR_WIDTH,
} from "../scene/scrollbars";
import { getSelectedElements } from "../scene/selection";
import { renderElement, renderElementToSvg } from "./renderElement";
import { getClientColors } from "../clients";
import { isLinearElement } from "../element/typeChecks";
import { LinearElementEditor } from "../element/linearElementEditor";
import {
isSelectedViaGroup,
getSelectedGroupIds,
getElementsInGroup,
} from "../groups";
type HandlerRectanglesRet = keyof ReturnType<typeof handlerRectangles>;
const strokeRectWithRotation = (
context: CanvasRenderingContext2D,
x: number,
y: number,
width: number,
height: number,
cx: number,
cy: number,
angle: number,
fill?: boolean,
) => {
context.translate(cx, cy);
context.rotate(angle);
if (fill) {
context.fillRect(x - cx, y - cy, width, height);
}
context.strokeRect(x - cx, y - cy, width, height);
context.rotate(-angle);
context.translate(-cx, -cy);
};
const strokeCircle = (
context: CanvasRenderingContext2D,
x: number,
y: number,
width: number,
height: number,
) => {
context.beginPath();
context.arc(x + width / 2, y + height / 2, width / 2, 0, Math.PI * 2);
context.fill();
context.stroke();
};
const strokeGrid = (
context: CanvasRenderingContext2D,
gridSize: number,
offsetX: number,
offsetY: number,
width: number,
height: number,
) => {
const origStrokeStyle = context.strokeStyle;
context.strokeStyle = "rgba(0,0,0,0.1)";
context.beginPath();
for (let x = offsetX; x < offsetX + width + gridSize * 2; x += gridSize) {
context.moveTo(x, offsetY - gridSize);
context.lineTo(x, offsetY + height + gridSize * 2);
}
for (let y = offsetY; y < offsetY + height + gridSize * 2; y += gridSize) {
context.moveTo(offsetX - gridSize, y);
context.lineTo(offsetX + width + gridSize * 2, y);
}
context.stroke();
context.strokeStyle = origStrokeStyle;
};
const renderLinearPointHandles = (
context: CanvasRenderingContext2D,
appState: AppState,
sceneState: SceneState,
element: NonDeleted<ExcalidrawLinearElement>,
) => {
context.translate(sceneState.scrollX, sceneState.scrollY);
const origStrokeStyle = context.strokeStyle;
const lineWidth = context.lineWidth;
context.lineWidth = 1 / sceneState.zoom;
LinearElementEditor.getPointsGlobalCoordinates(element).forEach(
(point, idx) => {
context.strokeStyle = "red";
context.setLineDash([]);
context.fillStyle =
appState.editingLinearElement?.activePointIndex === idx
? "rgba(255, 127, 127, 0.9)"
: "rgba(255, 255, 255, 0.9)";
const { POINT_HANDLE_SIZE } = LinearElementEditor;
strokeCircle(
context,
point[0] - POINT_HANDLE_SIZE / 2 / sceneState.zoom,
point[1] - POINT_HANDLE_SIZE / 2 / sceneState.zoom,
POINT_HANDLE_SIZE / sceneState.zoom,
POINT_HANDLE_SIZE / sceneState.zoom,
);
},
);
context.setLineDash([]);
context.lineWidth = lineWidth;
context.translate(-sceneState.scrollX, -sceneState.scrollY);
context.strokeStyle = origStrokeStyle;
};
export const renderScene = (
elements: readonly NonDeletedExcalidrawElement[],
appState: AppState,
selectionElement: NonDeletedExcalidrawElement | null,
scale: number,
rc: RoughCanvas,
canvas: HTMLCanvasElement,
sceneState: SceneState,
// extra options, currently passed by export helper
{
renderScrollbars = true,
renderSelection = true,
// Whether to employ render optimizations to improve performance.
// Should not be turned on for export operations and similar, because it
// doesn't guarantee pixel-perfect output.
renderOptimizations = false,
renderGrid = true,
}: {
renderScrollbars?: boolean;
renderSelection?: boolean;
renderOptimizations?: boolean;
renderGrid?: boolean;
} = {},
) => {
if (!canvas) {
return { atLeastOneVisibleElement: false };
}
const context = canvas.getContext("2d")!;
context.scale(scale, scale);
// When doing calculations based on canvas width we should used normalized one
const normalizedCanvasWidth = canvas.width / scale;
const normalizedCanvasHeight = canvas.height / scale;
// Paint background
if (typeof sceneState.viewBackgroundColor === "string") {
const hasTransparence =
sceneState.viewBackgroundColor === "transparent" ||
sceneState.viewBackgroundColor.length === 5 || // #RGBA
sceneState.viewBackgroundColor.length === 9 || // #RRGGBBA
/(hsla|rgba)\(/.test(sceneState.viewBackgroundColor);
if (hasTransparence) {
context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
}
const fillStyle = context.fillStyle;
context.fillStyle = sceneState.viewBackgroundColor;
context.fillRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
context.fillStyle = fillStyle;
} else {
context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
}
// Apply zoom
const zoomTranslationX = (-normalizedCanvasWidth * (sceneState.zoom - 1)) / 2;
const zoomTranslationY =
(-normalizedCanvasHeight * (sceneState.zoom - 1)) / 2;
context.translate(zoomTranslationX, zoomTranslationY);
context.scale(sceneState.zoom, sceneState.zoom);
// Grid
if (renderGrid && appState.gridSize) {
strokeGrid(
context,
appState.gridSize,
-Math.ceil(zoomTranslationX / sceneState.zoom / appState.gridSize) *
appState.gridSize +
(sceneState.scrollX % appState.gridSize),
-Math.ceil(zoomTranslationY / sceneState.zoom / appState.gridSize) *
appState.gridSize +
(sceneState.scrollY % appState.gridSize),
normalizedCanvasWidth / sceneState.zoom,
normalizedCanvasHeight / sceneState.zoom,
);
}
// Paint visible elements
const visibleElements = elements.filter((element) =>
isVisibleElement(
element,
normalizedCanvasWidth,
normalizedCanvasHeight,
sceneState,
),
);
visibleElements.forEach((element) => {
renderElement(element, rc, context, renderOptimizations, sceneState);
if (
isLinearElement(element) &&
appState.editingLinearElement &&
appState.editingLinearElement.elementId === element.id
) {
renderLinearPointHandles(context, appState, sceneState, element);
}
});
// Paint selection element
if (selectionElement) {
renderElement(
selectionElement,
rc,
context,
renderOptimizations,
sceneState,
);
}
// Paint selected elements
if (
renderSelection &&
!appState.multiElement &&
!appState.editingLinearElement
) {
context.translate(sceneState.scrollX, sceneState.scrollY);
const selections = elements.reduce((acc, element) => {
const selectionColors = [];
// local user
if (
appState.selectedElementIds[element.id] &&
!isSelectedViaGroup(appState, element)
) {
selectionColors.push(oc.black);
}
// remote users
if (sceneState.remoteSelectedElementIds[element.id]) {
selectionColors.push(
...sceneState.remoteSelectedElementIds[element.id].map((socketId) => {
const { background } = getClientColors(socketId);
return background;
}),
);
}
if (selectionColors.length) {
const [
elementX1,
elementY1,
elementX2,
elementY2,
] = getElementAbsoluteCoords(element);
acc.push({
angle: element.angle,
elementX1,
elementY1,
elementX2,
elementY2,
selectionColors,
});
}
return acc;
}, [] as { angle: number; elementX1: number; elementY1: number; elementX2: number; elementY2: number; selectionColors: string[] }[]);
function addSelectionForGroupId(groupId: GroupId) {
const groupElements = getElementsInGroup(elements, groupId);
const [elementX1, elementY1, elementX2, elementY2] = getCommonBounds(
groupElements,
);
selections.push({
angle: 0,
elementX1,
elementX2,
elementY1,
elementY2,
selectionColors: [oc.black],
});
}
for (const groupId of getSelectedGroupIds(appState)) {
// TODO: support multiplayer selected group IDs
addSelectionForGroupId(groupId);
}
if (appState.editingGroupId) {
addSelectionForGroupId(appState.editingGroupId);
}
selections.forEach(
({
angle,
elementX1,
elementY1,
elementX2,
elementY2,
selectionColors,
}) => {
const elementWidth = elementX2 - elementX1;
const elementHeight = elementY2 - elementY1;
const initialLineDash = context.getLineDash();
const lineWidth = context.lineWidth;
const lineDashOffset = context.lineDashOffset;
const strokeStyle = context.strokeStyle;
const dashedLinePadding = 4 / sceneState.zoom;
const dashWidth = 8 / sceneState.zoom;
const spaceWidth = 4 / sceneState.zoom;
context.lineWidth = 1 / sceneState.zoom;
const count = selectionColors.length;
for (var i = 0; i < count; ++i) {
context.strokeStyle = selectionColors[i];
context.setLineDash([
dashWidth,
spaceWidth + (dashWidth + spaceWidth) * (count - 1),
]);
context.lineDashOffset = (dashWidth + spaceWidth) * i;
strokeRectWithRotation(
context,
elementX1 - dashedLinePadding,
elementY1 - dashedLinePadding,
elementWidth + dashedLinePadding * 2,
elementHeight + dashedLinePadding * 2,
elementX1 + elementWidth / 2,
elementY1 + elementHeight / 2,
angle,
);
}
context.lineDashOffset = lineDashOffset;
context.strokeStyle = strokeStyle;
context.lineWidth = lineWidth;
context.setLineDash(initialLineDash);
},
);
context.translate(-sceneState.scrollX, -sceneState.scrollY);
const locallySelectedElements = getSelectedElements(elements, appState);
// Paint resize handlers
if (locallySelectedElements.length === 1) {
context.translate(sceneState.scrollX, sceneState.scrollY);
context.fillStyle = oc.white;
const handlers = handlerRectangles(
locallySelectedElements[0],
sceneState.zoom,
);
Object.keys(handlers).forEach((key) => {
const handler = handlers[key as HandlerRectanglesRet];
if (handler !== undefined) {
const lineWidth = context.lineWidth;
context.lineWidth = 1 / sceneState.zoom;
if (key === "rotation") {
strokeCircle(
context,
handler[0],
handler[1],
handler[2],
handler[3],
);
} else {
strokeRectWithRotation(
context,
handler[0],
handler[1],
handler[2],
handler[3],
handler[0] + handler[2] / 2,
handler[1] + handler[3] / 2,
locallySelectedElements[0].angle,
true, // fill before stroke
);
}
context.lineWidth = lineWidth;
}
});
context.translate(-sceneState.scrollX, -sceneState.scrollY);
} else if (locallySelectedElements.length > 1 && !appState.isRotating) {
const dashedLinePadding = 4 / sceneState.zoom;
context.translate(sceneState.scrollX, sceneState.scrollY);
context.fillStyle = oc.white;
const [x1, y1, x2, y2] = getCommonBounds(locallySelectedElements);
const initialLineDash = context.getLineDash();
context.setLineDash([2 / sceneState.zoom]);
const lineWidth = context.lineWidth;
context.lineWidth = 1 / sceneState.zoom;
strokeRectWithRotation(
context,
x1 - dashedLinePadding,
y1 - dashedLinePadding,
x2 - x1 + dashedLinePadding * 2,
y2 - y1 + dashedLinePadding * 2,
(x1 + x2) / 2,
(y1 + y2) / 2,
0,
);
context.lineWidth = lineWidth;
context.setLineDash(initialLineDash);
const handlers = handlerRectanglesFromCoords(
[x1, y1, x2, y2],
0,
sceneState.zoom,
undefined,
OMIT_SIDES_FOR_MULTIPLE_ELEMENTS,
);
Object.keys(handlers).forEach((key) => {
const handler = handlers[key as HandlerRectanglesRet];
if (handler !== undefined) {
const lineWidth = context.lineWidth;
context.lineWidth = 1 / sceneState.zoom;
if (key === "rotation") {
strokeCircle(
context,
handler[0],
handler[1],
handler[2],
handler[3],
);
} else {
strokeRectWithRotation(
context,
handler[0],
handler[1],
handler[2],
handler[3],
handler[0] + handler[2] / 2,
handler[1] + handler[3] / 2,
0,
true, // fill before stroke
);
}
context.lineWidth = lineWidth;
}
});
context.translate(-sceneState.scrollX, -sceneState.scrollY);
}
}
// Reset zoom
context.scale(1 / sceneState.zoom, 1 / sceneState.zoom);
context.translate(-zoomTranslationX, -zoomTranslationY);
// Paint remote pointers
for (const clientId in sceneState.remotePointerViewportCoords) {
let { x, y } = sceneState.remotePointerViewportCoords[clientId];
const username = sceneState.remotePointerUsernames[clientId];
const width = 9;
const height = 14;
const isOutOfBounds =
x < 0 ||
x > normalizedCanvasWidth - width ||
y < 0 ||
y > normalizedCanvasHeight - height;
x = Math.max(x, 0);
x = Math.min(x, normalizedCanvasWidth - width);
y = Math.max(y, 0);
y = Math.min(y, normalizedCanvasHeight - height);
const { background, stroke } = getClientColors(clientId);
const strokeStyle = context.strokeStyle;
const fillStyle = context.fillStyle;
const globalAlpha = context.globalAlpha;
context.strokeStyle = stroke;
context.fillStyle = background;
if (isOutOfBounds) {
context.globalAlpha = 0.2;
}
if (
sceneState.remotePointerButton &&
sceneState.remotePointerButton[clientId] === "down"
) {
context.beginPath();
context.arc(x, y, 15, 0, 2 * Math.PI, false);
context.lineWidth = 3;
context.strokeStyle = "#ffffff88";
context.stroke();
context.closePath();
context.beginPath();
context.arc(x, y, 15, 0, 2 * Math.PI, false);
context.lineWidth = 1;
context.strokeStyle = stroke;
context.stroke();
context.closePath();
}
context.beginPath();
context.moveTo(x, y);
context.lineTo(x + 1, y + 14);
context.lineTo(x + 4, y + 9);
context.lineTo(x + 9, y + 10);
context.lineTo(x, y);
context.fill();
context.stroke();
if (!isOutOfBounds && username) {
const offsetX = x + width;
const offsetY = y + height;
const paddingHorizontal = 4;
const paddingVertical = 4;
const measure = context.measureText(username);
const measureHeight =
measure.actualBoundingBoxDescent + measure.actualBoundingBoxAscent;
// Border
context.fillStyle = stroke;
context.globalAlpha = globalAlpha;
context.fillRect(
offsetX - 1,
offsetY - 1,
measure.width + 2 * paddingHorizontal + 2,
measureHeight + 2 * paddingVertical + 2,
);
// Background
context.fillStyle = background;
context.fillRect(
offsetX,
offsetY,
measure.width + 2 * paddingHorizontal,
measureHeight + 2 * paddingVertical,
);
context.fillStyle = oc.white;
context.fillText(
username,
offsetX + paddingHorizontal,
offsetY + paddingVertical + measure.actualBoundingBoxAscent,
);
}
context.strokeStyle = strokeStyle;
context.fillStyle = fillStyle;
context.globalAlpha = globalAlpha;
context.closePath();
}
// Paint scrollbars
let scrollBars;
if (renderScrollbars) {
scrollBars = getScrollBars(
elements,
normalizedCanvasWidth,
normalizedCanvasHeight,
sceneState,
);
const fillStyle = context.fillStyle;
const strokeStyle = context.strokeStyle;
context.fillStyle = SCROLLBAR_COLOR;
context.strokeStyle = "rgba(255,255,255,0.8)";
[scrollBars.horizontal, scrollBars.vertical].forEach((scrollBar) => {
if (scrollBar) {
roundRect(
context,
scrollBar.x,
scrollBar.y,
scrollBar.width,
scrollBar.height,
SCROLLBAR_WIDTH / 2,
);
}
});
context.fillStyle = fillStyle;
context.strokeStyle = strokeStyle;
}
context.scale(1 / scale, 1 / scale);
return { atLeastOneVisibleElement: visibleElements.length > 0, scrollBars };
};
const isVisibleElement = (
element: ExcalidrawElement,
viewportWidth: number,
viewportHeight: number,
{
scrollX,
scrollY,
zoom,
}: {
scrollX: FlooredNumber;
scrollY: FlooredNumber;
zoom: number;
},
) => {
const [x1, y1, x2, y2] = getElementBounds(element);
// Apply zoom
const viewportWidthWithZoom = viewportWidth / zoom;
const viewportHeightWithZoom = viewportHeight / zoom;
const viewportWidthDiff = viewportWidth - viewportWidthWithZoom;
const viewportHeightDiff = viewportHeight - viewportHeightWithZoom;
return (
x2 + scrollX - viewportWidthDiff / 2 >= 0 &&
x1 + scrollX - viewportWidthDiff / 2 <= viewportWidthWithZoom &&
y2 + scrollY - viewportHeightDiff / 2 >= 0 &&
y1 + scrollY - viewportHeightDiff / 2 <= viewportHeightWithZoom
);
};
// This should be only called for exporting purposes
export const renderSceneToSvg = (
elements: readonly NonDeletedExcalidrawElement[],
rsvg: RoughSVG,
svgRoot: SVGElement,
{
offsetX = 0,
offsetY = 0,
}: {
offsetX?: number;
offsetY?: number;
} = {},
) => {
if (!svgRoot) {
return;
}
// render elements
elements.forEach((element) => {
if (!element.isDeleted) {
renderElementToSvg(
element,
rsvg,
svgRoot,
element.x + offsetX,
element.y + offsetY,
);
}
});
};
|
src/renderer/renderScene.ts
| 1 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.9936256408691406,
0.0165821835398674,
0.00016251124907284975,
0.00017646324704401195,
0.12124772369861603
] |
{
"id": 3,
"code_window": [
"import { getSelectedElements } from \"../scene/selection\";\n",
"\n",
"import { renderElement, renderElementToSvg } from \"./renderElement\";\n",
"import { getClientColors } from \"../clients\";\n",
"import { isLinearElement } from \"../element/typeChecks\";\n",
"import { LinearElementEditor } from \"../element/linearElementEditor\";\n",
"import {\n",
" isSelectedViaGroup,\n",
" getSelectedGroupIds,\n",
" getElementsInGroup,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 32
}
|
import oc from "open-color";
import { AppState, FlooredNumber } from "./types";
import { getDateTime } from "./utils";
import { t } from "./i18n";
import {
DEFAULT_FONT_SIZE,
DEFAULT_FONT_FAMILY,
DEFAULT_TEXT_ALIGN,
} from "./constants";
export const getDefaultAppState = (): AppState => {
return {
isLoading: false,
errorMessage: null,
draggingElement: null,
resizingElement: null,
multiElement: null,
editingElement: null,
editingLinearElement: null,
elementType: "selection",
elementLocked: false,
exportBackground: true,
shouldAddWatermark: false,
currentItemStrokeColor: oc.black,
currentItemBackgroundColor: "transparent",
currentItemFillStyle: "hachure",
currentItemStrokeWidth: 1,
currentItemStrokeStyle: "solid",
currentItemRoughness: 1,
currentItemOpacity: 100,
currentItemFontSize: DEFAULT_FONT_SIZE,
currentItemFontFamily: DEFAULT_FONT_FAMILY,
currentItemTextAlign: DEFAULT_TEXT_ALIGN,
viewBackgroundColor: oc.white,
scrollX: 0 as FlooredNumber,
scrollY: 0 as FlooredNumber,
cursorX: 0,
cursorY: 0,
cursorButton: "up",
scrolledOutside: false,
name: `${t("labels.untitled")}-${getDateTime()}`,
username: "",
isCollaborating: false,
isResizing: false,
isRotating: false,
selectionElement: null,
zoom: 1,
openMenu: null,
lastPointerDownWith: "mouse",
selectedElementIds: {},
previousSelectedElementIds: {},
collaborators: new Map(),
shouldCacheIgnoreZoom: false,
showShortcutsDialog: false,
zenModeEnabled: false,
gridSize: null,
editingGroupId: null,
selectedGroupIds: {},
width: window.innerWidth,
height: window.innerHeight,
isLibraryOpen: false,
};
};
/**
* Config containing all AppState keys. Used to determine whether given state
* prop should be stripped when exporting to given storage type.
*/
const APP_STATE_STORAGE_CONF = (<
Values extends {
/** whether to keep when storing to browser storage (localStorage/IDB) */
browser: boolean;
/** whether to keep when exporting to file/database */
export: boolean;
},
T extends Record<keyof AppState, Values>
>(
config: { [K in keyof T]: K extends keyof AppState ? T[K] : never },
) => config)({
collaborators: { browser: false, export: false },
currentItemBackgroundColor: { browser: true, export: false },
currentItemFillStyle: { browser: true, export: false },
currentItemFontFamily: { browser: true, export: false },
currentItemFontSize: { browser: true, export: false },
currentItemOpacity: { browser: true, export: false },
currentItemRoughness: { browser: true, export: false },
currentItemStrokeColor: { browser: true, export: false },
currentItemStrokeStyle: { browser: true, export: false },
currentItemStrokeWidth: { browser: true, export: false },
currentItemTextAlign: { browser: true, export: false },
cursorButton: { browser: true, export: false },
cursorX: { browser: true, export: false },
cursorY: { browser: true, export: false },
draggingElement: { browser: false, export: false },
editingElement: { browser: false, export: false },
editingGroupId: { browser: true, export: false },
editingLinearElement: { browser: false, export: false },
elementLocked: { browser: true, export: false },
elementType: { browser: true, export: false },
errorMessage: { browser: false, export: false },
exportBackground: { browser: true, export: false },
gridSize: { browser: true, export: true },
height: { browser: false, export: false },
isCollaborating: { browser: false, export: false },
isLibraryOpen: { browser: false, export: false },
isLoading: { browser: false, export: false },
isResizing: { browser: false, export: false },
isRotating: { browser: false, export: false },
lastPointerDownWith: { browser: true, export: false },
multiElement: { browser: false, export: false },
name: { browser: true, export: false },
openMenu: { browser: true, export: false },
previousSelectedElementIds: { browser: true, export: false },
resizingElement: { browser: false, export: false },
scrolledOutside: { browser: true, export: false },
scrollX: { browser: true, export: false },
scrollY: { browser: true, export: false },
selectedElementIds: { browser: true, export: false },
selectedGroupIds: { browser: true, export: false },
selectionElement: { browser: false, export: false },
shouldAddWatermark: { browser: true, export: false },
shouldCacheIgnoreZoom: { browser: true, export: false },
showShortcutsDialog: { browser: false, export: false },
username: { browser: true, export: false },
viewBackgroundColor: { browser: true, export: true },
width: { browser: false, export: false },
zenModeEnabled: { browser: true, export: false },
zoom: { browser: true, export: false },
});
const _clearAppStateForStorage = <ExportType extends "export" | "browser">(
appState: Partial<AppState>,
exportType: ExportType,
) => {
type ExportableKeys = {
[K in keyof typeof APP_STATE_STORAGE_CONF]: typeof APP_STATE_STORAGE_CONF[K][ExportType] extends true
? K
: never;
}[keyof typeof APP_STATE_STORAGE_CONF];
const stateForExport = {} as { [K in ExportableKeys]?: typeof appState[K] };
for (const key of Object.keys(appState) as (keyof typeof appState)[]) {
const propConfig = APP_STATE_STORAGE_CONF[key];
if (!propConfig) {
console.error(
`_clearAppStateForStorage: appState key "${key}" config doesn't exist for "${exportType}" export type`,
);
}
if (propConfig?.[exportType]) {
// @ts-ignore see https://github.com/microsoft/TypeScript/issues/31445
stateForExport[key] = appState[key];
}
}
return stateForExport;
};
export const clearAppStateForLocalStorage = (appState: Partial<AppState>) => {
return _clearAppStateForStorage(appState, "browser");
};
export const cleanAppStateForExport = (appState: Partial<AppState>) => {
return _clearAppStateForStorage(appState, "export");
};
|
src/appState.ts
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.0008031183388084173,
0.00023008562857285142,
0.00016442719788756222,
0.00017681003373581916,
0.00015473370149265975
] |
{
"id": 3,
"code_window": [
"import { getSelectedElements } from \"../scene/selection\";\n",
"\n",
"import { renderElement, renderElementToSvg } from \"./renderElement\";\n",
"import { getClientColors } from \"../clients\";\n",
"import { isLinearElement } from \"../element/typeChecks\";\n",
"import { LinearElementEditor } from \"../element/linearElementEditor\";\n",
"import {\n",
" isSelectedViaGroup,\n",
" getSelectedGroupIds,\n",
" getElementsInGroup,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 32
}
|
#!/usr/bin/env node
// In order to use this, you need to install Cairo on your machine. See
// instructions here: https://github.com/Automattic/node-canvas#compiling
// In order to run:
// npm install canvas # please do not check it in
// npm run build-node
// node build/static/js/build-node.js
// open test.png
var rewire = require("rewire");
var defaults = rewire("react-scripts/scripts/build.js");
var config = defaults.__get__("config");
// Disable multiple chunks
config.optimization.runtimeChunk = false;
config.optimization.splitChunks = {
cacheGroups: {
default: false,
},
};
// Set the filename to be deterministic
config.output.filename = "static/js/build-node.js";
// Don't choke on node-specific requires
config.target = "node";
// Set the node entrypoint
config.entry = "./src/index-node";
// By default, webpack is going to replace the require of the canvas.node file
// to just a string with the path of the canvas.node file. We need to tell
// webpack to avoid rewriting that dependency.
config.externals = function (context, request, callback) {
if (/\.node$/.test(request)) {
return callback(
null,
"commonjs ../../../node_modules/canvas/build/Release/canvas.node",
);
}
callback();
};
|
scripts/build-node.js
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.00017657247371971607,
0.00017489325546193868,
0.00017401788500137627,
0.00017467336147092283,
9.271989256376401e-7
] |
{
"id": 3,
"code_window": [
"import { getSelectedElements } from \"../scene/selection\";\n",
"\n",
"import { renderElement, renderElementToSvg } from \"./renderElement\";\n",
"import { getClientColors } from \"../clients\";\n",
"import { isLinearElement } from \"../element/typeChecks\";\n",
"import { LinearElementEditor } from \"../element/linearElementEditor\";\n",
"import {\n",
" isSelectedViaGroup,\n",
" getSelectedGroupIds,\n",
" getElementsInGroup,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 32
}
|
import React from "react";
import ReactDOM from "react-dom";
import { render, fireEvent } from "./test-utils";
import App from "../components/App";
import * as Renderer from "../renderer/renderScene";
import { reseed } from "../random";
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
const renderScene = jest.spyOn(Renderer, "renderScene");
beforeEach(() => {
localStorage.clear();
renderScene.mockClear();
reseed(7);
});
const { h } = window;
describe("resize element", () => {
it("rectangle", () => {
const { getByToolName, container } = render(<App />);
const canvas = container.querySelector("canvas")!;
{
// create element
const tool = getByToolName("rectangle");
fireEvent.click(tool);
fireEvent.pointerDown(canvas, { clientX: 30, clientY: 20 });
fireEvent.pointerMove(canvas, { clientX: 60, clientY: 70 });
fireEvent.pointerUp(canvas);
expect(renderScene).toHaveBeenCalledTimes(4);
expect(h.state.selectionElement).toBeNull();
expect(h.elements.length).toEqual(1);
expect(h.state.selectedElementIds[h.elements[0].id]).toBeTruthy();
expect([h.elements[0].x, h.elements[0].y]).toEqual([30, 20]);
expect([h.elements[0].width, h.elements[0].height]).toEqual([30, 50]);
renderScene.mockClear();
}
// select the element first
fireEvent.pointerDown(canvas, { clientX: 50, clientY: 20 });
fireEvent.pointerUp(canvas);
// select a handler rectangle (top-left)
fireEvent.pointerDown(canvas, { clientX: 21, clientY: 13 });
fireEvent.pointerMove(canvas, { clientX: 20, clientY: 40 });
fireEvent.pointerUp(canvas);
expect(renderScene).toHaveBeenCalledTimes(5);
expect(h.state.selectionElement).toBeNull();
expect(h.elements.length).toEqual(1);
expect([h.elements[0].x, h.elements[0].y]).toEqual([29, 47]);
expect([h.elements[0].width, h.elements[0].height]).toEqual([30, 50]);
h.elements.forEach((element) => expect(element).toMatchSnapshot());
});
});
describe("resize element with aspect ratio when SHIFT is clicked", () => {
it("rectangle", () => {
const { getByToolName, container } = render(<App />);
const canvas = container.querySelector("canvas")!;
{
// create element
const tool = getByToolName("rectangle");
fireEvent.click(tool);
fireEvent.pointerDown(canvas, { clientX: 30, clientY: 20 });
fireEvent.pointerMove(canvas, { clientX: 60, clientY: 70 });
fireEvent.pointerUp(canvas);
expect(renderScene).toHaveBeenCalledTimes(4);
expect(h.state.selectionElement).toBeNull();
expect(h.elements.length).toEqual(1);
expect(h.state.selectedElementIds[h.elements[0].id]).toBeTruthy();
expect([h.elements[0].x, h.elements[0].y]).toEqual([30, 20]);
expect([h.elements[0].x, h.elements[0].y]).toEqual([30, 20]);
expect([h.elements[0].width, h.elements[0].height]).toEqual([30, 50]);
renderScene.mockClear();
}
// select the element first
fireEvent.pointerDown(canvas, { clientX: 50, clientY: 20 });
fireEvent.pointerUp(canvas);
// select a handler rectangle (top-left)
fireEvent.pointerDown(canvas, { clientX: 21, clientY: 13 });
fireEvent.pointerMove(canvas, { clientX: 20, clientY: 40, shiftKey: true });
fireEvent.pointerUp(canvas);
expect(renderScene).toHaveBeenCalledTimes(5);
expect(h.state.selectionElement).toBeNull();
expect(h.elements.length).toEqual(1);
expect([h.elements[0].x, h.elements[0].y]).toEqual([29, 47]);
expect([h.elements[0].width, h.elements[0].height]).toEqual([30, 50]);
h.elements.forEach((element) => expect(element).toMatchSnapshot());
});
});
|
src/tests/resize.test.tsx
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.00022793764946982265,
0.00019466756202746183,
0.00016577981295995414,
0.00019828457152470946,
0.000024411679987679236
] |
{
"id": 4,
"code_window": [
" ),\n",
" );\n",
"\n",
" visibleElements.forEach((element) => {\n",
" renderElement(element, rc, context, renderOptimizations, sceneState);\n",
" if (\n",
" isLinearElement(element) &&\n",
" appState.editingLinearElement &&\n",
" appState.editingLinearElement.elementId === element.id\n",
" ) {\n",
" renderLinearPointHandles(context, appState, sceneState, element);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" });\n",
"\n",
" if (appState.editingLinearElement) {\n",
" const element = LinearElementEditor.getElement(\n",
" appState.editingLinearElement.elementId,\n",
" );\n",
" if (element) {\n"
],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 222
}
|
import { RoughCanvas } from "roughjs/bin/canvas";
import { RoughSVG } from "roughjs/bin/svg";
import oc from "open-color";
import { FlooredNumber, AppState } from "../types";
import {
ExcalidrawElement,
NonDeletedExcalidrawElement,
ExcalidrawLinearElement,
NonDeleted,
GroupId,
} from "../element/types";
import {
getElementAbsoluteCoords,
OMIT_SIDES_FOR_MULTIPLE_ELEMENTS,
handlerRectanglesFromCoords,
handlerRectangles,
getElementBounds,
getCommonBounds,
} from "../element";
import { roundRect } from "./roundRect";
import { SceneState } from "../scene/types";
import {
getScrollBars,
SCROLLBAR_COLOR,
SCROLLBAR_WIDTH,
} from "../scene/scrollbars";
import { getSelectedElements } from "../scene/selection";
import { renderElement, renderElementToSvg } from "./renderElement";
import { getClientColors } from "../clients";
import { isLinearElement } from "../element/typeChecks";
import { LinearElementEditor } from "../element/linearElementEditor";
import {
isSelectedViaGroup,
getSelectedGroupIds,
getElementsInGroup,
} from "../groups";
type HandlerRectanglesRet = keyof ReturnType<typeof handlerRectangles>;
const strokeRectWithRotation = (
context: CanvasRenderingContext2D,
x: number,
y: number,
width: number,
height: number,
cx: number,
cy: number,
angle: number,
fill?: boolean,
) => {
context.translate(cx, cy);
context.rotate(angle);
if (fill) {
context.fillRect(x - cx, y - cy, width, height);
}
context.strokeRect(x - cx, y - cy, width, height);
context.rotate(-angle);
context.translate(-cx, -cy);
};
const strokeCircle = (
context: CanvasRenderingContext2D,
x: number,
y: number,
width: number,
height: number,
) => {
context.beginPath();
context.arc(x + width / 2, y + height / 2, width / 2, 0, Math.PI * 2);
context.fill();
context.stroke();
};
const strokeGrid = (
context: CanvasRenderingContext2D,
gridSize: number,
offsetX: number,
offsetY: number,
width: number,
height: number,
) => {
const origStrokeStyle = context.strokeStyle;
context.strokeStyle = "rgba(0,0,0,0.1)";
context.beginPath();
for (let x = offsetX; x < offsetX + width + gridSize * 2; x += gridSize) {
context.moveTo(x, offsetY - gridSize);
context.lineTo(x, offsetY + height + gridSize * 2);
}
for (let y = offsetY; y < offsetY + height + gridSize * 2; y += gridSize) {
context.moveTo(offsetX - gridSize, y);
context.lineTo(offsetX + width + gridSize * 2, y);
}
context.stroke();
context.strokeStyle = origStrokeStyle;
};
const renderLinearPointHandles = (
context: CanvasRenderingContext2D,
appState: AppState,
sceneState: SceneState,
element: NonDeleted<ExcalidrawLinearElement>,
) => {
context.translate(sceneState.scrollX, sceneState.scrollY);
const origStrokeStyle = context.strokeStyle;
const lineWidth = context.lineWidth;
context.lineWidth = 1 / sceneState.zoom;
LinearElementEditor.getPointsGlobalCoordinates(element).forEach(
(point, idx) => {
context.strokeStyle = "red";
context.setLineDash([]);
context.fillStyle =
appState.editingLinearElement?.activePointIndex === idx
? "rgba(255, 127, 127, 0.9)"
: "rgba(255, 255, 255, 0.9)";
const { POINT_HANDLE_SIZE } = LinearElementEditor;
strokeCircle(
context,
point[0] - POINT_HANDLE_SIZE / 2 / sceneState.zoom,
point[1] - POINT_HANDLE_SIZE / 2 / sceneState.zoom,
POINT_HANDLE_SIZE / sceneState.zoom,
POINT_HANDLE_SIZE / sceneState.zoom,
);
},
);
context.setLineDash([]);
context.lineWidth = lineWidth;
context.translate(-sceneState.scrollX, -sceneState.scrollY);
context.strokeStyle = origStrokeStyle;
};
export const renderScene = (
elements: readonly NonDeletedExcalidrawElement[],
appState: AppState,
selectionElement: NonDeletedExcalidrawElement | null,
scale: number,
rc: RoughCanvas,
canvas: HTMLCanvasElement,
sceneState: SceneState,
// extra options, currently passed by export helper
{
renderScrollbars = true,
renderSelection = true,
// Whether to employ render optimizations to improve performance.
// Should not be turned on for export operations and similar, because it
// doesn't guarantee pixel-perfect output.
renderOptimizations = false,
renderGrid = true,
}: {
renderScrollbars?: boolean;
renderSelection?: boolean;
renderOptimizations?: boolean;
renderGrid?: boolean;
} = {},
) => {
if (!canvas) {
return { atLeastOneVisibleElement: false };
}
const context = canvas.getContext("2d")!;
context.scale(scale, scale);
// When doing calculations based on canvas width we should used normalized one
const normalizedCanvasWidth = canvas.width / scale;
const normalizedCanvasHeight = canvas.height / scale;
// Paint background
if (typeof sceneState.viewBackgroundColor === "string") {
const hasTransparence =
sceneState.viewBackgroundColor === "transparent" ||
sceneState.viewBackgroundColor.length === 5 || // #RGBA
sceneState.viewBackgroundColor.length === 9 || // #RRGGBBA
/(hsla|rgba)\(/.test(sceneState.viewBackgroundColor);
if (hasTransparence) {
context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
}
const fillStyle = context.fillStyle;
context.fillStyle = sceneState.viewBackgroundColor;
context.fillRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
context.fillStyle = fillStyle;
} else {
context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
}
// Apply zoom
const zoomTranslationX = (-normalizedCanvasWidth * (sceneState.zoom - 1)) / 2;
const zoomTranslationY =
(-normalizedCanvasHeight * (sceneState.zoom - 1)) / 2;
context.translate(zoomTranslationX, zoomTranslationY);
context.scale(sceneState.zoom, sceneState.zoom);
// Grid
if (renderGrid && appState.gridSize) {
strokeGrid(
context,
appState.gridSize,
-Math.ceil(zoomTranslationX / sceneState.zoom / appState.gridSize) *
appState.gridSize +
(sceneState.scrollX % appState.gridSize),
-Math.ceil(zoomTranslationY / sceneState.zoom / appState.gridSize) *
appState.gridSize +
(sceneState.scrollY % appState.gridSize),
normalizedCanvasWidth / sceneState.zoom,
normalizedCanvasHeight / sceneState.zoom,
);
}
// Paint visible elements
const visibleElements = elements.filter((element) =>
isVisibleElement(
element,
normalizedCanvasWidth,
normalizedCanvasHeight,
sceneState,
),
);
visibleElements.forEach((element) => {
renderElement(element, rc, context, renderOptimizations, sceneState);
if (
isLinearElement(element) &&
appState.editingLinearElement &&
appState.editingLinearElement.elementId === element.id
) {
renderLinearPointHandles(context, appState, sceneState, element);
}
});
// Paint selection element
if (selectionElement) {
renderElement(
selectionElement,
rc,
context,
renderOptimizations,
sceneState,
);
}
// Paint selected elements
if (
renderSelection &&
!appState.multiElement &&
!appState.editingLinearElement
) {
context.translate(sceneState.scrollX, sceneState.scrollY);
const selections = elements.reduce((acc, element) => {
const selectionColors = [];
// local user
if (
appState.selectedElementIds[element.id] &&
!isSelectedViaGroup(appState, element)
) {
selectionColors.push(oc.black);
}
// remote users
if (sceneState.remoteSelectedElementIds[element.id]) {
selectionColors.push(
...sceneState.remoteSelectedElementIds[element.id].map((socketId) => {
const { background } = getClientColors(socketId);
return background;
}),
);
}
if (selectionColors.length) {
const [
elementX1,
elementY1,
elementX2,
elementY2,
] = getElementAbsoluteCoords(element);
acc.push({
angle: element.angle,
elementX1,
elementY1,
elementX2,
elementY2,
selectionColors,
});
}
return acc;
}, [] as { angle: number; elementX1: number; elementY1: number; elementX2: number; elementY2: number; selectionColors: string[] }[]);
function addSelectionForGroupId(groupId: GroupId) {
const groupElements = getElementsInGroup(elements, groupId);
const [elementX1, elementY1, elementX2, elementY2] = getCommonBounds(
groupElements,
);
selections.push({
angle: 0,
elementX1,
elementX2,
elementY1,
elementY2,
selectionColors: [oc.black],
});
}
for (const groupId of getSelectedGroupIds(appState)) {
// TODO: support multiplayer selected group IDs
addSelectionForGroupId(groupId);
}
if (appState.editingGroupId) {
addSelectionForGroupId(appState.editingGroupId);
}
selections.forEach(
({
angle,
elementX1,
elementY1,
elementX2,
elementY2,
selectionColors,
}) => {
const elementWidth = elementX2 - elementX1;
const elementHeight = elementY2 - elementY1;
const initialLineDash = context.getLineDash();
const lineWidth = context.lineWidth;
const lineDashOffset = context.lineDashOffset;
const strokeStyle = context.strokeStyle;
const dashedLinePadding = 4 / sceneState.zoom;
const dashWidth = 8 / sceneState.zoom;
const spaceWidth = 4 / sceneState.zoom;
context.lineWidth = 1 / sceneState.zoom;
const count = selectionColors.length;
for (var i = 0; i < count; ++i) {
context.strokeStyle = selectionColors[i];
context.setLineDash([
dashWidth,
spaceWidth + (dashWidth + spaceWidth) * (count - 1),
]);
context.lineDashOffset = (dashWidth + spaceWidth) * i;
strokeRectWithRotation(
context,
elementX1 - dashedLinePadding,
elementY1 - dashedLinePadding,
elementWidth + dashedLinePadding * 2,
elementHeight + dashedLinePadding * 2,
elementX1 + elementWidth / 2,
elementY1 + elementHeight / 2,
angle,
);
}
context.lineDashOffset = lineDashOffset;
context.strokeStyle = strokeStyle;
context.lineWidth = lineWidth;
context.setLineDash(initialLineDash);
},
);
context.translate(-sceneState.scrollX, -sceneState.scrollY);
const locallySelectedElements = getSelectedElements(elements, appState);
// Paint resize handlers
if (locallySelectedElements.length === 1) {
context.translate(sceneState.scrollX, sceneState.scrollY);
context.fillStyle = oc.white;
const handlers = handlerRectangles(
locallySelectedElements[0],
sceneState.zoom,
);
Object.keys(handlers).forEach((key) => {
const handler = handlers[key as HandlerRectanglesRet];
if (handler !== undefined) {
const lineWidth = context.lineWidth;
context.lineWidth = 1 / sceneState.zoom;
if (key === "rotation") {
strokeCircle(
context,
handler[0],
handler[1],
handler[2],
handler[3],
);
} else {
strokeRectWithRotation(
context,
handler[0],
handler[1],
handler[2],
handler[3],
handler[0] + handler[2] / 2,
handler[1] + handler[3] / 2,
locallySelectedElements[0].angle,
true, // fill before stroke
);
}
context.lineWidth = lineWidth;
}
});
context.translate(-sceneState.scrollX, -sceneState.scrollY);
} else if (locallySelectedElements.length > 1 && !appState.isRotating) {
const dashedLinePadding = 4 / sceneState.zoom;
context.translate(sceneState.scrollX, sceneState.scrollY);
context.fillStyle = oc.white;
const [x1, y1, x2, y2] = getCommonBounds(locallySelectedElements);
const initialLineDash = context.getLineDash();
context.setLineDash([2 / sceneState.zoom]);
const lineWidth = context.lineWidth;
context.lineWidth = 1 / sceneState.zoom;
strokeRectWithRotation(
context,
x1 - dashedLinePadding,
y1 - dashedLinePadding,
x2 - x1 + dashedLinePadding * 2,
y2 - y1 + dashedLinePadding * 2,
(x1 + x2) / 2,
(y1 + y2) / 2,
0,
);
context.lineWidth = lineWidth;
context.setLineDash(initialLineDash);
const handlers = handlerRectanglesFromCoords(
[x1, y1, x2, y2],
0,
sceneState.zoom,
undefined,
OMIT_SIDES_FOR_MULTIPLE_ELEMENTS,
);
Object.keys(handlers).forEach((key) => {
const handler = handlers[key as HandlerRectanglesRet];
if (handler !== undefined) {
const lineWidth = context.lineWidth;
context.lineWidth = 1 / sceneState.zoom;
if (key === "rotation") {
strokeCircle(
context,
handler[0],
handler[1],
handler[2],
handler[3],
);
} else {
strokeRectWithRotation(
context,
handler[0],
handler[1],
handler[2],
handler[3],
handler[0] + handler[2] / 2,
handler[1] + handler[3] / 2,
0,
true, // fill before stroke
);
}
context.lineWidth = lineWidth;
}
});
context.translate(-sceneState.scrollX, -sceneState.scrollY);
}
}
// Reset zoom
context.scale(1 / sceneState.zoom, 1 / sceneState.zoom);
context.translate(-zoomTranslationX, -zoomTranslationY);
// Paint remote pointers
for (const clientId in sceneState.remotePointerViewportCoords) {
let { x, y } = sceneState.remotePointerViewportCoords[clientId];
const username = sceneState.remotePointerUsernames[clientId];
const width = 9;
const height = 14;
const isOutOfBounds =
x < 0 ||
x > normalizedCanvasWidth - width ||
y < 0 ||
y > normalizedCanvasHeight - height;
x = Math.max(x, 0);
x = Math.min(x, normalizedCanvasWidth - width);
y = Math.max(y, 0);
y = Math.min(y, normalizedCanvasHeight - height);
const { background, stroke } = getClientColors(clientId);
const strokeStyle = context.strokeStyle;
const fillStyle = context.fillStyle;
const globalAlpha = context.globalAlpha;
context.strokeStyle = stroke;
context.fillStyle = background;
if (isOutOfBounds) {
context.globalAlpha = 0.2;
}
if (
sceneState.remotePointerButton &&
sceneState.remotePointerButton[clientId] === "down"
) {
context.beginPath();
context.arc(x, y, 15, 0, 2 * Math.PI, false);
context.lineWidth = 3;
context.strokeStyle = "#ffffff88";
context.stroke();
context.closePath();
context.beginPath();
context.arc(x, y, 15, 0, 2 * Math.PI, false);
context.lineWidth = 1;
context.strokeStyle = stroke;
context.stroke();
context.closePath();
}
context.beginPath();
context.moveTo(x, y);
context.lineTo(x + 1, y + 14);
context.lineTo(x + 4, y + 9);
context.lineTo(x + 9, y + 10);
context.lineTo(x, y);
context.fill();
context.stroke();
if (!isOutOfBounds && username) {
const offsetX = x + width;
const offsetY = y + height;
const paddingHorizontal = 4;
const paddingVertical = 4;
const measure = context.measureText(username);
const measureHeight =
measure.actualBoundingBoxDescent + measure.actualBoundingBoxAscent;
// Border
context.fillStyle = stroke;
context.globalAlpha = globalAlpha;
context.fillRect(
offsetX - 1,
offsetY - 1,
measure.width + 2 * paddingHorizontal + 2,
measureHeight + 2 * paddingVertical + 2,
);
// Background
context.fillStyle = background;
context.fillRect(
offsetX,
offsetY,
measure.width + 2 * paddingHorizontal,
measureHeight + 2 * paddingVertical,
);
context.fillStyle = oc.white;
context.fillText(
username,
offsetX + paddingHorizontal,
offsetY + paddingVertical + measure.actualBoundingBoxAscent,
);
}
context.strokeStyle = strokeStyle;
context.fillStyle = fillStyle;
context.globalAlpha = globalAlpha;
context.closePath();
}
// Paint scrollbars
let scrollBars;
if (renderScrollbars) {
scrollBars = getScrollBars(
elements,
normalizedCanvasWidth,
normalizedCanvasHeight,
sceneState,
);
const fillStyle = context.fillStyle;
const strokeStyle = context.strokeStyle;
context.fillStyle = SCROLLBAR_COLOR;
context.strokeStyle = "rgba(255,255,255,0.8)";
[scrollBars.horizontal, scrollBars.vertical].forEach((scrollBar) => {
if (scrollBar) {
roundRect(
context,
scrollBar.x,
scrollBar.y,
scrollBar.width,
scrollBar.height,
SCROLLBAR_WIDTH / 2,
);
}
});
context.fillStyle = fillStyle;
context.strokeStyle = strokeStyle;
}
context.scale(1 / scale, 1 / scale);
return { atLeastOneVisibleElement: visibleElements.length > 0, scrollBars };
};
const isVisibleElement = (
element: ExcalidrawElement,
viewportWidth: number,
viewportHeight: number,
{
scrollX,
scrollY,
zoom,
}: {
scrollX: FlooredNumber;
scrollY: FlooredNumber;
zoom: number;
},
) => {
const [x1, y1, x2, y2] = getElementBounds(element);
// Apply zoom
const viewportWidthWithZoom = viewportWidth / zoom;
const viewportHeightWithZoom = viewportHeight / zoom;
const viewportWidthDiff = viewportWidth - viewportWidthWithZoom;
const viewportHeightDiff = viewportHeight - viewportHeightWithZoom;
return (
x2 + scrollX - viewportWidthDiff / 2 >= 0 &&
x1 + scrollX - viewportWidthDiff / 2 <= viewportWidthWithZoom &&
y2 + scrollY - viewportHeightDiff / 2 >= 0 &&
y1 + scrollY - viewportHeightDiff / 2 <= viewportHeightWithZoom
);
};
// This should be only called for exporting purposes
export const renderSceneToSvg = (
elements: readonly NonDeletedExcalidrawElement[],
rsvg: RoughSVG,
svgRoot: SVGElement,
{
offsetX = 0,
offsetY = 0,
}: {
offsetX?: number;
offsetY?: number;
} = {},
) => {
if (!svgRoot) {
return;
}
// render elements
elements.forEach((element) => {
if (!element.isDeleted) {
renderElementToSvg(
element,
rsvg,
svgRoot,
element.x + offsetX,
element.y + offsetY,
);
}
});
};
|
src/renderer/renderScene.ts
| 1 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.9974355101585388,
0.016005998477339745,
0.00016478914767503738,
0.0001734239631332457,
0.1217634454369545
] |
{
"id": 4,
"code_window": [
" ),\n",
" );\n",
"\n",
" visibleElements.forEach((element) => {\n",
" renderElement(element, rc, context, renderOptimizations, sceneState);\n",
" if (\n",
" isLinearElement(element) &&\n",
" appState.editingLinearElement &&\n",
" appState.editingLinearElement.elementId === element.id\n",
" ) {\n",
" renderLinearPointHandles(context, appState, sceneState, element);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" });\n",
"\n",
" if (appState.editingLinearElement) {\n",
" const element = LinearElementEditor.getElement(\n",
" appState.editingLinearElement.elementId,\n",
" );\n",
" if (element) {\n"
],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 222
}
|
import { ExcalidrawTextElement } from "../element/types";
import { FlooredNumber } from "../types";
export type SceneState = {
scrollX: FlooredNumber;
scrollY: FlooredNumber;
// null indicates transparent bg
viewBackgroundColor: string | null;
zoom: number;
shouldCacheIgnoreZoom: boolean;
remotePointerViewportCoords: { [id: string]: { x: number; y: number } };
remotePointerButton?: { [id: string]: string | undefined };
remoteSelectedElementIds: { [elementId: string]: string[] };
remotePointerUsernames: { [id: string]: string };
};
export type SceneScroll = {
scrollX: FlooredNumber;
scrollY: FlooredNumber;
};
export interface Scene {
elements: ExcalidrawTextElement[];
}
export type ExportType =
| "png"
| "clipboard"
| "clipboard-svg"
| "backend"
| "svg";
export type ScrollBars = {
horizontal: {
x: number;
y: number;
width: number;
height: number;
} | null;
vertical: {
x: number;
y: number;
width: number;
height: number;
} | null;
};
|
src/scene/types.ts
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.0012454492971301079,
0.00044902676017954946,
0.00016489053086843342,
0.00017767328245099634,
0.0004155425413046032
] |
{
"id": 4,
"code_window": [
" ),\n",
" );\n",
"\n",
" visibleElements.forEach((element) => {\n",
" renderElement(element, rc, context, renderOptimizations, sceneState);\n",
" if (\n",
" isLinearElement(element) &&\n",
" appState.editingLinearElement &&\n",
" appState.editingLinearElement.elementId === element.id\n",
" ) {\n",
" renderLinearPointHandles(context, appState, sceneState, element);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" });\n",
"\n",
" if (appState.editingLinearElement) {\n",
" const element = LinearElementEditor.getElement(\n",
" appState.editingLinearElement.elementId,\n",
" );\n",
" if (element) {\n"
],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 222
}
|
.FixedSideContainer {
--margin: 0.25rem;
position: absolute;
pointer-events: none;
}
.FixedSideContainer > * {
pointer-events: all;
}
.FixedSideContainer_side_top {
left: var(--margin);
top: var(--margin);
right: var(--margin);
z-index: 2;
}
.FixedSideContainer_side_top.zen-mode {
right: 42px;
}
/* TODO: if these are used, make sure to implement RTL support
.FixedSideContainer_side_left {
left: var(--margin);
top: var(--margin);
bottom: var(--margin);
z-index: 1;
}
.FixedSideContainer_side_right {
right: var(--margin);
top: var(--margin);
bottom: var(--margin);
z-index: 3;
}
*/
|
src/components/FixedSideContainer.css
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.0002042455889750272,
0.0001769304508343339,
0.00016366557974833995,
0.00016990532458294183,
0.000016505317034898326
] |
{
"id": 4,
"code_window": [
" ),\n",
" );\n",
"\n",
" visibleElements.forEach((element) => {\n",
" renderElement(element, rc, context, renderOptimizations, sceneState);\n",
" if (\n",
" isLinearElement(element) &&\n",
" appState.editingLinearElement &&\n",
" appState.editingLinearElement.elementId === element.id\n",
" ) {\n",
" renderLinearPointHandles(context, appState, sceneState, element);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" });\n",
"\n",
" if (appState.editingLinearElement) {\n",
" const element = LinearElementEditor.getElement(\n",
" appState.editingLinearElement.elementId,\n",
" );\n",
" if (element) {\n"
],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 222
}
|
import {
ExcalidrawElement,
NonDeletedExcalidrawElement,
} from "../element/types";
import { getElementAbsoluteCoords, hitTest } from "../element";
import { AppState } from "../types";
export const hasBackground = (type: string) =>
type === "rectangle" ||
type === "ellipse" ||
type === "diamond" ||
type === "draw" ||
type === "line";
export const hasStroke = (type: string) =>
type === "rectangle" ||
type === "ellipse" ||
type === "diamond" ||
type === "arrow" ||
type === "draw" ||
type === "line";
export const hasText = (type: string) => type === "text";
export const getElementAtPosition = (
elements: readonly NonDeletedExcalidrawElement[],
appState: AppState,
x: number,
y: number,
zoom: number,
) => {
let hitElement = null;
// We need to to hit testing from front (end of the array) to back (beginning of the array)
for (let i = elements.length - 1; i >= 0; --i) {
if (elements[i].isDeleted) {
continue;
}
if (hitTest(elements[i], appState, x, y, zoom)) {
hitElement = elements[i];
break;
}
}
return hitElement;
};
export const getElementContainingPosition = (
elements: readonly ExcalidrawElement[],
x: number,
y: number,
) => {
let hitElement = null;
// We need to to hit testing from front (end of the array) to back (beginning of the array)
for (let i = elements.length - 1; i >= 0; --i) {
if (elements[i].isDeleted) {
continue;
}
const [x1, y1, x2, y2] = getElementAbsoluteCoords(elements[i]);
if (x1 < x && x < x2 && y1 < y && y < y2) {
hitElement = elements[i];
break;
}
}
return hitElement;
};
|
src/scene/comparisons.ts
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.00017790860147215426,
0.00016958195192273706,
0.00016474058793392032,
0.00016903576033655554,
0.0000040231843740912154
] |
{
"id": 5,
"code_window": [
" renderLinearPointHandles(context, appState, sceneState, element);\n",
" }\n",
" });\n",
"\n",
" // Paint selection element\n",
" if (selectionElement) {\n",
" renderElement(\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" }\n"
],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 229
}
|
import {
NonDeleted,
ExcalidrawLinearElement,
ExcalidrawElement,
} from "./types";
import { distance2d, rotate, isPathALoop } from "../math";
import { getElementAbsoluteCoords } from ".";
import { getElementPointsCoords } from "./bounds";
import { Point, AppState } from "../types";
import { mutateElement } from "./mutateElement";
import { SceneHistory } from "../history";
import { globalSceneState } from "../scene";
export class LinearElementEditor {
public elementId: ExcalidrawElement["id"];
public activePointIndex: number | null;
public draggingElementPointIndex: number | null;
public lastUncommittedPoint: Point | null;
constructor(element: NonDeleted<ExcalidrawLinearElement>) {
LinearElementEditor.normalizePoints(element);
this.elementId = element.id;
this.activePointIndex = null;
this.lastUncommittedPoint = null;
this.draggingElementPointIndex = null;
}
// ---------------------------------------------------------------------------
// static methods
// ---------------------------------------------------------------------------
static POINT_HANDLE_SIZE = 20;
static getElement(id: ExcalidrawElement["id"]) {
const element = globalSceneState.getNonDeletedElement(id);
if (element) {
return element as NonDeleted<ExcalidrawLinearElement>;
}
return null;
}
/** @returns whether point was dragged */
static handlePointDragging(
appState: AppState,
setState: React.Component<any, AppState>["setState"],
scenePointerX: number,
scenePointerY: number,
lastX: number,
lastY: number,
): boolean {
if (!appState.editingLinearElement) {
return false;
}
const { editingLinearElement } = appState;
let { draggingElementPointIndex, elementId } = editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return false;
}
const clickedPointIndex =
draggingElementPointIndex ??
LinearElementEditor.getPointIndexUnderCursor(
element,
appState.zoom,
scenePointerX,
scenePointerY,
);
draggingElementPointIndex = draggingElementPointIndex ?? clickedPointIndex;
if (draggingElementPointIndex > -1) {
if (
editingLinearElement.draggingElementPointIndex !==
draggingElementPointIndex ||
editingLinearElement.activePointIndex !== clickedPointIndex
) {
setState({
editingLinearElement: {
...editingLinearElement,
draggingElementPointIndex,
activePointIndex: clickedPointIndex,
},
});
}
const [deltaX, deltaY] = rotate(
scenePointerX - lastX,
scenePointerY - lastY,
0,
0,
-element.angle,
);
const targetPoint = element.points[clickedPointIndex];
LinearElementEditor.movePoint(element, clickedPointIndex, [
targetPoint[0] + deltaX,
targetPoint[1] + deltaY,
]);
return true;
}
return false;
}
static handlePointerUp(
editingLinearElement: LinearElementEditor,
): LinearElementEditor {
const { elementId, draggingElementPointIndex } = editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return editingLinearElement;
}
if (
draggingElementPointIndex !== null &&
(draggingElementPointIndex === 0 ||
draggingElementPointIndex === element.points.length - 1) &&
isPathALoop(element.points)
) {
LinearElementEditor.movePoint(
element,
draggingElementPointIndex,
draggingElementPointIndex === 0
? element.points[element.points.length - 1]
: element.points[0],
);
}
if (draggingElementPointIndex !== null) {
return {
...editingLinearElement,
draggingElementPointIndex: null,
};
}
return editingLinearElement;
}
static handlePointerDown(
event: React.PointerEvent<HTMLCanvasElement>,
appState: AppState,
setState: React.Component<any, AppState>["setState"],
history: SceneHistory,
scenePointerX: number,
scenePointerY: number,
): {
didAddPoint: boolean;
hitElement: ExcalidrawElement | null;
} {
const ret: ReturnType<typeof LinearElementEditor["handlePointerDown"]> = {
didAddPoint: false,
hitElement: null,
};
if (!appState.editingLinearElement) {
return ret;
}
const { elementId } = appState.editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return ret;
}
if (event.altKey) {
if (!appState.editingLinearElement.lastUncommittedPoint) {
mutateElement(element, {
points: [
...element.points,
LinearElementEditor.createPointAt(
element,
scenePointerX,
scenePointerY,
),
],
});
}
history.resumeRecording();
setState({
editingLinearElement: {
...appState.editingLinearElement,
activePointIndex: element.points.length - 1,
lastUncommittedPoint: null,
},
});
ret.didAddPoint = true;
return ret;
}
const clickedPointIndex = LinearElementEditor.getPointIndexUnderCursor(
element,
appState.zoom,
scenePointerX,
scenePointerY,
);
// if we clicked on a point, set the element as hitElement otherwise
// it would get deselected if the point is outside the hitbox area
if (clickedPointIndex > -1) {
ret.hitElement = element;
}
setState({
editingLinearElement: {
...appState.editingLinearElement,
activePointIndex: clickedPointIndex > -1 ? clickedPointIndex : null,
},
});
return ret;
}
static handlePointerMove(
event: React.PointerEvent<HTMLCanvasElement>,
scenePointerX: number,
scenePointerY: number,
editingLinearElement: LinearElementEditor,
): LinearElementEditor {
const { elementId, lastUncommittedPoint } = editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return editingLinearElement;
}
const { points } = element;
const lastPoint = points[points.length - 1];
if (!event.altKey) {
if (lastPoint === lastUncommittedPoint) {
LinearElementEditor.movePoint(element, points.length - 1, "delete");
}
return editingLinearElement;
}
const newPoint = LinearElementEditor.createPointAt(
element,
scenePointerX,
scenePointerY,
);
if (lastPoint === lastUncommittedPoint) {
LinearElementEditor.movePoint(
element,
element.points.length - 1,
newPoint,
);
} else {
LinearElementEditor.movePoint(element, "new", newPoint);
}
return {
...editingLinearElement,
lastUncommittedPoint: element.points[element.points.length - 1],
};
}
static getPointsGlobalCoordinates(
element: NonDeleted<ExcalidrawLinearElement>,
) {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
const cx = (x1 + x2) / 2;
const cy = (y1 + y2) / 2;
return element.points.map((point) => {
let { x, y } = element;
[x, y] = rotate(x + point[0], y + point[1], cx, cy, element.angle);
return [x, y];
});
}
static getPointIndexUnderCursor(
element: NonDeleted<ExcalidrawLinearElement>,
zoom: AppState["zoom"],
x: number,
y: number,
) {
const pointHandles = this.getPointsGlobalCoordinates(element);
let idx = pointHandles.length;
// loop from right to left because points on the right are rendered over
// points on the left, thus should take precedence when clicking, if they
// overlap
while (--idx > -1) {
const point = pointHandles[idx];
if (
distance2d(x, y, point[0], point[1]) * zoom <
// +1px to account for outline stroke
this.POINT_HANDLE_SIZE / 2 + 1
) {
return idx;
}
}
return -1;
}
static createPointAt(
element: NonDeleted<ExcalidrawLinearElement>,
scenePointerX: number,
scenePointerY: number,
): Point {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
const cx = (x1 + x2) / 2;
const cy = (y1 + y2) / 2;
const [rotatedX, rotatedY] = rotate(
scenePointerX,
scenePointerY,
cx,
cy,
-element.angle,
);
return [rotatedX - element.x, rotatedY - element.y];
}
// element-mutating methods
// ---------------------------------------------------------------------------
/**
* Normalizes line points so that the start point is at [0,0]. This is
* expected in various parts of the codebase.
*/
static normalizePoints(element: NonDeleted<ExcalidrawLinearElement>) {
const { points } = element;
const offsetX = points[0][0];
const offsetY = points[0][1];
mutateElement(element, {
points: points.map((point, _idx) => {
return [point[0] - offsetX, point[1] - offsetY] as const;
}),
x: element.x + offsetX,
y: element.y + offsetY,
});
}
static movePoint(
element: NonDeleted<ExcalidrawLinearElement>,
pointIndex: number | "new",
targetPosition: Point | "delete",
) {
const { points } = element;
// in case we're moving start point, instead of modifying its position
// which would break the invariant of it being at [0,0], we move
// all the other points in the opposite direction by delta to
// offset it. We do the same with actual element.x/y position, so
// this hacks are completely transparent to the user.
let offsetX = 0;
let offsetY = 0;
let nextPoints: (readonly [number, number])[];
if (targetPosition === "delete") {
// remove point
if (pointIndex === "new") {
throw new Error("invalid args in movePoint");
}
nextPoints = points.slice();
nextPoints.splice(pointIndex, 1);
if (pointIndex === 0) {
// if deleting first point, make the next to be [0,0] and recalculate
// positions of the rest with respect to it
offsetX = nextPoints[0][0];
offsetY = nextPoints[0][1];
nextPoints = nextPoints.map((point, idx) => {
if (idx === 0) {
return [0, 0];
}
return [point[0] - offsetX, point[1] - offsetY];
});
}
} else if (pointIndex === "new") {
nextPoints = [...points, targetPosition];
} else {
const deltaX = targetPosition[0] - points[pointIndex][0];
const deltaY = targetPosition[1] - points[pointIndex][1];
nextPoints = points.map((point, idx) => {
if (idx === pointIndex) {
if (idx === 0) {
offsetX = deltaX;
offsetY = deltaY;
return point;
}
offsetX = 0;
offsetY = 0;
return [point[0] + deltaX, point[1] + deltaY] as const;
}
return offsetX || offsetY
? ([point[0] - offsetX, point[1] - offsetY] as const)
: point;
});
}
const nextCoords = getElementPointsCoords(element, nextPoints);
const prevCoords = getElementPointsCoords(element, points);
const nextCenterX = (nextCoords[0] + nextCoords[2]) / 2;
const nextCenterY = (nextCoords[1] + nextCoords[3]) / 2;
const prevCenterX = (prevCoords[0] + prevCoords[2]) / 2;
const prevCenterY = (prevCoords[1] + prevCoords[3]) / 2;
const dX = prevCenterX - nextCenterX;
const dY = prevCenterY - nextCenterY;
const rotated = rotate(offsetX, offsetY, dX, dY, element.angle);
mutateElement(element, {
points: nextPoints,
x: element.x + rotated[0],
y: element.y + rotated[1],
});
}
}
|
src/element/linearElementEditor.ts
| 1 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.0034409137442708015,
0.0004564061528071761,
0.00016501113714184612,
0.000185104800038971,
0.0006445722538046539
] |
{
"id": 5,
"code_window": [
" renderLinearPointHandles(context, appState, sceneState, element);\n",
" }\n",
" });\n",
"\n",
" // Paint selection element\n",
" if (selectionElement) {\n",
" renderElement(\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" }\n"
],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 229
}
|
import { encryptAESGEM } from "../data";
import { SocketUpdateData } from "../types";
import { BROADCAST, SCENE } from "../constants";
import App from "./App";
class Portal {
app: App;
socket: SocketIOClient.Socket | null = null;
socketInitialized: boolean = false; // we don't want the socket to emit any updates until it is fully initialized
roomID: string | null = null;
roomKey: string | null = null;
constructor(app: App) {
this.app = app;
}
open(socket: SocketIOClient.Socket, id: string, key: string) {
this.socket = socket;
this.roomID = id;
this.roomKey = key;
// Initialize socket listeners (moving from App)
this.socket.on("init-room", () => {
if (this.socket) {
this.socket.emit("join-room", this.roomID);
this.app.restoreUserName();
}
});
this.socket.on("new-user", async (_socketID: string) => {
this.app.broadcastScene(SCENE.INIT, /* syncAll */ true);
});
this.socket.on("room-user-change", (clients: string[]) => {
this.app.setCollaborators(clients);
});
}
close() {
if (!this.socket) {
return;
}
this.socket.close();
this.socket = null;
this.roomID = null;
this.roomKey = null;
}
isOpen() {
return !!(
this.socketInitialized &&
this.socket &&
this.roomID &&
this.roomKey
);
}
async _broadcastSocketData(
data: SocketUpdateData,
volatile: boolean = false,
) {
if (this.isOpen()) {
const json = JSON.stringify(data);
const encoded = new TextEncoder().encode(json);
const encrypted = await encryptAESGEM(encoded, this.roomKey!);
this.socket!.emit(
volatile ? BROADCAST.SERVER_VOLATILE : BROADCAST.SERVER,
this.roomID,
encrypted.data,
encrypted.iv,
);
}
}
}
export default Portal;
|
src/components/Portal.tsx
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.00017406234110239893,
0.00017122318968176842,
0.00016826018691062927,
0.00017107721942011267,
0.0000016376491203118348
] |
{
"id": 5,
"code_window": [
" renderLinearPointHandles(context, appState, sceneState, element);\n",
" }\n",
" });\n",
"\n",
" // Paint selection element\n",
" if (selectionElement) {\n",
" renderElement(\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" }\n"
],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 229
}
|
import React from "react";
import ReactDOM from "react-dom";
import { render, fireEvent } from "./test-utils";
import App from "../components/App";
import * as Renderer from "../renderer/renderScene";
import { reseed } from "../random";
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
const renderScene = jest.spyOn(Renderer, "renderScene");
beforeEach(() => {
localStorage.clear();
renderScene.mockClear();
reseed(7);
});
const { h } = window;
describe("move element", () => {
it("rectangle", () => {
const { getByToolName, container } = render(<App />);
const canvas = container.querySelector("canvas")!;
{
// create element
const tool = getByToolName("rectangle");
fireEvent.click(tool);
fireEvent.pointerDown(canvas, { clientX: 30, clientY: 20 });
fireEvent.pointerMove(canvas, { clientX: 60, clientY: 70 });
fireEvent.pointerUp(canvas);
expect(renderScene).toHaveBeenCalledTimes(4);
expect(h.state.selectionElement).toBeNull();
expect(h.elements.length).toEqual(1);
expect(h.state.selectedElementIds[h.elements[0].id]).toBeTruthy();
expect([h.elements[0].x, h.elements[0].y]).toEqual([30, 20]);
renderScene.mockClear();
}
fireEvent.pointerDown(canvas, { clientX: 50, clientY: 20 });
fireEvent.pointerMove(canvas, { clientX: 20, clientY: 40 });
fireEvent.pointerUp(canvas);
expect(renderScene).toHaveBeenCalledTimes(3);
expect(h.state.selectionElement).toBeNull();
expect(h.elements.length).toEqual(1);
expect([h.elements[0].x, h.elements[0].y]).toEqual([0, 40]);
h.elements.forEach((element) => expect(element).toMatchSnapshot());
});
});
describe("duplicate element on move when ALT is clicked", () => {
it("rectangle", () => {
const { getByToolName, container } = render(<App />);
const canvas = container.querySelector("canvas")!;
{
// create element
const tool = getByToolName("rectangle");
fireEvent.click(tool);
fireEvent.pointerDown(canvas, { clientX: 30, clientY: 20 });
fireEvent.pointerMove(canvas, { clientX: 60, clientY: 70 });
fireEvent.pointerUp(canvas);
expect(renderScene).toHaveBeenCalledTimes(4);
expect(h.state.selectionElement).toBeNull();
expect(h.elements.length).toEqual(1);
expect(h.state.selectedElementIds[h.elements[0].id]).toBeTruthy();
expect([h.elements[0].x, h.elements[0].y]).toEqual([30, 20]);
renderScene.mockClear();
}
fireEvent.pointerDown(canvas, { clientX: 50, clientY: 20 });
fireEvent.pointerMove(canvas, { clientX: 20, clientY: 40, altKey: true });
// firing another pointerMove event with alt key pressed should NOT trigger
// another duplication
fireEvent.pointerMove(canvas, { clientX: 20, clientY: 40, altKey: true });
fireEvent.pointerMove(canvas, { clientX: 10, clientY: 60 });
fireEvent.pointerUp(canvas);
expect(renderScene).toHaveBeenCalledTimes(4);
expect(h.state.selectionElement).toBeNull();
expect(h.elements.length).toEqual(2);
// previous element should stay intact
expect([h.elements[0].x, h.elements[0].y]).toEqual([30, 20]);
expect([h.elements[1].x, h.elements[1].y]).toEqual([-10, 60]);
h.elements.forEach((element) => expect(element).toMatchSnapshot());
});
});
|
src/tests/move.test.tsx
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.00855844747275114,
0.0022877641022205353,
0.00016510307614225894,
0.00017066611326299608,
0.0032544333953410387
] |
{
"id": 5,
"code_window": [
" renderLinearPointHandles(context, appState, sceneState, element);\n",
" }\n",
" });\n",
"\n",
" // Paint selection element\n",
" if (selectionElement) {\n",
" renderElement(\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" }\n"
],
"file_path": "src/renderer/renderScene.ts",
"type": "replace",
"edit_start_line_idx": 229
}
|
import { reseed } from "../random";
import React from "react";
import ReactDOM from "react-dom";
import * as Renderer from "../renderer/renderScene";
import { waitFor, render, screen, fireEvent } from "./test-utils";
import App from "../components/App";
import { setLanguage } from "../i18n";
import { ToolName } from "./queries/toolQueries";
import { KEYS, Key } from "../keys";
import { setDateTimeForTests } from "../utils";
import { ExcalidrawElement } from "../element/types";
import { handlerRectangles } from "../element";
import { queryByText } from "@testing-library/react";
import { copiedStyles } from "../actions/actionStyles";
const { h } = window;
const renderScene = jest.spyOn(Renderer, "renderScene");
let getByToolName: (name: string) => HTMLElement = null!;
let canvas: HTMLCanvasElement = null!;
const clickTool = (toolName: ToolName) => {
fireEvent.click(getByToolName(toolName));
};
let altKey = false;
let shiftKey = false;
let ctrlKey = false;
function withModifierKeys(
modifiers: { alt?: boolean; shift?: boolean; ctrl?: boolean },
cb: () => void,
) {
const prevAltKey = altKey;
const prevShiftKey = shiftKey;
const prevCtrlKey = ctrlKey;
altKey = !!modifiers.alt;
shiftKey = !!modifiers.shift;
ctrlKey = !!modifiers.ctrl;
try {
cb();
} finally {
altKey = prevAltKey;
shiftKey = prevShiftKey;
ctrlKey = prevCtrlKey;
}
}
const hotkeyDown = (hotkey: Key) => {
const key = KEYS[hotkey];
if (typeof key !== "string") {
throw new Error("must provide a hotkey, not a key code");
}
keyDown(key);
};
const hotkeyUp = (hotkey: Key) => {
const key = KEYS[hotkey];
if (typeof key !== "string") {
throw new Error("must provide a hotkey, not a key code");
}
keyUp(key);
};
const keyDown = (key: string) => {
fireEvent.keyDown(document, {
key,
ctrlKey,
shiftKey,
altKey,
keyCode: key.toUpperCase().charCodeAt(0),
which: key.toUpperCase().charCodeAt(0),
});
};
const keyUp = (key: string) => {
fireEvent.keyUp(document, {
key,
ctrlKey,
shiftKey,
altKey,
keyCode: key.toUpperCase().charCodeAt(0),
which: key.toUpperCase().charCodeAt(0),
});
};
const hotkeyPress = (key: Key) => {
hotkeyDown(key);
hotkeyUp(key);
};
const keyPress = (key: string) => {
keyDown(key);
keyUp(key);
};
class Pointer {
private clientX = 0;
private clientY = 0;
constructor(
private readonly pointerType: "mouse" | "touch" | "pen",
private readonly pointerId = 1,
) {}
reset() {
this.clientX = 0;
this.clientY = 0;
}
getPosition() {
return [this.clientX, this.clientY];
}
restorePosition(x = 0, y = 0) {
this.clientX = x;
this.clientY = y;
fireEvent.pointerMove(canvas, this.getEvent());
}
private getEvent() {
return {
clientX: this.clientX,
clientY: this.clientY,
pointerType: this.pointerType,
pointerId: this.pointerId,
altKey,
shiftKey,
ctrlKey,
};
}
move(dx: number, dy: number) {
if (dx !== 0 || dy !== 0) {
this.clientX += dx;
this.clientY += dy;
fireEvent.pointerMove(canvas, this.getEvent());
}
}
down(dx = 0, dy = 0) {
this.move(dx, dy);
fireEvent.pointerDown(canvas, this.getEvent());
}
up(dx = 0, dy = 0) {
this.move(dx, dy);
fireEvent.pointerUp(canvas, this.getEvent());
}
click(dx = 0, dy = 0) {
this.down(dx, dy);
this.up();
}
doubleClick(dx = 0, dy = 0) {
this.move(dx, dy);
fireEvent.doubleClick(canvas, this.getEvent());
}
}
const mouse = new Pointer("mouse");
const finger1 = new Pointer("touch", 1);
const finger2 = new Pointer("touch", 2);
const clickLabeledElement = (label: string) => {
const element = document.querySelector(`[aria-label='${label}']`);
if (!element) {
throw new Error(`No labeled element found: ${label}`);
}
fireEvent.click(element);
};
const getSelectedElements = (): ExcalidrawElement[] => {
return h.elements.filter((element) => h.state.selectedElementIds[element.id]);
};
const getSelectedElement = (): ExcalidrawElement => {
const selectedElements = getSelectedElements();
if (selectedElements.length !== 1) {
throw new Error(
`expected 1 selected element; got ${selectedElements.length}`,
);
}
return selectedElements[0];
};
function getStateHistory() {
// @ts-ignore
return h.history.stateHistory;
}
type HandlerRectanglesRet = keyof ReturnType<typeof handlerRectangles>;
const getResizeHandles = (pointerType: "mouse" | "touch" | "pen") => {
const rects = handlerRectangles(
getSelectedElement(),
h.state.zoom,
pointerType,
) as {
[T in HandlerRectanglesRet]: [number, number, number, number];
};
const rv: { [K in keyof typeof rects]: [number, number] } = {} as any;
for (const handlePos in rects) {
const [x, y, width, height] = rects[handlePos as keyof typeof rects];
rv[handlePos as keyof typeof rects] = [x + width / 2, y + height / 2];
}
return rv;
};
/**
* This is always called at the end of your test, so usually you don't need to call it.
* However, if you have a long test, you might want to call it during the test so it's easier
* to debug where a test failure came from.
*/
const checkpoint = (name: string) => {
expect(renderScene.mock.calls.length).toMatchSnapshot(
`[${name}] number of renders`,
);
expect(h.state).toMatchSnapshot(`[${name}] appState`);
expect(h.history.getSnapshotForTest()).toMatchSnapshot(`[${name}] history`);
expect(h.elements.length).toMatchSnapshot(`[${name}] number of elements`);
h.elements.forEach((element, i) =>
expect(element).toMatchSnapshot(`[${name}] element ${i}`),
);
};
beforeEach(async () => {
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
localStorage.clear();
renderScene.mockClear();
h.history.clear();
reseed(7);
setDateTimeForTests("201933152653");
mouse.reset();
finger1.reset();
finger2.reset();
altKey = ctrlKey = shiftKey = false;
await setLanguage("en.json");
const renderResult = render(<App />);
getByToolName = renderResult.getByToolName;
canvas = renderResult.container.querySelector("canvas")!;
});
afterEach(() => {
checkpoint("end of test");
});
describe("regression tests", () => {
it("draw every type of shape", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
clickTool("diamond");
mouse.down(10, -10);
mouse.up(10, 10);
clickTool("ellipse");
mouse.down(10, -10);
mouse.up(10, 10);
clickTool("arrow");
mouse.down(10, -10);
mouse.up(10, 10);
clickTool("line");
mouse.down(10, -10);
mouse.up(10, 10);
clickTool("arrow");
mouse.click(10, -10);
mouse.click(10, 10);
mouse.click(-10, 10);
hotkeyPress("ENTER");
clickTool("line");
mouse.click(10, -20);
mouse.click(10, 10);
mouse.click(-10, 10);
hotkeyPress("ENTER");
clickTool("draw");
mouse.down(10, -20);
mouse.up(10, 10);
expect(h.elements.map((element) => element.type)).toEqual([
"rectangle",
"diamond",
"ellipse",
"arrow",
"line",
"arrow",
"line",
"draw",
]);
});
it("click to select a shape", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
const firstRectPos = mouse.getPosition();
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
const prevSelectedId = getSelectedElement().id;
mouse.restorePosition(...firstRectPos);
mouse.click();
expect(getSelectedElement().id).not.toEqual(prevSelectedId);
});
for (const [keys, shape] of [
["2r", "rectangle"],
["3d", "diamond"],
["4e", "ellipse"],
["5a", "arrow"],
["6l", "line"],
["7x", "draw"],
] as [string, ExcalidrawElement["type"]][]) {
for (const key of keys) {
it(`hotkey ${key} selects ${shape} tool`, () => {
keyPress(key);
mouse.down(10, 10);
mouse.up(10, 10);
expect(getSelectedElement().type).toBe(shape);
});
}
}
it("change the properties of a shape", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
clickLabeledElement("Background");
clickLabeledElement("#fa5252");
clickLabeledElement("Stroke");
clickLabeledElement("#5f3dc4");
expect(getSelectedElement().backgroundColor).toBe("#fa5252");
expect(getSelectedElement().strokeColor).toBe("#5f3dc4");
});
it("resize an element, trying every resize handle", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
const resizeHandles = getResizeHandles("mouse");
delete resizeHandles.rotation; // exclude rotation handle
for (const handlePos in resizeHandles) {
const [x, y] = resizeHandles[handlePos as keyof typeof resizeHandles];
const { width: prevWidth, height: prevHeight } = getSelectedElement();
mouse.restorePosition(x, y);
mouse.down();
mouse.up(-5, -5);
const {
width: nextWidthNegative,
height: nextHeightNegative,
} = getSelectedElement();
expect(
prevWidth !== nextWidthNegative || prevHeight !== nextHeightNegative,
).toBeTruthy();
checkpoint(`resize handle ${handlePos} (-5, -5)`);
mouse.down();
mouse.up(5, 5);
const { width, height } = getSelectedElement();
expect(width).toBe(prevWidth);
expect(height).toBe(prevHeight);
checkpoint(`unresize handle ${handlePos} (-5, -5)`);
mouse.restorePosition(x, y);
mouse.down();
mouse.up(5, 5);
const {
width: nextWidthPositive,
height: nextHeightPositive,
} = getSelectedElement();
expect(
prevWidth !== nextWidthPositive || prevHeight !== nextHeightPositive,
).toBeTruthy();
checkpoint(`resize handle ${handlePos} (+5, +5)`);
mouse.down();
mouse.up(-5, -5);
const { width: finalWidth, height: finalHeight } = getSelectedElement();
expect(finalWidth).toBe(prevWidth);
expect(finalHeight).toBe(prevHeight);
checkpoint(`unresize handle ${handlePos} (+5, +5)`);
}
});
it("click on an element and drag it", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
const { x: prevX, y: prevY } = getSelectedElement();
mouse.down(-10, -10);
mouse.up(10, 10);
const { x: nextX, y: nextY } = getSelectedElement();
expect(nextX).toBeGreaterThan(prevX);
expect(nextY).toBeGreaterThan(prevY);
checkpoint("dragged");
mouse.down();
mouse.up(-10, -10);
const { x, y } = getSelectedElement();
expect(x).toBe(prevX);
expect(y).toBe(prevY);
});
it("alt-drag duplicates an element", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
expect(
h.elements.filter((element) => element.type === "rectangle").length,
).toBe(1);
withModifierKeys({ alt: true }, () => {
mouse.down(-10, -10);
mouse.up(10, 10);
});
expect(
h.elements.filter((element) => element.type === "rectangle").length,
).toBe(2);
});
it("click-drag to select a group", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
const finalPosition = mouse.getPosition();
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
mouse.restorePosition(0, 0);
mouse.down();
mouse.restorePosition(...finalPosition);
mouse.up(5, 5);
expect(
h.elements.filter((element) => h.state.selectedElementIds[element.id])
.length,
).toBe(2);
});
it("shift-click to multiselect, then drag", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
const prevRectsXY = h.elements
.filter((element) => element.type === "rectangle")
.map((element) => ({ x: element.x, y: element.y }));
mouse.reset();
mouse.click(10, 10);
withModifierKeys({ shift: true }, () => {
mouse.click(20, 0);
});
mouse.down();
mouse.up(10, 10);
h.elements
.filter((element) => element.type === "rectangle")
.forEach((element, i) => {
expect(element.x).toBeGreaterThan(prevRectsXY[i].x);
expect(element.y).toBeGreaterThan(prevRectsXY[i].y);
});
});
it("pinch-to-zoom works", () => {
expect(h.state.zoom).toBe(1);
finger1.down(50, 50);
finger2.down(60, 50);
finger1.move(-10, 0);
expect(h.state.zoom).toBeGreaterThan(1);
const zoomed = h.state.zoom;
finger1.move(5, 0);
finger2.move(-5, 0);
expect(h.state.zoom).toBeLessThan(zoomed);
});
it("two-finger scroll works", () => {
const startScrollY = h.state.scrollY;
finger1.down(50, 50);
finger2.down(60, 50);
finger1.up(0, -10);
finger2.up(0, -10);
expect(h.state.scrollY).toBeLessThan(startScrollY);
const startScrollX = h.state.scrollX;
finger1.restorePosition(50, 50);
finger2.restorePosition(50, 60);
finger1.down();
finger2.down();
finger1.up(10, 0);
finger2.up(10, 0);
expect(h.state.scrollX).toBeGreaterThan(startScrollX);
});
it("spacebar + drag scrolls the canvas", () => {
const { scrollX: startScrollX, scrollY: startScrollY } = h.state;
hotkeyDown("SPACE");
mouse.down(50, 50);
mouse.up(60, 60);
hotkeyUp("SPACE");
const { scrollX, scrollY } = h.state;
expect(scrollX).not.toEqual(startScrollX);
expect(scrollY).not.toEqual(startScrollY);
});
it("arrow keys", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
hotkeyPress("ARROW_LEFT");
hotkeyPress("ARROW_LEFT");
hotkeyPress("ARROW_RIGHT");
hotkeyPress("ARROW_UP");
hotkeyPress("ARROW_UP");
hotkeyPress("ARROW_DOWN");
expect(h.elements[0].x).toBe(9);
expect(h.elements[0].y).toBe(9);
});
it("undo/redo drawing an element", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
clickTool("arrow");
mouse.click(10, -10);
mouse.click(10, 10);
mouse.click(-10, 10);
hotkeyPress("ENTER");
expect(h.elements.filter((element) => !element.isDeleted).length).toBe(3);
withModifierKeys({ ctrl: true }, () => {
keyPress("z");
keyPress("z");
});
expect(h.elements.filter((element) => !element.isDeleted).length).toBe(2);
withModifierKeys({ ctrl: true }, () => {
keyPress("z");
});
expect(h.elements.filter((element) => !element.isDeleted).length).toBe(1);
withModifierKeys({ ctrl: true, shift: true }, () => {
keyPress("z");
});
expect(h.elements.filter((element) => !element.isDeleted).length).toBe(2);
});
it("noop interaction after undo shouldn't create history entry", () => {
// NOTE: this will fail if this test case is run in isolation. There's
// some leaking state or race conditions in initialization/teardown
// (couldn't figure out)
expect(getStateHistory().length).toBe(0);
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
const firstElementEndPoint = mouse.getPosition();
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
const secondElementEndPoint = mouse.getPosition();
expect(getStateHistory().length).toBe(2);
withModifierKeys({ ctrl: true }, () => {
keyPress("z");
});
expect(getStateHistory().length).toBe(1);
// clicking an element shouldn't add to history
mouse.restorePosition(...firstElementEndPoint);
mouse.click();
expect(getStateHistory().length).toBe(1);
withModifierKeys({ shift: true, ctrl: true }, () => {
keyPress("z");
});
expect(getStateHistory().length).toBe(2);
// clicking an element shouldn't add to history
mouse.click();
expect(getStateHistory().length).toBe(2);
const firstSelectedElementId = getSelectedElement().id;
// same for clicking the element just redo-ed
mouse.restorePosition(...secondElementEndPoint);
mouse.click();
expect(getStateHistory().length).toBe(2);
expect(getSelectedElement().id).not.toEqual(firstSelectedElementId);
});
it("zoom hotkeys", () => {
expect(h.state.zoom).toBe(1);
fireEvent.keyDown(document, { code: "Equal", ctrlKey: true });
fireEvent.keyUp(document, { code: "Equal", ctrlKey: true });
expect(h.state.zoom).toBeGreaterThan(1);
fireEvent.keyDown(document, { code: "Minus", ctrlKey: true });
fireEvent.keyUp(document, { code: "Minus", ctrlKey: true });
expect(h.state.zoom).toBe(1);
});
it("rerenders UI on language change", async () => {
// select rectangle tool to show properties menu
clickTool("rectangle");
// english lang should display `hachure` label
expect(screen.queryByText(/hachure/i)).not.toBeNull();
fireEvent.change(document.querySelector(".dropdown-select__language")!, {
target: { value: "de-DE" },
});
// switching to german, `hachure` label should no longer exist
await waitFor(() => expect(screen.queryByText(/hachure/i)).toBeNull());
// reset language
fireEvent.change(document.querySelector(".dropdown-select__language")!, {
target: { value: "en" },
});
// switching back to English
await waitFor(() => expect(screen.queryByText(/hachure/i)).not.toBeNull());
});
it("make a group and duplicate it", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
const end = mouse.getPosition();
mouse.reset();
mouse.down();
mouse.restorePosition(...end);
mouse.up();
expect(h.elements.length).toBe(3);
for (const element of h.elements) {
expect(element.groupIds.length).toBe(0);
expect(h.state.selectedElementIds[element.id]).toBe(true);
}
withModifierKeys({ ctrl: true }, () => {
keyPress("g");
});
for (const element of h.elements) {
expect(element.groupIds.length).toBe(1);
}
withModifierKeys({ alt: true }, () => {
mouse.restorePosition(...end);
mouse.down();
mouse.up(10, 10);
});
expect(h.elements.length).toBe(6);
const groups = new Set();
for (const element of h.elements) {
for (const groupId of element.groupIds) {
groups.add(groupId);
}
}
expect(groups.size).toBe(2);
});
it("double click to edit a group", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
withModifierKeys({ ctrl: true }, () => {
keyPress("a");
keyPress("g");
});
expect(getSelectedElements().length).toBe(3);
expect(h.state.editingGroupId).toBe(null);
mouse.doubleClick();
expect(getSelectedElements().length).toBe(1);
expect(h.state.editingGroupId).not.toBe(null);
});
it("adjusts z order when grouping", () => {
const positions = [];
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
positions.push(mouse.getPosition());
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
positions.push(mouse.getPosition());
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
positions.push(mouse.getPosition());
const ids = h.elements.map((element) => element.id);
mouse.restorePosition(...positions[0]);
mouse.click();
mouse.restorePosition(...positions[2]);
withModifierKeys({ shift: true }, () => {
mouse.click();
});
withModifierKeys({ ctrl: true }, () => {
keyPress("g");
});
expect(h.elements.map((element) => element.id)).toEqual([
ids[1],
ids[0],
ids[2],
]);
});
it("supports nested groups", () => {
const positions: number[][] = [];
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
positions.push(mouse.getPosition());
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
positions.push(mouse.getPosition());
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
positions.push(mouse.getPosition());
withModifierKeys({ ctrl: true }, () => {
keyPress("a");
keyPress("g");
});
mouse.doubleClick();
withModifierKeys({ shift: true }, () => {
mouse.restorePosition(...positions[0]);
mouse.click();
});
withModifierKeys({ ctrl: true }, () => {
keyPress("g");
});
const groupIds = h.elements[2].groupIds;
expect(groupIds.length).toBe(2);
expect(h.elements[1].groupIds).toEqual(groupIds);
expect(h.elements[0].groupIds).toEqual(groupIds.slice(1));
mouse.click(50, 50);
expect(getSelectedElements().length).toBe(0);
mouse.restorePosition(...positions[0]);
mouse.click();
expect(getSelectedElements().length).toBe(3);
expect(h.state.editingGroupId).toBe(null);
mouse.doubleClick();
expect(getSelectedElements().length).toBe(2);
expect(h.state.editingGroupId).toBe(groupIds[1]);
mouse.doubleClick();
expect(getSelectedElements().length).toBe(1);
expect(h.state.editingGroupId).toBe(groupIds[0]);
// click out of the group
mouse.restorePosition(...positions[1]);
mouse.click();
expect(getSelectedElements().length).toBe(0);
mouse.click();
expect(getSelectedElements().length).toBe(3);
mouse.doubleClick();
expect(getSelectedElements().length).toBe(1);
});
it("updates fontSize & fontFamily appState", () => {
clickTool("text");
expect(h.state.currentItemFontFamily).toEqual(1); // Virgil
fireEvent.click(screen.getByText(/code/i));
expect(h.state.currentItemFontFamily).toEqual(3); // Cascadia
});
it("shows context menu for canvas", () => {
fireEvent.contextMenu(canvas, { button: 2, clientX: 1, clientY: 1 });
const contextMenu = document.querySelector(".context-menu");
const options = contextMenu?.querySelectorAll(".context-menu-option");
const expectedOptions = ["Select all", "Toggle grid mode"];
expect(contextMenu).not.toBeNull();
expect(options?.length).toBe(2);
expect(options?.item(0).textContent).toBe(expectedOptions[0]);
});
it("shows context menu for element", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
fireEvent.contextMenu(canvas, { button: 2, clientX: 1, clientY: 1 });
const contextMenu = document.querySelector(".context-menu");
const options = contextMenu?.querySelectorAll(".context-menu-option");
const expectedOptions = [
"Copy styles",
"Paste styles",
"Delete",
"Add to library",
"Send backward",
"Bring forward",
"Send to back",
"Bring to front",
"Duplicate",
];
expect(contextMenu).not.toBeNull();
expect(contextMenu?.children.length).toBe(9);
options?.forEach((opt, i) => {
expect(opt.textContent).toBe(expectedOptions[i]);
});
});
it("shows 'Group selection' in context menu for multiple selected elements", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
mouse.reset();
mouse.click(10, 10);
withModifierKeys({ shift: true }, () => {
mouse.click(20, 0);
});
fireEvent.contextMenu(canvas, { button: 2, clientX: 1, clientY: 1 });
const contextMenu = document.querySelector(".context-menu");
const options = contextMenu?.querySelectorAll(".context-menu-option");
const expectedOptions = [
"Copy styles",
"Paste styles",
"Delete",
"Group selection",
"Add to library",
"Send backward",
"Bring forward",
"Send to back",
"Bring to front",
"Duplicate",
];
expect(contextMenu).not.toBeNull();
expect(contextMenu?.children.length).toBe(10);
options?.forEach((opt, i) => {
expect(opt.textContent).toBe(expectedOptions[i]);
});
});
it("shows 'Ungroup selection' in context menu for group inside selected elements", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
mouse.reset();
mouse.click(10, 10);
withModifierKeys({ shift: true }, () => {
mouse.click(20, 0);
});
withModifierKeys({ ctrl: true }, () => {
keyPress("g");
});
fireEvent.contextMenu(canvas, { button: 2, clientX: 1, clientY: 1 });
const contextMenu = document.querySelector(".context-menu");
const options = contextMenu?.querySelectorAll(".context-menu-option");
const expectedOptions = [
"Copy styles",
"Paste styles",
"Delete",
"Ungroup selection",
"Add to library",
"Send backward",
"Bring forward",
"Send to back",
"Bring to front",
"Duplicate",
];
expect(contextMenu).not.toBeNull();
expect(contextMenu?.children.length).toBe(10);
options?.forEach((opt, i) => {
expect(opt.textContent).toBe(expectedOptions[i]);
});
});
it("selecting 'Copy styles' in context menu copies styles", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
fireEvent.contextMenu(canvas, { button: 2, clientX: 1, clientY: 1 });
const contextMenu = document.querySelector(".context-menu");
expect(copiedStyles).toBe("{}");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Copy styles")!);
expect(copiedStyles).not.toBe("{}");
const element = JSON.parse(copiedStyles);
expect(element).toEqual(getSelectedElement());
});
it("selecting 'Paste styles' in context menu pastes styles", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
// Change some styles of second rectangle
clickLabeledElement("Stroke");
clickLabeledElement("#c92a2a");
clickLabeledElement("Background");
clickLabeledElement("#e64980");
// Fill style
fireEvent.click(screen.getByLabelText("Cross-hatch"));
// Stroke width
fireEvent.click(screen.getByLabelText("Bold"));
// Stroke style
fireEvent.click(screen.getByLabelText("Dotted"));
// Roughness
fireEvent.click(screen.getByLabelText("Cartoonist"));
// Opacity
fireEvent.change(screen.getByLabelText("Opacity"), {
target: { value: "60" },
});
mouse.reset();
// Copy styles of second rectangle
fireEvent.contextMenu(canvas, { button: 2, clientX: 40, clientY: 40 });
let contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Copy styles")!);
const secondRect = JSON.parse(copiedStyles);
expect(secondRect.id).toBe(h.elements[1].id);
mouse.reset();
// Paste styles to first rectangle
fireEvent.contextMenu(canvas, { button: 2, clientX: 10, clientY: 10 });
contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Paste styles")!);
const firstRect = getSelectedElement();
expect(firstRect.id).toBe(h.elements[0].id);
expect(firstRect.strokeColor).toBe("#c92a2a");
expect(firstRect.backgroundColor).toBe("#e64980");
expect(firstRect.fillStyle).toBe("cross-hatch");
expect(firstRect.strokeWidth).toBe(2); // Bold: 2
expect(firstRect.strokeStyle).toBe("dotted");
expect(firstRect.roughness).toBe(2); // Cartoonist: 2
expect(firstRect.opacity).toBe(60);
});
it("selecting 'Delete' in context menu deletes element", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
fireEvent.contextMenu(canvas, { button: 2, clientX: 1, clientY: 1 });
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Delete")!);
expect(getSelectedElements()).toHaveLength(0);
expect(h.elements[0].isDeleted).toBe(true);
});
it("selecting 'Add to library' in context menu adds element to library", async () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
fireEvent.contextMenu(canvas, { button: 2, clientX: 1, clientY: 1 });
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Add to library")!);
await waitFor(() => {
const library = localStorage.getItem("excalidraw-library");
expect(library).not.toBeNull();
const addedElement = JSON.parse(library!)[0][0];
expect(addedElement).toEqual(h.elements[0]);
});
});
it("selecting 'Duplicate' in context menu duplicates element", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
fireEvent.contextMenu(canvas, { button: 2, clientX: 1, clientY: 1 });
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Duplicate")!);
expect(h.elements).toHaveLength(2);
const { id: _id0, seed: _seed0, x: _x0, y: _y0, ...rect1 } = h.elements[0];
const { id: _id1, seed: _seed1, x: _x1, y: _y1, ...rect2 } = h.elements[1];
expect(rect1).toEqual(rect2);
});
it("selecting 'Send backward' in context menu sends element backward", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
fireEvent.contextMenu(canvas, { button: 2, clientX: 40, clientY: 40 });
const contextMenu = document.querySelector(".context-menu");
const elementsBefore = h.elements;
fireEvent.click(queryByText(contextMenu as HTMLElement, "Send backward")!);
expect(elementsBefore[0].id).toEqual(h.elements[1].id);
expect(elementsBefore[1].id).toEqual(h.elements[0].id);
});
it("selecting 'Bring forward' in context menu brings element forward", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
fireEvent.contextMenu(canvas, { button: 2, clientX: 10, clientY: 10 });
const contextMenu = document.querySelector(".context-menu");
const elementsBefore = h.elements;
fireEvent.click(queryByText(contextMenu as HTMLElement, "Bring forward")!);
expect(elementsBefore[0].id).toEqual(h.elements[1].id);
expect(elementsBefore[1].id).toEqual(h.elements[0].id);
});
it("selecting 'Send to back' in context menu sends element to back", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
fireEvent.contextMenu(canvas, { button: 2, clientX: 40, clientY: 40 });
const contextMenu = document.querySelector(".context-menu");
const elementsBefore = h.elements;
fireEvent.click(queryByText(contextMenu as HTMLElement, "Send to back")!);
expect(elementsBefore[1].id).toEqual(h.elements[0].id);
});
it("selecting 'Bring to front' in context menu brings element to front", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
fireEvent.contextMenu(canvas, { button: 2, clientX: 10, clientY: 10 });
const contextMenu = document.querySelector(".context-menu");
const elementsBefore = h.elements;
fireEvent.click(queryByText(contextMenu as HTMLElement, "Bring to front")!);
expect(elementsBefore[0].id).toEqual(h.elements[1].id);
});
it("selecting 'Group selection' in context menu groups selected elements", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
withModifierKeys({ shift: true }, () => {
mouse.click(10, 10);
});
fireEvent.contextMenu(canvas, { button: 2, clientX: 1, clientY: 1 });
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Group selection")!,
);
const selectedGroupIds = Object.keys(h.state.selectedGroupIds);
expect(h.elements[0].groupIds).toEqual(selectedGroupIds);
expect(h.elements[1].groupIds).toEqual(selectedGroupIds);
});
it("selecting 'Ungroup selection' in context menu ungroups selected group", () => {
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
withModifierKeys({ shift: true }, () => {
mouse.click(10, 10);
});
withModifierKeys({ ctrl: true }, () => {
keyPress("g");
});
fireEvent.contextMenu(canvas, { button: 2, clientX: 1, clientY: 1 });
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Ungroup selection")!,
);
const selectedGroupIds = Object.keys(h.state.selectedGroupIds);
expect(selectedGroupIds).toHaveLength(0);
expect(h.elements[0].groupIds).toHaveLength(0);
expect(h.elements[1].groupIds).toHaveLength(0);
});
});
|
src/tests/regressionTests.test.tsx
| 0 |
https://github.com/excalidraw/excalidraw/commit/f295550940c7ee03f61cead395080a09ad27b599
|
[
0.003191422438248992,
0.00019839427841361612,
0.00016228888125624508,
0.00017245180788449943,
0.0002724941004998982
] |
{
"id": 0,
"code_window": [
"import NotFoundPage from 'containers/NotFoundPage/Loadable';\n",
"import OverlayBlocker from 'components/OverlayBlocker';\n",
"import PluginPage from 'containers/PluginPage';\n",
"// Utils\n",
"import auth from 'utils/auth';\n",
"import injectReducer from 'utils/injectReducer';\n",
"import injectSaga from 'utils/injectSaga';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import FullStory from 'components/FullStory';\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "add",
"edit_start_line_idx": 45
}
|
/**
*
* App.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router-dom';
import AdminPage from 'containers/AdminPage';
import NotFoundPage from 'containers/NotFoundPage';
import NotificationProvider from 'containers/NotificationProvider';
import AppLoader from 'containers/AppLoader';
import FullStory from 'components/FullStory';
import LoadingIndicatorPage from 'components/LoadingIndicatorPage';
import '../../styles/main.scss';
import styles from './styles.scss';
export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<FullStory org="GK708" />
<NotificationProvider />
<AppLoader>
{({ shouldLoad }) => {
if (shouldLoad) {
return <LoadingIndicatorPage />;
}
return (
<div className={styles.container}>
<Switch>
<Route path="/" component={AdminPage} />
<Route path="" component={NotFoundPage} />
</Switch>
</div>
);
}}
</AppLoader>
</div>
);
}
}
App.contextTypes = {
router: PropTypes.object.isRequired,
};
App.propTypes = {};
export default App;
|
packages/strapi-admin/admin/src/containers/App/index.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00020798202604055405,
0.0001740930019877851,
0.00015803954738657922,
0.00016979733482003212,
0.00001599456118128728
] |
{
"id": 0,
"code_window": [
"import NotFoundPage from 'containers/NotFoundPage/Loadable';\n",
"import OverlayBlocker from 'components/OverlayBlocker';\n",
"import PluginPage from 'containers/PluginPage';\n",
"// Utils\n",
"import auth from 'utils/auth';\n",
"import injectReducer from 'utils/injectReducer';\n",
"import injectSaga from 'utils/injectSaga';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import FullStory from 'components/FullStory';\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "add",
"edit_start_line_idx": 45
}
|
.gradientOff {
background-image: linear-gradient( to bottom right, #F65A1D, #F68E0E );
color: white !important;
z-index: 0!important;
&:active, :hover {
box-shadow: inset -1px 1px 3px rgba(0,0,0,0.1);
background-image: linear-gradient( to bottom right, #F65A1D, #F68E0E );
color: white !important;
z-index: 0!important;
}
}
.gradientOn {
background-image: linear-gradient( to bottom right, #005EEA, #0097F6);
color: white !important;
box-shadow: inset 1px 1px 3px rgba(0,0,0,0.1);
&:active, :hover {
background-image: linear-gradient( to bottom right, #005EEA, #0097F6);
color: white !important;
z-index: 0!important;
}
}
.inputToggleContainer {
padding-top: 9px;
> button {
width: 5.3rem;
height: 3.4rem;
margin-bottom: 2.8rem;
padding: 0;
border: 1px solid #E3E9F3;
border-radius: 0.25rem;
color: #CED3DB;
background-color: white;
box-shadow: 0px 1px 1px rgba(104, 118, 142, 0.05);
font-weight: 600;
font-size: 1.2rem;
letter-spacing: 0.1rem;
font-family: Lato;
line-height: 3.4rem;
cursor: pointer;
&:first-of-type {
border-right: none;
}
&:nth-of-type(2) {
border-left: none;
}
&:hover {
z-index: 0 !important;
}
&:focus {
outline: 0;
box-shadow: 0 0 0;
}
&:disabled {
cursor: not-allowed;
}
}
}
.error {
> button {
&:first-child {
border: 1px solid #ff203c !important;
border-right: 0 !important;
}
&:last-child {
border: 1px solid #ff203c !important;
border-left: 0 !important;
}
}
}
|
packages/strapi-helper-plugin/lib/src/components/InputToggle/styles.scss
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017911827308125794,
0.00017552374629303813,
0.0001679019769653678,
0.00017625439795665443,
0.0000034057361517625395
] |
{
"id": 0,
"code_window": [
"import NotFoundPage from 'containers/NotFoundPage/Loadable';\n",
"import OverlayBlocker from 'components/OverlayBlocker';\n",
"import PluginPage from 'containers/PluginPage';\n",
"// Utils\n",
"import auth from 'utils/auth';\n",
"import injectReducer from 'utils/injectReducer';\n",
"import injectSaga from 'utils/injectSaga';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import FullStory from 'components/FullStory';\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "add",
"edit_start_line_idx": 45
}
|
/**
*
* Sub
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { isFunction, isObject } from 'lodash';
import cn from 'classnames';
import LoadingBar from 'components/LoadingBar';
import styles from './styles.scss';
function Sub({ bordered, content, link, name, style, title, underline }) {
if (isObject(title)) {
return (
<div className={cn(styles.subWrapper, bordered && styles.subBordered)}>
<FormattedMessage {...title}>
{message => <span className={cn(underline && styles.underlinedTitle)}>{message}{name}</span>}
</FormattedMessage>
{content()}
</div>
);
}
return (
<a className={cn(styles.subWrapper, bordered && styles.subBordered, styles.link)} href={`https://blog.strapi.io/${link}`} target="_blank">
<span>{title}</span>
{title === '' && <LoadingBar />}
{content === '' && <LoadingBar style={{ width: '40%' }} />}
<p style={style}>
{isFunction(content) ? content() : content}
</p>
</a>
);
}
Sub.defaultProps = {
bordered: false,
content: () => '',
link: '',
name: '',
style: {},
title: {
id: 'app.utils.defaultMessage',
defaultMessage: 'app.utils.defaultMessage',
values: {},
},
underline: false,
};
Sub.propTypes = {
bordered: PropTypes.bool,
content: PropTypes.oneOfType([
PropTypes.func,
PropTypes.string,
]),
link: PropTypes.string,
name: PropTypes.string,
style: PropTypes.object,
title: PropTypes.oneOfType([
PropTypes.object,
PropTypes.string,
]),
underline: PropTypes.bool,
};
export default Sub;
|
packages/strapi-admin/admin/src/components/Sub/index.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017750091501511633,
0.00017326907254755497,
0.00016984697140287608,
0.0001731564407236874,
0.0000022499564238387393
] |
{
"id": 0,
"code_window": [
"import NotFoundPage from 'containers/NotFoundPage/Loadable';\n",
"import OverlayBlocker from 'components/OverlayBlocker';\n",
"import PluginPage from 'containers/PluginPage';\n",
"// Utils\n",
"import auth from 'utils/auth';\n",
"import injectReducer from 'utils/injectReducer';\n",
"import injectSaga from 'utils/injectSaga';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import FullStory from 'components/FullStory';\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "add",
"edit_start_line_idx": 45
}
|
.fade {
opacity: 0;
@include transition($transition-fade);
&.show {
opacity: 1;
}
}
.collapse {
display: none;
&.show {
display: block;
}
}
tr {
&.collapse.show {
display: table-row;
}
}
tbody {
&.collapse.show {
display: table-row-group;
}
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
@include transition($transition-collapse);
}
|
packages/strapi-admin/admin/src/styles/libs/bootstrap/_transitions.scss
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.0001800922182155773,
0.0001764303888194263,
0.00017294070858042687,
0.00017634429968893528,
0.0000029336047191463877
] |
{
"id": 1,
"code_window": [
" this.checkLogin(this.props);\n",
" ReactGA.initialize('UA-54313258-9');\n",
" }\n",
"\n",
" componentDidUpdate(prevProps) {\n",
" const { adminPage: { allowGa }, location: { pathname }, plugins } = this.props;\n",
"\n",
" if (prevProps.location.pathname !== pathname) {\n",
" this.checkLogin(this.props);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { adminPage: { uuid }, location: { pathname }, plugins } = this.props;\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "replace",
"edit_start_line_idx": 75
}
|
import { all, fork, call, put, select, takeLatest } from 'redux-saga/effects';
import auth from 'utils/auth';
import request from 'utils/request';
import { makeSelectAppPlugins } from 'containers/App/selectors';
import {
getAdminDataSucceeded,
} from './actions';
import { GET_ADMIN_DATA } from './constants';
function* getData() {
try {
const appPlugins = yield select(makeSelectAppPlugins());
const hasUserPlugin = appPlugins.indexOf('users-permissions') !== -1;
if (hasUserPlugin && auth.getToken() !== null) {
yield call(request, `${strapi.backendURL}/users/me`, { method: 'GET' });
}
const [{ allowGa }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([
call(request, '/admin/gaConfig', { method: 'GET' }),
call(request, '/admin/strapiVersion', { method: 'GET' }),
call(request, '/admin/currentEnvironment', { method: 'GET' }),
call(request, '/admin/layout', { method: 'GET' }),
]);
yield put(getAdminDataSucceeded({ allowGa, strapiVersion, currentEnvironment, layout }));
} catch(err) {
console.log(err); // eslint-disable-line no-console
}
}
function* defaultSaga() {
yield all([
fork(takeLatest, GET_ADMIN_DATA, getData),
]);
}
export default defaultSaga;
|
packages/strapi-admin/admin/src/containers/AdminPage/saga.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.0030110031366348267,
0.0009053338435478508,
0.00017353883595205843,
0.000218396628042683,
0.0012162281200289726
] |
{
"id": 1,
"code_window": [
" this.checkLogin(this.props);\n",
" ReactGA.initialize('UA-54313258-9');\n",
" }\n",
"\n",
" componentDidUpdate(prevProps) {\n",
" const { adminPage: { allowGa }, location: { pathname }, plugins } = this.props;\n",
"\n",
" if (prevProps.location.pathname !== pathname) {\n",
" this.checkLogin(this.props);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { adminPage: { uuid }, location: { pathname }, plugins } = this.props;\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "replace",
"edit_start_line_idx": 75
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { isEmpty } from 'lodash';
import { FormattedMessage } from 'react-intl';
import cn from 'classnames';
/* eslint-disable jsx-a11y/no-autofocus */
import styles from './styles.scss';
function InputText(props) {
const placeholder = isEmpty(props.placeholder) ? 'app.utils.placeholder.defaultMessage' : props.placeholder;
return (
<FormattedMessage id={placeholder} defaultMessage={placeholder}>
{(message) => (
<input
autoFocus={props.autoFocus}
className={cn(
styles.textInput,
'form-control',
!props.deactivateErrorHighlight && props.error && 'is-invalid',
!isEmpty(props.className) && props.className,
)}
disabled={props.disabled}
id={props.name}
name={props.name}
onBlur={props.onBlur}
onChange={props.onChange}
onFocus={props.onFocus}
placeholder={message}
ref={props.inputRef}
style={props.style}
tabIndex={props.tabIndex}
type="text"
value={props.value}
/>
)}
</FormattedMessage>
);
}
InputText.defaultProps = {
autoFocus: false,
className: '',
deactivateErrorHighlight: false,
disabled: false,
error: false,
inputRef: () => {},
onBlur: () => {},
onFocus: () => {},
placeholder: 'app.utils.placeholder.defaultMessage',
style: {},
tabIndex: '0',
};
InputText.propTypes = {
autoFocus: PropTypes.bool,
className: PropTypes.string,
deactivateErrorHighlight: PropTypes.bool,
disabled: PropTypes.bool,
error: PropTypes.bool,
inputRef: PropTypes.func,
name: PropTypes.string.isRequired,
onBlur: PropTypes.func,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func,
placeholder: PropTypes.string,
style: PropTypes.object,
tabIndex: PropTypes.string,
value: PropTypes.string.isRequired,
};
export default InputText;
|
packages/strapi-helper-plugin/lib/src/components/InputText/index.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017826077237259597,
0.0001711099612293765,
0.00016493155271746218,
0.00017056267824955285,
0.000004904291927232407
] |
{
"id": 1,
"code_window": [
" this.checkLogin(this.props);\n",
" ReactGA.initialize('UA-54313258-9');\n",
" }\n",
"\n",
" componentDidUpdate(prevProps) {\n",
" const { adminPage: { allowGa }, location: { pathname }, plugins } = this.props;\n",
"\n",
" if (prevProps.location.pathname !== pathname) {\n",
" this.checkLogin(this.props);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { adminPage: { uuid }, location: { pathname }, plugins } = this.props;\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "replace",
"edit_start_line_idx": 75
}
|
/**
*
* ImgPreviewArrow
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import styles from './styles.scss';
function ImgPreviewArrow(props) {
let divStyle = props.show ? {} : { display: 'none' };
if (props.enable) {
divStyle = { zIndex: 99999 };
}
return (
<div
className={cn(
styles.arrowContainer,
props.type === 'left' && styles.arrowLeft,
props.type !== 'left' && styles.arrowRight,
)}
style={divStyle}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
props.onClick(props.type);
}}
onMouseEnter={props.onMouseEnter}
onMouseLeave={props.onMouseLeave}
/>
);
}
ImgPreviewArrow.defaultProps = {
enable: false,
onClick: () => {},
onMouseEnter: () => {},
onMouseLeave: () => {},
show: false,
type: 'left',
};
ImgPreviewArrow.propTypes = {
enable: PropTypes.bool,
onClick: PropTypes.func,
onMouseEnter: PropTypes.func,
onMouseLeave: PropTypes.func,
show: PropTypes.bool,
type: PropTypes.string,
};
export default ImgPreviewArrow;
|
packages/strapi-helper-plugin/lib/src/components/ImgPreviewArrow/index.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00018692044250201434,
0.00017479470989201218,
0.00016769958892837167,
0.00017402993398718536,
0.0000064366445258201566
] |
{
"id": 1,
"code_window": [
" this.checkLogin(this.props);\n",
" ReactGA.initialize('UA-54313258-9');\n",
" }\n",
"\n",
" componentDidUpdate(prevProps) {\n",
" const { adminPage: { allowGa }, location: { pathname }, plugins } = this.props;\n",
"\n",
" if (prevProps.location.pathname !== pathname) {\n",
" this.checkLogin(this.props);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { adminPage: { uuid }, location: { pathname }, plugins } = this.props;\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "replace",
"edit_start_line_idx": 75
}
|
.emptyAttributesBlock { /* stylelint-disable */
height: 22.1rem;
margin-top: -.1rem;
padding-top: 5.8rem;
background-image: url('../../assets/images/background-empty-attributes.svg');
background-color: #FFFFFF;
background-repeat: repeat;
text-align: center;
font-size: 1.4rem;
font-family: Lato;
box-shadow: 2px 2px 4px #E3E9F3;
}
.title {
margin-bottom: 1.8rem;
font-size: 1.8rem;
line-height: 1.8rem;
font-weight: bold;
}
.description {
color: #333740;
}
.buttonContainer {
margin-top: 4.6rem;
> button {
padding-right: 1.5rem;
font-size: 1.3rem;
> i {
margin-right: 1rem !important;
}
}
}
|
packages/strapi-helper-plugin/lib/src/components/EmptyAttributesBlock/styles.scss
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017596222460269928,
0.0001740329316817224,
0.00017098098760470748,
0.00017459428636357188,
0.0000018488811974748387
] |
{
"id": 2,
"code_window": [
"\n",
" if (prevProps.location.pathname !== pathname) {\n",
" this.checkLogin(this.props);\n",
"\n",
" if (allowGa) {\n",
" ReactGA.pageview(pathname);\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (uuid) {\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "replace",
"edit_start_line_idx": 80
}
|
/*
* AdminPage
*
* This is the first thing users see of our AdminPage, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import ReactGA from 'react-ga';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { Switch, Route } from 'react-router-dom';
import { get, includes, isFunction, map, omit } from 'lodash';
import { bindActionCreators, compose } from 'redux';
// Actions required for disabling and enabling the OverlayBlocker
import { disableGlobalOverlayBlocker, enableGlobalOverlayBlocker } from 'actions/overlayBlocker';
import { pluginLoaded, updatePlugin } from 'containers/App/actions';
import {
makeSelectAppPlugins,
makeSelectBlockApp,
makeSelectIsAppLoading,
makeSelectShowGlobalAppBlocker,
selectHasUserPlugin,
selectPlugins,
} from 'containers/App/selectors';
// Design
import ComingSoonPage from 'containers/ComingSoonPage';
import Content from 'containers/Content';
import LocaleToggle from 'containers/LocaleToggle';
import CTAWrapper from 'components/CtaWrapper';
import Header from 'components/Header/index';
import HomePage from 'containers/HomePage/Loadable';
import InstallPluginPage from 'containers/InstallPluginPage/Loadable';
import LeftMenu from 'containers/LeftMenu';
import ListPluginsPage from 'containers/ListPluginsPage/Loadable';
import LoadingIndicatorPage from 'components/LoadingIndicatorPage';
import Logout from 'components/Logout';
import NotFoundPage from 'containers/NotFoundPage/Loadable';
import OverlayBlocker from 'components/OverlayBlocker';
import PluginPage from 'containers/PluginPage';
// Utils
import auth from 'utils/auth';
import injectReducer from 'utils/injectReducer';
import injectSaga from 'utils/injectSaga';
import { getAdminData } from './actions';
import reducer from './reducer';
import saga from './saga';
import selectAdminPage from './selectors';
import styles from './styles.scss';
const PLUGINS_TO_BLOCK_PRODUCTION = ['content-type-builder', 'settings-manager'];
export class AdminPage extends React.Component {
// eslint-disable-line react/prefer-stateless-function
state = { hasAlreadyRegistereOtherPlugins: false };
getChildContext = () => ({
disableGlobalOverlayBlocker: this.props.disableGlobalOverlayBlocker,
enableGlobalOverlayBlocker: this.props.enableGlobalOverlayBlocker,
plugins: this.props.plugins,
updatePlugin: this.props.updatePlugin,
});
componentDidMount() {
this.props.getAdminData();
this.checkLogin(this.props);
ReactGA.initialize('UA-54313258-9');
}
componentDidUpdate(prevProps) {
const { adminPage: { allowGa }, location: { pathname }, plugins } = this.props;
if (prevProps.location.pathname !== pathname) {
this.checkLogin(this.props);
if (allowGa) {
ReactGA.pageview(pathname);
}
}
const hasAdminPath = ['users-permissions', 'hasAdminUser'];
if (get(prevProps.plugins.toJS(), hasAdminPath) !== get(plugins.toJS(), hasAdminPath)) {
this.checkLogin(this.props, true);
}
if (!this.hasUserPluginLoaded(prevProps) && this.hasUserPluginLoaded(this.props)) {
this.checkLogin(this.props);
}
}
checkLogin = (props, skipAction = false) => {
if (props.hasUserPlugin && this.isUrlProtected(props) && !auth.getToken()) {
if (!this.hasUserPluginLoaded(props)) {
return;
}
const endPoint = this.hasAdminUser(props) ? 'login' : 'register';
this.props.history.push(`/plugins/users-permissions/auth/${endPoint}`);
}
if (
!this.isUrlProtected(props) &&
includes(props.location.pathname, 'auth/register') &&
this.hasAdminUser(props) &&
!skipAction
) {
this.props.history.push('/plugins/users-permissions/auth/login');
}
if (
props.hasUserPlugin &&
!this.isUrlProtected(props) &&
!includes(props.location.pathname, 'auth/register') &&
!this.hasAdminUser(props)
) {
this.props.history.push('/plugins/users-permissions/auth/register');
}
if (!props.hasUserPlugin || (auth.getToken() && !this.state.hasAlreadyRegistereOtherPlugins)) {
map(omit(this.props.plugins.toJS(), ['users-permissions', 'email']), plugin => {
switch (true) {
case isFunction(plugin.bootstrap) && isFunction(plugin.pluginRequirements):
plugin
.pluginRequirements(plugin)
.then(plugin => {
return plugin.bootstrap(plugin);
})
.then(plugin => this.props.pluginLoaded(plugin));
break;
case isFunction(plugin.pluginRequirements):
plugin.pluginRequirements(plugin).then(plugin => this.props.pluginLoaded(plugin));
break;
case isFunction(plugin.bootstrap):
plugin.bootstrap(plugin).then(plugin => this.props.pluginLoaded(plugin));
break;
default:
}
});
this.setState({ hasAlreadyRegistereOtherPlugins: true });
}
};
hasUserPluginInstalled = () => {
const { appPlugins } = this.props;
return appPlugins.indexOf('users-permissions') !== -1;
}
hasUserPluginLoaded = props =>
typeof get(props.plugins.toJS(), ['users-permissions', 'hasAdminUser']) !== 'undefined';
hasAdminUser = props => get(props.plugins.toJS(), ['users-permissions', 'hasAdminUser']);
isUrlProtected = props =>
!includes(props.location.pathname, get(props.plugins.toJS(), ['users-permissions', 'nonProtectedUrl']));
shouldDisplayLogout = () => auth.getToken() && this.props.hasUserPlugin && this.isUrlProtected(this.props);
showLeftMenu = () => !includes(this.props.location.pathname, 'users-permissions/auth/');
showLoading = () => {
const { isAppLoading, adminPage: { isLoading } } = this.props;
return isAppLoading || isLoading || (this.hasUserPluginInstalled() && !this.hasUserPluginLoaded(this.props));
}
retrievePlugins = () => {
const {
adminPage: { currentEnvironment },
plugins,
} = this.props;
if (currentEnvironment === 'production') {
let pluginsToDisplay = plugins;
PLUGINS_TO_BLOCK_PRODUCTION.map(plugin => (pluginsToDisplay = pluginsToDisplay.delete(plugin)));
return pluginsToDisplay;
}
return plugins;
};
render() {
const { adminPage } = this.props;
const header = this.showLeftMenu() ? <Header /> : '';
const style = this.showLeftMenu() ? {} : { width: '100%' };
if (this.showLoading()) {
return <LoadingIndicatorPage />;
}
return (
<div className={styles.adminPage}>
{this.showLeftMenu() && (
<LeftMenu
plugins={this.retrievePlugins()}
layout={adminPage.layout}
version={adminPage.strapiVersion}
/>
)}
<CTAWrapper>
{this.shouldDisplayLogout() && <Logout />}
<LocaleToggle isLogged={this.shouldDisplayLogout() === true} />
</CTAWrapper>
<div className={styles.adminPageRightWrapper} style={style}>
{header}
<Content {...this.props} showLeftMenu={this.showLeftMenu()}>
<Switch>
<Route path="/" component={HomePage} exact />
<Route path="/plugins/:pluginId" component={PluginPage} />
<Route path="/plugins" component={ComingSoonPage} />
<Route path="/list-plugins" component={ListPluginsPage} exact />
<Route path="/install-plugin" component={InstallPluginPage} exact />
<Route path="/configuration" component={ComingSoonPage} exact />
<Route path="" component={NotFoundPage} />
<Route path="404" component={NotFoundPage} />
</Switch>
</Content>
</div>
<OverlayBlocker isOpen={this.props.blockApp && this.props.showGlobalAppBlocker} />
</div>
);
}
}
AdminPage.childContextTypes = {
disableGlobalOverlayBlocker: PropTypes.func,
enableGlobalOverlayBlocker: PropTypes.func,
plugins: PropTypes.object,
updatePlugin: PropTypes.func,
};
AdminPage.contextTypes = {
router: PropTypes.object.isRequired,
};
AdminPage.defaultProps = {
adminPage: {},
appPlugins: [],
hasUserPlugin: true,
isAppLoading: true,
};
AdminPage.propTypes = {
adminPage: PropTypes.object,
appPlugins: PropTypes.array,
blockApp: PropTypes.bool.isRequired,
disableGlobalOverlayBlocker: PropTypes.func.isRequired,
enableGlobalOverlayBlocker: PropTypes.func.isRequired,
hasUserPlugin: PropTypes.bool,
history: PropTypes.object.isRequired,
isAppLoading: PropTypes.bool,
location: PropTypes.object.isRequired,
pluginLoaded: PropTypes.func.isRequired,
plugins: PropTypes.object.isRequired,
showGlobalAppBlocker: PropTypes.bool.isRequired,
updatePlugin: PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
adminPage: selectAdminPage(),
appPlugins: makeSelectAppPlugins(),
blockApp: makeSelectBlockApp(),
hasUserPlugin: selectHasUserPlugin(),
isAppLoading: makeSelectIsAppLoading(),
plugins: selectPlugins(),
showGlobalAppBlocker: makeSelectShowGlobalAppBlocker(),
});
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
disableGlobalOverlayBlocker,
enableGlobalOverlayBlocker,
getAdminData,
pluginLoaded,
updatePlugin,
},
dispatch,
);
}
const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({ key: 'adminPage', reducer });
const withSaga = injectSaga({ key: 'adminPage', saga });
export default compose(withReducer, withSaga, withConnect)(AdminPage);
|
packages/strapi-admin/admin/src/containers/AdminPage/index.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.9847601056098938,
0.060430169105529785,
0.0001646683522267267,
0.00017580948770046234,
0.2252727895975113
] |
{
"id": 2,
"code_window": [
"\n",
" if (prevProps.location.pathname !== pathname) {\n",
" this.checkLogin(this.props);\n",
"\n",
" if (allowGa) {\n",
" ReactGA.pageview(pathname);\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (uuid) {\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "replace",
"edit_start_line_idx": 80
}
|
// Resize anything
@mixin resizable($direction) {
overflow: auto; // Per CSS3 UI, `resize` only applies when `overflow` isn't `visible`
resize: $direction; // Options: horizontal, vertical, both
}
|
packages/strapi-admin/admin/src/styles/libs/bootstrap/mixins/_resize.scss
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00016536854673177004,
0.00016536854673177004,
0.00016536854673177004,
0.00016536854673177004,
0
] |
{
"id": 2,
"code_window": [
"\n",
" if (prevProps.location.pathname !== pathname) {\n",
" this.checkLogin(this.props);\n",
"\n",
" if (allowGa) {\n",
" ReactGA.pageview(pathname);\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (uuid) {\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "replace",
"edit_start_line_idx": 80
}
|
.editForm {
background: #ffffff;
padding: 45px 30px 22px 30px;
border-radius: 2px;
box-shadow: 0 2px 4px #E3E9F3;
}
.inputStyle {
max-width: 358px;
}
.separator {
height: 1px;
width: 100%;
margin-bottom: 22px;
background: #F6F6F6;
box-sizing: border-box;
}
.subFormWrapper {
margin-bottom: 14px;
padding: 23px 30px 0 30px;
background-color: #FAFAFB;
}
|
packages/strapi-plugin-email/admin/src/components/EditForm/styles.scss
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017576635582372546,
0.0001748583308653906,
0.0001740205188980326,
0.00017478816153015941,
7.144606684050814e-7
] |
{
"id": 2,
"code_window": [
"\n",
" if (prevProps.location.pathname !== pathname) {\n",
" this.checkLogin(this.props);\n",
"\n",
" if (allowGa) {\n",
" ReactGA.pageview(pathname);\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (uuid) {\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "replace",
"edit_start_line_idx": 80
}
|
/**
*
* Separator
*
*/
import React from 'react';
import styles from './styles.scss';
const Separator = () => <span className={styles.separatorSpan} />;
export default Separator;
|
packages/strapi-plugin-content-manager/admin/src/components/Filter/Separator.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017866473353933543,
0.000175731343915686,
0.0001727979542920366,
0.000175731343915686,
0.0000029333896236494184
] |
{
"id": 3,
"code_window": [
" return <LoadingIndicatorPage />;\n",
" }\n",
"\n",
" return (\n",
" <div className={styles.adminPage}>\n",
" {this.showLeftMenu() && (\n",
" <LeftMenu\n",
" plugins={this.retrievePlugins()}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" {this.props.adminPage.uuid ? <FullStory org=\"GK708\" /> : ''}\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "add",
"edit_start_line_idx": 200
}
|
/**
*
* AdminPage reducer
*
*/
import { fromJS, Map } from 'immutable';
import {
GET_ADMIN_DATA_SUCCEEDED,
} from './constants';
const initialState = fromJS({
allowGa: true,
currentEnvironment: 'development',
isLoading: true,
layout: Map({}),
strapiVersion: '3',
});
function adminPageReducer(state = initialState, action) {
switch (action.type) {
case GET_ADMIN_DATA_SUCCEEDED:
return state
.update('allowGa', () => action.data.allowGa)
.update('currentEnvironment', () => action.data.currentEnvironment)
.update('layout', () => Map(action.data.layout))
.update('strapiVersion', () => action.data.strapiVersion)
.update('isLoading', () => false);
default:
return state;
}
}
export default adminPageReducer;
|
packages/strapi-admin/admin/src/containers/AdminPage/reducer.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00046621187357231975,
0.00028816983103752136,
0.00016472645802423358,
0.00026087049627676606,
0.0001266539766220376
] |
{
"id": 3,
"code_window": [
" return <LoadingIndicatorPage />;\n",
" }\n",
"\n",
" return (\n",
" <div className={styles.adminPage}>\n",
" {this.showLeftMenu() && (\n",
" <LeftMenu\n",
" plugins={this.retrievePlugins()}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" {this.props.adminPage.uuid ? <FullStory org=\"GK708\" /> : ''}\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "add",
"edit_start_line_idx": 200
}
|
import { createSelector } from 'reselect';
/**
* Direct selector to the homePage state domain
*/
const selectHomePageDomain = () => state => state.get('homePage');
/**
* Default selector used by HomePage
*/
const selectHomePage = () => createSelector(
selectHomePageDomain(),
(substate) => substate.toJS(),
);
export default selectHomePage;
|
packages/strapi-generate-plugin/files/admin/src/containers/HomePage/selectors.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.000271610013442114,
0.0002213511907029897,
0.0001710923679638654,
0.0002213511907029897,
0.0000502588227391243
] |
{
"id": 3,
"code_window": [
" return <LoadingIndicatorPage />;\n",
" }\n",
"\n",
" return (\n",
" <div className={styles.adminPage}>\n",
" {this.showLeftMenu() && (\n",
" <LeftMenu\n",
" plugins={this.retrievePlugins()}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" {this.props.adminPage.uuid ? <FullStory org=\"GK708\" /> : ''}\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "add",
"edit_start_line_idx": 200
}
|
import { createSelector } from 'reselect';
/**
* Direct selector to the homePage state domain
*/
const selectHomePageDomain = () => (state) => state.get('homePage');
/**
* Other specific selectors
*/
/**
* Default selector used by HomePage
*/
const makeSelectHomePage = () => createSelector(
selectHomePageDomain(),
(substate) => substate.toJS(),
);
const makeSelectBody = () => createSelector(
selectHomePageDomain(),
(substate) => substate.get('body').toJS(),
);
export default makeSelectHomePage;
export {
makeSelectBody,
selectHomePageDomain,
};
|
packages/strapi-admin/admin/src/containers/HomePage/selectors.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017167284386232495,
0.0001680006826063618,
0.00016545008111279458,
0.00016743989544920623,
0.000002394643615843961
] |
{
"id": 3,
"code_window": [
" return <LoadingIndicatorPage />;\n",
" }\n",
"\n",
" return (\n",
" <div className={styles.adminPage}>\n",
" {this.showLeftMenu() && (\n",
" <LeftMenu\n",
" plugins={this.retrievePlugins()}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" {this.props.adminPage.uuid ? <FullStory org=\"GK708\" /> : ''}\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/index.js",
"type": "add",
"edit_start_line_idx": 200
}
|
{
"session": {
"enabled": true,
"client": "cookie",
"key": "strapi.sid",
"prefix": "strapi:sess:",
"secretKeys": ["mySecretKey1", "mySecretKey2"],
"httpOnly": true,
"maxAge": 86400000,
"overwrite": true,
"signed": false,
"rolling": false
},
"logger": {
"level": "info",
"exposeInContext": true,
"requests": false
},
"parser": {
"enabled": true,
"multipart": true
}
}
|
packages/strapi-generate-new/files/config/environments/staging/request.json
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017403064703103155,
0.00017313718853984028,
0.00017138545808847994,
0.00017399548960383981,
0.0000012387505421429523
] |
{
"id": 4,
"code_window": [
"import {\n",
" GET_ADMIN_DATA_SUCCEEDED,\n",
"} from './constants';\n",
"\n",
"const initialState = fromJS({\n",
" allowGa: true,\n",
" currentEnvironment: 'development',\n",
" isLoading: true,\n",
" layout: Map({}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" uuid: false,\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/reducer.js",
"type": "replace",
"edit_start_line_idx": 13
}
|
/**
*
* App.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router-dom';
import AdminPage from 'containers/AdminPage';
import NotFoundPage from 'containers/NotFoundPage';
import NotificationProvider from 'containers/NotificationProvider';
import AppLoader from 'containers/AppLoader';
import FullStory from 'components/FullStory';
import LoadingIndicatorPage from 'components/LoadingIndicatorPage';
import '../../styles/main.scss';
import styles from './styles.scss';
export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<FullStory org="GK708" />
<NotificationProvider />
<AppLoader>
{({ shouldLoad }) => {
if (shouldLoad) {
return <LoadingIndicatorPage />;
}
return (
<div className={styles.container}>
<Switch>
<Route path="/" component={AdminPage} />
<Route path="" component={NotFoundPage} />
</Switch>
</div>
);
}}
</AppLoader>
</div>
);
}
}
App.contextTypes = {
router: PropTypes.object.isRequired,
};
App.propTypes = {};
export default App;
|
packages/strapi-admin/admin/src/containers/App/index.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017387075058650225,
0.0001700503780739382,
0.00016350117221008986,
0.00017050188034772873,
0.000003267883585067466
] |
{
"id": 4,
"code_window": [
"import {\n",
" GET_ADMIN_DATA_SUCCEEDED,\n",
"} from './constants';\n",
"\n",
"const initialState = fromJS({\n",
" allowGa: true,\n",
" currentEnvironment: 'development',\n",
" isLoading: true,\n",
" layout: Map({}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" uuid: false,\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/reducer.js",
"type": "replace",
"edit_start_line_idx": 13
}
|
// import { LOCATION_CHANGE } from 'react-router-redux';
// import { takeLatest, put, fork, take, cancel } from 'redux-saga/effects';
// Individual exports for testing
export function* defaultSaga() {
}
// All sagas to be loaded
export default defaultSaga;
|
packages/strapi-generate-plugin/files/admin/src/containers/HomePage/saga.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00016873236745595932,
0.00016873236745595932,
0.00016873236745595932,
0.00016873236745595932,
0
] |
{
"id": 4,
"code_window": [
"import {\n",
" GET_ADMIN_DATA_SUCCEEDED,\n",
"} from './constants';\n",
"\n",
"const initialState = fromJS({\n",
" allowGa: true,\n",
" currentEnvironment: 'development',\n",
" isLoading: true,\n",
" layout: Map({}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" uuid: false,\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/reducer.js",
"type": "replace",
"edit_start_line_idx": 13
}
|
{
"connection": "<%= connection %>",
"collectionName": "<%= collectionName || idPluralized %>",
"info": {
"name": "<%= id %>",
"description": "<%= description %>"
},
"options": {
"increments": true,
"timestamps": true,
"comment": ""
},
"attributes": {
<%= attributes %>
}
}
|
packages/strapi-generate-api/templates/bookshelf/model.settings.template
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017438728536944836,
0.00017356725584249943,
0.0001727472263155505,
0.00017356725584249943,
8.200295269489288e-7
] |
{
"id": 4,
"code_window": [
"import {\n",
" GET_ADMIN_DATA_SUCCEEDED,\n",
"} from './constants';\n",
"\n",
"const initialState = fromJS({\n",
" allowGa: true,\n",
" currentEnvironment: 'development',\n",
" isLoading: true,\n",
" layout: Map({}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" uuid: false,\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/reducer.js",
"type": "replace",
"edit_start_line_idx": 13
}
|
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
.tmp
*.log
*.sql
*.sqlite
*.sqlite3
############################
# Misc.
############################
*#
ssl
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
############################
# Tests
############################
testApp
coverage
############################
# Front-end workflow
############################
bower_components
############################
# Production config
############################
**/production/
|
packages/strapi-generate-new/templates/npmignore
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017203875177074224,
0.00016902854258660227,
0.00016555030015297234,
0.0001685496245045215,
0.000001976108251255937
] |
{
"id": 5,
"code_window": [
"\n",
"function adminPageReducer(state = initialState, action) {\n",
" switch (action.type) {\n",
" case GET_ADMIN_DATA_SUCCEEDED:\n",
" return state\n",
" .update('allowGa', () => action.data.allowGa)\n",
" .update('currentEnvironment', () => action.data.currentEnvironment)\n",
" .update('layout', () => Map(action.data.layout))\n",
" .update('strapiVersion', () => action.data.strapiVersion)\n",
" .update('isLoading', () => false);\n",
" default:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .update('uuid', () => action.data.uuid)\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/reducer.js",
"type": "replace",
"edit_start_line_idx": 24
}
|
/*
* AdminPage
*
* This is the first thing users see of our AdminPage, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import ReactGA from 'react-ga';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { Switch, Route } from 'react-router-dom';
import { get, includes, isFunction, map, omit } from 'lodash';
import { bindActionCreators, compose } from 'redux';
// Actions required for disabling and enabling the OverlayBlocker
import { disableGlobalOverlayBlocker, enableGlobalOverlayBlocker } from 'actions/overlayBlocker';
import { pluginLoaded, updatePlugin } from 'containers/App/actions';
import {
makeSelectAppPlugins,
makeSelectBlockApp,
makeSelectIsAppLoading,
makeSelectShowGlobalAppBlocker,
selectHasUserPlugin,
selectPlugins,
} from 'containers/App/selectors';
// Design
import ComingSoonPage from 'containers/ComingSoonPage';
import Content from 'containers/Content';
import LocaleToggle from 'containers/LocaleToggle';
import CTAWrapper from 'components/CtaWrapper';
import Header from 'components/Header/index';
import HomePage from 'containers/HomePage/Loadable';
import InstallPluginPage from 'containers/InstallPluginPage/Loadable';
import LeftMenu from 'containers/LeftMenu';
import ListPluginsPage from 'containers/ListPluginsPage/Loadable';
import LoadingIndicatorPage from 'components/LoadingIndicatorPage';
import Logout from 'components/Logout';
import NotFoundPage from 'containers/NotFoundPage/Loadable';
import OverlayBlocker from 'components/OverlayBlocker';
import PluginPage from 'containers/PluginPage';
// Utils
import auth from 'utils/auth';
import injectReducer from 'utils/injectReducer';
import injectSaga from 'utils/injectSaga';
import { getAdminData } from './actions';
import reducer from './reducer';
import saga from './saga';
import selectAdminPage from './selectors';
import styles from './styles.scss';
const PLUGINS_TO_BLOCK_PRODUCTION = ['content-type-builder', 'settings-manager'];
export class AdminPage extends React.Component {
// eslint-disable-line react/prefer-stateless-function
state = { hasAlreadyRegistereOtherPlugins: false };
getChildContext = () => ({
disableGlobalOverlayBlocker: this.props.disableGlobalOverlayBlocker,
enableGlobalOverlayBlocker: this.props.enableGlobalOverlayBlocker,
plugins: this.props.plugins,
updatePlugin: this.props.updatePlugin,
});
componentDidMount() {
this.props.getAdminData();
this.checkLogin(this.props);
ReactGA.initialize('UA-54313258-9');
}
componentDidUpdate(prevProps) {
const { adminPage: { allowGa }, location: { pathname }, plugins } = this.props;
if (prevProps.location.pathname !== pathname) {
this.checkLogin(this.props);
if (allowGa) {
ReactGA.pageview(pathname);
}
}
const hasAdminPath = ['users-permissions', 'hasAdminUser'];
if (get(prevProps.plugins.toJS(), hasAdminPath) !== get(plugins.toJS(), hasAdminPath)) {
this.checkLogin(this.props, true);
}
if (!this.hasUserPluginLoaded(prevProps) && this.hasUserPluginLoaded(this.props)) {
this.checkLogin(this.props);
}
}
checkLogin = (props, skipAction = false) => {
if (props.hasUserPlugin && this.isUrlProtected(props) && !auth.getToken()) {
if (!this.hasUserPluginLoaded(props)) {
return;
}
const endPoint = this.hasAdminUser(props) ? 'login' : 'register';
this.props.history.push(`/plugins/users-permissions/auth/${endPoint}`);
}
if (
!this.isUrlProtected(props) &&
includes(props.location.pathname, 'auth/register') &&
this.hasAdminUser(props) &&
!skipAction
) {
this.props.history.push('/plugins/users-permissions/auth/login');
}
if (
props.hasUserPlugin &&
!this.isUrlProtected(props) &&
!includes(props.location.pathname, 'auth/register') &&
!this.hasAdminUser(props)
) {
this.props.history.push('/plugins/users-permissions/auth/register');
}
if (!props.hasUserPlugin || (auth.getToken() && !this.state.hasAlreadyRegistereOtherPlugins)) {
map(omit(this.props.plugins.toJS(), ['users-permissions', 'email']), plugin => {
switch (true) {
case isFunction(plugin.bootstrap) && isFunction(plugin.pluginRequirements):
plugin
.pluginRequirements(plugin)
.then(plugin => {
return plugin.bootstrap(plugin);
})
.then(plugin => this.props.pluginLoaded(plugin));
break;
case isFunction(plugin.pluginRequirements):
plugin.pluginRequirements(plugin).then(plugin => this.props.pluginLoaded(plugin));
break;
case isFunction(plugin.bootstrap):
plugin.bootstrap(plugin).then(plugin => this.props.pluginLoaded(plugin));
break;
default:
}
});
this.setState({ hasAlreadyRegistereOtherPlugins: true });
}
};
hasUserPluginInstalled = () => {
const { appPlugins } = this.props;
return appPlugins.indexOf('users-permissions') !== -1;
}
hasUserPluginLoaded = props =>
typeof get(props.plugins.toJS(), ['users-permissions', 'hasAdminUser']) !== 'undefined';
hasAdminUser = props => get(props.plugins.toJS(), ['users-permissions', 'hasAdminUser']);
isUrlProtected = props =>
!includes(props.location.pathname, get(props.plugins.toJS(), ['users-permissions', 'nonProtectedUrl']));
shouldDisplayLogout = () => auth.getToken() && this.props.hasUserPlugin && this.isUrlProtected(this.props);
showLeftMenu = () => !includes(this.props.location.pathname, 'users-permissions/auth/');
showLoading = () => {
const { isAppLoading, adminPage: { isLoading } } = this.props;
return isAppLoading || isLoading || (this.hasUserPluginInstalled() && !this.hasUserPluginLoaded(this.props));
}
retrievePlugins = () => {
const {
adminPage: { currentEnvironment },
plugins,
} = this.props;
if (currentEnvironment === 'production') {
let pluginsToDisplay = plugins;
PLUGINS_TO_BLOCK_PRODUCTION.map(plugin => (pluginsToDisplay = pluginsToDisplay.delete(plugin)));
return pluginsToDisplay;
}
return plugins;
};
render() {
const { adminPage } = this.props;
const header = this.showLeftMenu() ? <Header /> : '';
const style = this.showLeftMenu() ? {} : { width: '100%' };
if (this.showLoading()) {
return <LoadingIndicatorPage />;
}
return (
<div className={styles.adminPage}>
{this.showLeftMenu() && (
<LeftMenu
plugins={this.retrievePlugins()}
layout={adminPage.layout}
version={adminPage.strapiVersion}
/>
)}
<CTAWrapper>
{this.shouldDisplayLogout() && <Logout />}
<LocaleToggle isLogged={this.shouldDisplayLogout() === true} />
</CTAWrapper>
<div className={styles.adminPageRightWrapper} style={style}>
{header}
<Content {...this.props} showLeftMenu={this.showLeftMenu()}>
<Switch>
<Route path="/" component={HomePage} exact />
<Route path="/plugins/:pluginId" component={PluginPage} />
<Route path="/plugins" component={ComingSoonPage} />
<Route path="/list-plugins" component={ListPluginsPage} exact />
<Route path="/install-plugin" component={InstallPluginPage} exact />
<Route path="/configuration" component={ComingSoonPage} exact />
<Route path="" component={NotFoundPage} />
<Route path="404" component={NotFoundPage} />
</Switch>
</Content>
</div>
<OverlayBlocker isOpen={this.props.blockApp && this.props.showGlobalAppBlocker} />
</div>
);
}
}
AdminPage.childContextTypes = {
disableGlobalOverlayBlocker: PropTypes.func,
enableGlobalOverlayBlocker: PropTypes.func,
plugins: PropTypes.object,
updatePlugin: PropTypes.func,
};
AdminPage.contextTypes = {
router: PropTypes.object.isRequired,
};
AdminPage.defaultProps = {
adminPage: {},
appPlugins: [],
hasUserPlugin: true,
isAppLoading: true,
};
AdminPage.propTypes = {
adminPage: PropTypes.object,
appPlugins: PropTypes.array,
blockApp: PropTypes.bool.isRequired,
disableGlobalOverlayBlocker: PropTypes.func.isRequired,
enableGlobalOverlayBlocker: PropTypes.func.isRequired,
hasUserPlugin: PropTypes.bool,
history: PropTypes.object.isRequired,
isAppLoading: PropTypes.bool,
location: PropTypes.object.isRequired,
pluginLoaded: PropTypes.func.isRequired,
plugins: PropTypes.object.isRequired,
showGlobalAppBlocker: PropTypes.bool.isRequired,
updatePlugin: PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
adminPage: selectAdminPage(),
appPlugins: makeSelectAppPlugins(),
blockApp: makeSelectBlockApp(),
hasUserPlugin: selectHasUserPlugin(),
isAppLoading: makeSelectIsAppLoading(),
plugins: selectPlugins(),
showGlobalAppBlocker: makeSelectShowGlobalAppBlocker(),
});
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
disableGlobalOverlayBlocker,
enableGlobalOverlayBlocker,
getAdminData,
pluginLoaded,
updatePlugin,
},
dispatch,
);
}
const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({ key: 'adminPage', reducer });
const withSaga = injectSaga({ key: 'adminPage', saga });
export default compose(withReducer, withSaga, withConnect)(AdminPage);
|
packages/strapi-admin/admin/src/containers/AdminPage/index.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.955091655254364,
0.034741222858428955,
0.0001656949461903423,
0.00019801777671091259,
0.1710464358329773
] |
{
"id": 5,
"code_window": [
"\n",
"function adminPageReducer(state = initialState, action) {\n",
" switch (action.type) {\n",
" case GET_ADMIN_DATA_SUCCEEDED:\n",
" return state\n",
" .update('allowGa', () => action.data.allowGa)\n",
" .update('currentEnvironment', () => action.data.currentEnvironment)\n",
" .update('layout', () => Map(action.data.layout))\n",
" .update('strapiVersion', () => action.data.strapiVersion)\n",
" .update('isLoading', () => false);\n",
" default:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .update('uuid', () => action.data.uuid)\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/reducer.js",
"type": "replace",
"edit_start_line_idx": 24
}
|
.container {
padding-top: 18px;
}
.containerFluid {
padding: 18px 30px;
> div:first-child {
max-height: 33px;
}
}
.form {
padding-top: 2rem;
}
.main_wrapper{
background: #ffffff;
padding: 22px 28px 0px;
border-radius: 2px;
box-shadow: 0 2px 4px #E3E9F3;
}
.separator {
margin-top: 15px;
border-top: 1px solid #F6F6F6;
}
.titleContainer {
font-size: 18px;
font-weight: bold;
line-height: 18px;
}
.loaderWrapper {
display: flex;
flex-direction: column;
justify-content: center;
min-height: 260px;
margin: auto;
}
|
packages/strapi-plugin-users-permissions/admin/src/containers/EditPage/styles.scss
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017068600573111326,
0.00017015037883538753,
0.0001695686369203031,
0.0001703645393718034,
4.232944377235981e-7
] |
{
"id": 5,
"code_window": [
"\n",
"function adminPageReducer(state = initialState, action) {\n",
" switch (action.type) {\n",
" case GET_ADMIN_DATA_SUCCEEDED:\n",
" return state\n",
" .update('allowGa', () => action.data.allowGa)\n",
" .update('currentEnvironment', () => action.data.currentEnvironment)\n",
" .update('layout', () => Map(action.data.layout))\n",
" .update('strapiVersion', () => action.data.strapiVersion)\n",
" .update('isLoading', () => false);\n",
" default:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .update('uuid', () => action.data.uuid)\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/reducer.js",
"type": "replace",
"edit_start_line_idx": 24
}
|
{
"components.DownloadDb.download": "Installation en cours...",
"components.DownloadDb.text": "Cela peut prendre plusieurs minutes. Merci de patienter.",
"form.advanced.description": "Modification des configurations avancé.",
"form.advanced.item.admin": "Url du panel d'administration",
"form.advanced.item.prefix": "Prefix de l'API",
"form.advanced.name": "Avancé",
"form.application.description": "Modification des configurations de l'application.",
"form.application.item.description": "Description",
"form.application.item.name": "Nom",
"form.application.item.version": "Version",
"form.application.name": "Application",
"form.button.cancel": "Annuler",
"form.button.confirm": "Confimer",
"form.button.save": "Sauvegarder",
"form.database.item.authenticationDatabase": "Base de données d'authentification",
"form.database.item.client": "Client",
"form.database.item.connector": "Connecteur",
"form.database.item.database": "Base de données",
"form.database.item.default": "Définir comme connexion par défaut",
"form.database.item.host": "Hôte",
"form.database.item.name": "Nom de la Connexion",
"form.database.item.password": "Mot de Passe",
"form.database.item.port": "Port",
"form.database.item.provider.mongo": "Mongo",
"form.database.item.provider.mysql": "MySQL",
"form.database.item.provider.postgres": "PostgresSQL",
"form.database.item.provider.redis": "Redis",
"form.database.item.ssl": "SSL",
"form.database.item.username": "Surnom",
"form.databases.description": "Modification des configurations de bases de données par environnement.",
"form.databases.name": "Bases de données",
"form.language.choose": "Choisissez un langage",
"form.language.description": "Modification des langages.",
"form.language.name": "Langages",
"form.request.description": "Configuration des requêtes.",
"form.request.item.logger": "Logger",
"form.request.item.logger.exposeInContext": "Exposer dans le contexte",
"form.request.item.logger.level": "Niveau",
"form.request.item.logger.requests": "Requêtes",
"form.request.item.parser": "Parser",
"form.request.item.parser.multipart": "Parser Multipart",
"form.request.item.prefix": "Préfix",
"form.request.item.prefix.prefix": "Préfix",
"form.request.item.router": "Router",
"form.request.item.router.prefix": "Préfixe",
"form.request.name": "Requête",
"form.response.description": "Configuration des réponses.",
"form.response.item.gzip.enabled": "Gzip",
"form.response.item.responseTime.enabled": "Temps de réponse",
"form.response.name": "Réponse",
"form.security.description": "Configurations de sécurité.",
"form.security.item.cors": "Cors",
"form.security.item.cors.origin": "Origine",
"form.security.item.csrf": "CSRF",
"form.security.item.csrf.angular": "Angular",
"form.security.item.csrf.cookie": "Cookie",
"form.security.item.csrf.key": "Clé",
"form.security.item.csrf.secret": "Clé secrète",
"form.security.item.hsts": "HOSTS",
"form.security.item.hsts.includeSubDomains": "Inclure les sous-domaines",
"form.security.item.hsts.maxAge": "Max Age",
"form.security.item.hsts.preload": "Preload",
"form.security.item.p3p": "P3P",
"form.security.item.p3p.value": "Valeur",
"form.security.item.session": "Session",
"form.security.item.session.key": "Clé secrète",
"form.security.item.session.maxAge": "Durée de vie ",
"form.security.item.xframe": "Xframe",
"form.security.item.xframe.allow-from": "ALLOW-FROM",
"form.security.item.xframe.deny": "DENY",
"form.security.item.xframe.sameorigin": "SAMEORIGIN",
"form.security.item.xframe.value": "Options",
"form.security.item.xssProtection": "Protection xss",
"form.security.item.xssProtection.mode": "Mode",
"form.security.name": "Sécurité",
"form.server.description": "Modification des configurations serveur",
"form.server.item.cron": "Cron",
"form.server.item.host": "Host",
"form.server.item.port": "Port",
"form.server.item.proxy": "Paramètres du Proxy",
"form.server.item.proxy.enable": "Activer le Proxy",
"form.server.item.proxy.host": "Proxy Host",
"form.server.item.proxy.port": "Proxy Port",
"form.server.item.proxy.ssl": "Proxy SSL",
"form.server.name": "Serveur",
"language.af": "Afrikaans",
"language.af_NA": "Afrikaans (Namibië)",
"language.af_ZA": "Afrikaans (Suid-Afrika)",
"language.agq": "Aghem",
"language.agq_CM": "Aghem (Kàmàlûŋ)",
"language.ak": "Akan",
"language.ak_GH": "Akan (Gaana)",
"language.am": "አማርኛ",
"language.am_ET": "አማርኛ (ኢትዮጵያ)",
"language.ar": "العربية",
"language.ar_001": "العربية (العالم)",
"language.ar_AE": "العربية (الإمارات العربية المتحدة)",
"language.ar_BH": "العربية (البحرين)",
"language.ar_DZ": "العربية (الجزائر)",
"language.ar_EG": "العربية (مصر)",
"language.ar_IQ": "العربية (العراق)",
"language.ar_JO": "العربية (الأردن)",
"language.ar_KW": "العربية (الكويت)",
"language.ar_LB": "العربية (لبنان)",
"language.ar_LY": "العربية (ليبيا)",
"language.ar_MA": "العربية (المغرب)",
"language.ar_OM": "العربية (عُمان)",
"language.ar_QA": "العربية (قطر)",
"language.ar_SA": "العربية (المملكة العربية السعودية)",
"language.ar_SD": "العربية (السودان)",
"language.ar_SY": "العربية (سوريا)",
"language.ar_TN": "العربية (تونس)",
"language.ar_YE": "العربية (اليمن)",
"language.as": "অসমীয়া",
"language.as_IN": "অসমীয়া (ভাৰত)",
"language.asa": "Kipare",
"language.asa_TZ": "Kipare (Tadhania)",
"language.az": "azərbaycanca",
"language.az_Cyrl": "Азәрбајҹан (kiril)",
"language.az_Cyrl_AZ": "Азәрбајҹан (kiril, Азәрбајҹан)",
"language.az_Latn": "azərbaycanca (latın)",
"language.az_Latn_AZ": "azərbaycanca (latın, Azərbaycan)",
"language.bas": "Ɓàsàa",
"language.bas_CM": "Ɓàsàa (Kàmɛ̀rûn)",
"language.be": "беларуская",
"language.be_BY": "беларуская (Беларусь)",
"language.bem": "Ichibemba",
"language.bem_ZM": "Ichibemba (Zambia)",
"language.bez": "Hibena",
"language.bez_TZ": "Hibena (Hutanzania)",
"language.bg": "български",
"language.bg_BG": "български (България)",
"language.bm": "bamanakan",
"language.bm_ML": "bamanakan (Mali)",
"language.bn": "বাংলা",
"language.bn_BD": "বাংলা (বাংলাদেশ)",
"language.bn_IN": "বাংলা (ভারত)",
"language.bo": "པོད་སྐད་",
"language.bo_CN": "པོད་སྐད་ (རྒྱ་ནག)",
"language.bo_IN": "པོད་སྐད་ (རྒྱ་གར་)",
"language.br": "brezhoneg",
"language.br_FR": "brezhoneg (Frañs)",
"language.brx": "बड़ो",
"language.brx_IN": "बड़ो (भारत)",
"language.bs": "bosanski",
"language.bs_BA": "bosanski (Bosna i Hercegovina)",
"language.ca": "català",
"language.ca_ES": "català (Espanya)",
"language.cgg": "Rukiga",
"language.cgg_UG": "Rukiga (Uganda)",
"language.chr": "ᏣᎳᎩ",
"language.chr_US": "ᏣᎳᎩ (ᎠᎹᏰᏟ)",
"language.cs": "čeština",
"language.cs_CZ": "čeština (Česká republika)",
"language.cy": "Cymraeg",
"language.cy_GB": "Cymraeg (Prydain Fawr)",
"language.da": "dansk",
"language.da_DK": "dansk (Danmark)",
"language.dav": "Kitaita",
"language.dav_KE": "Kitaita (Kenya)",
"language.de": "Deutsch",
"language.de_AT": "Deutsch (Österreich)",
"language.de_BE": "Deutsch (Belgien)",
"language.de_CH": "Deutsch (Schweiz)",
"language.de_DE": "Deutsch (Deutschland)",
"language.de_LI": "Deutsch (Liechtenstein)",
"language.de_LU": "Deutsch (Luxemburg)",
"language.dje": "Zarmaciine",
"language.dje_NE": "Zarmaciine (Nižer)",
"language.dua": "duálá",
"language.dua_CM": "duálá (Cameroun)",
"language.dyo": "joola",
"language.dyo_SN": "joola (Senegal)",
"language.ebu": "Kĩembu",
"language.ebu_KE": "Kĩembu (Kenya)",
"language.ee": "eʋegbe",
"language.ee_GH": "eʋegbe (Ghana nutome)",
"language.ee_TG": "eʋegbe (Togo nutome)",
"language.el": "Ελληνικά",
"language.el_CY": "Ελληνικά (Κύπρος)",
"language.el_GR": "Ελληνικά (Ελλάδα)",
"language.en": "English",
"language.en_AS": "English (American Samoa)",
"language.en_AU": "English (Australia)",
"language.en_BB": "English (Barbados)",
"language.en_BE": "English (Belgium)",
"language.en_BM": "English (Bermuda)",
"language.en_BW": "English (Botswana)",
"language.en_BZ": "English (Belize)",
"language.en_CA": "English (Canada)",
"language.en_GB": "English (United Kingdom)",
"language.en_GU": "English (Guam)",
"language.en_GY": "English (Guyana)",
"language.en_HK": "English (Hong Kong SAR China)",
"language.en_IE": "English (Ireland)",
"language.en_IN": "English (India)",
"language.en_JM": "English (Jamaica)",
"language.en_MH": "English (Marshall Islands)",
"language.en_MP": "English (Northern Mariana Islands)",
"language.en_MT": "English (Malta)",
"language.en_MU": "English (Mauritius)",
"language.en_NA": "English (Namibia)",
"language.en_NZ": "English (New Zealand)",
"language.en_PH": "English (Philippines)",
"language.en_PK": "English (Pakistan)",
"language.en_SG": "English (Singapore)",
"language.en_TT": "English (Trinidad and Tobago)",
"language.en_UM": "English (U.S. Minor Outlying Islands)",
"language.en_US": "English (United States)",
"language.en_US_POSIX": "English (United States, Computer)",
"language.en_VI": "English (U.S. Virgin Islands)",
"language.en_ZA": "English (South Africa)",
"language.en_ZW": "English (Zimbabwe)",
"language.eo": "esperanto",
"language.es": "español",
"language.es_419": "español (Latinoamérica)",
"language.es_AR": "español (Argentina)",
"language.es_BO": "español (Bolivia)",
"language.es_CL": "español (Chile)",
"language.es_CO": "español (Colombia)",
"language.es_CR": "español (Costa Rica)",
"language.es_DO": "español (República Dominicana)",
"language.es_EC": "español (Ecuador)",
"language.es_ES": "español (España)",
"language.es_GQ": "español (Guinea Ecuatorial)",
"language.es_GT": "español (Guatemala)",
"language.es_HN": "español (Honduras)",
"language.es_MX": "español (México)",
"language.es_NI": "español (Nicaragua)",
"language.es_PA": "español (Panamá)",
"language.es_PE": "español (Perú)",
"language.es_PR": "español (Puerto Rico)",
"language.es_PY": "español (Paraguay)",
"language.es_SV": "español (El Salvador)",
"language.es_US": "español (Estados Unidos)",
"language.es_UY": "español (Uruguay)",
"language.es_VE": "español (Venezuela)",
"language.et": "eesti",
"language.et_EE": "eesti (Eesti)",
"language.eu": "euskara",
"language.eu_ES": "euskara (Espainia)",
"language.ewo": "ewondo",
"language.ewo_CM": "ewondo (Kamǝrún)",
"language.fa": "فارسی",
"language.fa_AF": "دری (افغانستان)",
"language.fa_IR": "فارسی (ایران)",
"language.ff": "Pulaar",
"language.ff_SN": "Pulaar (Senegaal)",
"language.fi": "suomi",
"language.fi_FI": "suomi (Suomi)",
"language.fil": "Filipino",
"language.fil_PH": "Filipino (Pilipinas)",
"language.fo": "føroyskt",
"language.fo_FO": "føroyskt (Føroyar)",
"language.fr": "français",
"language.fr_BE": "français (Belgique)",
"language.fr_BF": "français (Burkina Faso)",
"language.fr_BI": "français (Burundi)",
"language.fr_BJ": "français (Bénin)",
"language.fr_BL": "français (Saint-Barthélémy)",
"language.fr_CA": "français (Canada)",
"language.fr_CD": "français (République démocratique du Congo)",
"language.fr_CF": "français (République centrafricaine)",
"language.fr_CG": "français (Congo-Brazzaville)",
"language.fr_CH": "français (Suisse)",
"language.fr_CI": "français (Côte d’Ivoire)",
"language.fr_CM": "français (Cameroun)",
"language.fr_DJ": "français (Djibouti)",
"language.fr_FR": "français (France)",
"language.fr_GA": "français (Gabon)",
"language.fr_GF": "français (Guyane française)",
"language.fr_GN": "français (Guinée)",
"language.fr_GP": "français (Guadeloupe)",
"language.fr_GQ": "français (Guinée équatoriale)",
"language.fr_KM": "français (Comores)",
"language.fr_LU": "français (Luxembourg)",
"language.fr_MC": "français (Monaco)",
"language.fr_MF": "français (Saint-Martin)",
"language.fr_MG": "français (Madagascar)",
"language.fr_ML": "français (Mali)",
"language.fr_MQ": "français (Martinique)",
"language.fr_NE": "français (Niger)",
"language.fr_RE": "français (Réunion)",
"language.fr_RW": "français (Rwanda)",
"language.fr_SN": "français (Sénégal)",
"language.fr_TD": "français (Tchad)",
"language.fr_TG": "français (Togo)",
"language.fr_YT": "français (Mayotte)",
"language.ga": "Gaeilge",
"language.ga_IE": "Gaeilge (Éire)",
"language.gl": "galego",
"language.gl_ES": "galego (España)",
"language.gsw": "Schwiizertüütsch",
"language.gsw_CH": "Schwiizertüütsch (Schwiiz)",
"language.gu": "ગુજરાતી",
"language.gu_IN": "ગુજરાતી (ભારત)",
"language.guz": "Ekegusii",
"language.guz_KE": "Ekegusii (Kenya)",
"language.gv": "Gaelg",
"language.gv_GB": "Gaelg (Rywvaneth Unys)",
"language.ha": "Hausa",
"language.ha_Latn": "Hausa (Latn)",
"language.ha_Latn_GH": "Hausa (Latn, Gana)",
"language.ha_Latn_NE": "Hausa (Latn, Nijar)",
"language.ha_Latn_NG": "Hausa (Latn, Najeriya)",
"language.haw": "ʻŌlelo Hawaiʻi",
"language.haw_US": "ʻŌlelo Hawaiʻi (ʻAmelika Hui Pū ʻIa)",
"language.he": "עברית",
"language.he_IL": "עברית (ישראל)",
"language.hi": "हिन्दी",
"language.hi_IN": "हिन्दी (भारत)",
"language.hr": "hrvatski",
"language.hr_HR": "hrvatski (Hrvatska)",
"language.hu": "magyar",
"language.hu_HU": "magyar (Magyarország)",
"language.hy": "Հայերէն",
"language.hy_AM": "Հայերէն (Հայաստանի Հանրապետութիւն)",
"language.id": "Bahasa Indonesia",
"language.id_ID": "Bahasa Indonesia (Indonesia)",
"language.ig": "Igbo",
"language.ig_NG": "Igbo (Nigeria)",
"language.ii": "ꆈꌠꉙ",
"language.ii_CN": "ꆈꌠꉙ (ꍏꇩ)",
"language.is": "íslenska",
"language.is_IS": "íslenska (Ísland)",
"language.it": "italiano",
"language.it_CH": "italiano (Svizzera)",
"language.it_IT": "italiano (Italia)",
"language.ja": "日本語",
"language.ja_JP": "日本語(日本)",
"language.jmc": "Kimachame",
"language.jmc_TZ": "Kimachame (Tanzania)",
"language.ka": "ქართული",
"language.ka_GE": "ქართული (საქართველო)",
"language.kab": "Taqbaylit",
"language.kab_DZ": "Taqbaylit (Lezzayer)",
"language.kam": "Kikamba",
"language.kam_KE": "Kikamba (Kenya)",
"language.kde": "Chimakonde",
"language.kde_TZ": "Chimakonde (Tanzania)",
"language.kea": "kabuverdianu",
"language.kea_CV": "kabuverdianu (Kabu Verdi)",
"language.khq": "Koyra ciini",
"language.khq_ML": "Koyra ciini (Maali)",
"language.ki": "Gikuyu",
"language.ki_KE": "Gikuyu (Kenya)",
"language.kk": "қазақ тілі",
"language.kk_Cyrl": "қазақ тілі (кириллица)",
"language.kk_Cyrl_KZ": "қазақ тілі (кириллица, Қазақстан)",
"language.kl": "kalaallisut",
"language.kl_GL": "kalaallisut (Kalaallit Nunaat)",
"language.kln": "Kalenjin",
"language.kln_KE": "Kalenjin (Emetab Kenya)",
"language.km": "ភាសាខ្មែរ",
"language.km_KH": "ភាសាខ្មែរ (កម្ពុជា)",
"language.kn": "ಕನ್ನಡ",
"language.kn_IN": "ಕನ್ನಡ (ಭಾರತ)",
"language.ko": "한국어",
"language.ko_KR": "한국어(대한민국)",
"language.kok": "कोंकणी",
"language.kok_IN": "कोंकणी (भारत)",
"language.ksb": "Kishambaa",
"language.ksb_TZ": "Kishambaa (Tanzania)",
"language.ksf": "rikpa",
"language.ksf_CM": "rikpa (kamɛrún)",
"language.kw": "kernewek",
"language.kw_GB": "kernewek (Rywvaneth Unys)",
"language.lag": "Kɨlaangi",
"language.lag_TZ": "Kɨlaangi (Taansanía)",
"language.lg": "Luganda",
"language.lg_UG": "Luganda (Yuganda)",
"language.ln": "lingála",
"language.ln_CD": "lingála (Repibiki demokratiki ya Kongó)",
"language.ln_CG": "lingála (Kongo)",
"language.lt": "lietuvių",
"language.lt_LT": "lietuvių (Lietuva)",
"language.lu": "Tshiluba",
"language.lu_CD": "Tshiluba (Ditunga wa Kongu)",
"language.luo": "Dholuo",
"language.luo_KE": "Dholuo (Kenya)",
"language.luy": "Luluhia",
"language.luy_KE": "Luluhia (Kenya)",
"language.lv": "latviešu",
"language.lv_LV": "latviešu (Latvija)",
"language.mas": "Maa",
"language.mas_KE": "Maa (Kenya)",
"language.mas_TZ": "Maa (Tansania)",
"language.mer": "Kĩmĩrũ",
"language.mer_KE": "Kĩmĩrũ (Kenya)",
"language.mfe": "kreol morisien",
"language.mfe_MU": "kreol morisien (Moris)",
"language.mg": "Malagasy",
"language.mg_MG": "Malagasy (Madagasikara)",
"language.mgh": "Makua",
"language.mgh_MZ": "Makua (Umozambiki)",
"language.mk": "македонски",
"language.mk_MK": "македонски (Македонија)",
"language.ml": "മലയാളം",
"language.ml_IN": "മലയാളം (ഇന്ത്യ)",
"language.mr": "मराठी",
"language.mr_IN": "मराठी (भारत)",
"language.ms": "Bahasa Melayu",
"language.ms_BN": "Bahasa Melayu (Brunei)",
"language.ms_MY": "Bahasa Melayu (Malaysia)",
"language.mt": "Malti",
"language.mt_MT": "Malti (Malta)",
"language.mua": "MUNDAŊ",
"language.mua_CM": "MUNDAŊ (kameruŋ)",
"language.my": "ဗမာ",
"language.my_MM": "ဗမာ (မြန်မာ)",
"language.naq": "Khoekhoegowab",
"language.naq_NA": "Khoekhoegowab (Namibiab)",
"language.nb": "norsk bokmål",
"language.nb_NO": "norsk bokmål (Norge)",
"language.nd": "isiNdebele",
"language.nd_ZW": "isiNdebele (Zimbabwe)",
"language.ne": "नेपाली",
"language.ne_IN": "नेपाली (भारत)",
"language.ne_NP": "नेपाली (नेपाल)",
"language.nl": "Nederlands",
"language.nl_AW": "Nederlands (Aruba)",
"language.nl_BE": "Nederlands (België)",
"language.nl_CW": "Nederlands (Curaçao)",
"language.nl_NL": "Nederlands (Nederland)",
"language.nl_SX": "Nederlands (Sint Maarten)",
"language.nmg": "nmg",
"language.nmg_CM": "nmg (Kamerun)",
"language.nn": "nynorsk",
"language.nn_NO": "nynorsk (Noreg)",
"language.nus": "Thok Nath",
"language.nus_SD": "Thok Nath (Sudan)",
"language.nyn": "Runyankore",
"language.nyn_UG": "Runyankore (Uganda)",
"language.om": "Oromoo",
"language.om_ET": "Oromoo (Itoophiyaa)",
"language.om_KE": "Oromoo (Keeniyaa)",
"language.or": "ଓଡ଼ିଆ",
"language.or_IN": "ଓଡ଼ିଆ (ଭାରତ)",
"language.pa": "ਪੰਜਾਬੀ",
"language.pa_Arab": "پنجاب (العربية)",
"language.pa_Arab_PK": "پنجاب (العربية, پکستان)",
"language.pa_Guru": "ਪੰਜਾਬੀ (Guru)",
"language.pa_Guru_IN": "ਪੰਜਾਬੀ (Guru, ਭਾਰਤ)",
"language.pl": "polski",
"language.pl_PL": "polski (Polska)",
"language.ps": "پښتو",
"language.ps_AF": "پښتو (افغانستان)",
"language.pt": "português",
"language.pt_AO": "português (Angola)",
"language.pt_BR": "português (Brasil)",
"language.pt_GW": "português (Guiné Bissau)",
"language.pt_MZ": "português (Moçambique)",
"language.pt_PT": "português (Portugal)",
"language.pt_ST": "português (São Tomé e Príncipe)",
"language.rm": "rumantsch",
"language.rm_CH": "rumantsch (Svizra)",
"language.rn": "Ikirundi",
"language.rn_BI": "Ikirundi (Uburundi)",
"language.ro": "română",
"language.ro_MD": "română (Republica Moldova)",
"language.ro_RO": "română (România)",
"language.rof": "Kihorombo",
"language.rof_TZ": "Kihorombo (Tanzania)",
"language.ru": "русский",
"language.ru_MD": "русский (Молдова)",
"language.ru_RU": "русский (Россия)",
"language.ru_UA": "русский (Украина)",
"language.rw": "Kinyarwanda",
"language.rw_RW": "Kinyarwanda (Rwanda)",
"language.rwk": "Kiruwa",
"language.rwk_TZ": "Kiruwa (Tanzania)",
"language.saq": "Kisampur",
"language.saq_KE": "Kisampur (Kenya)",
"language.sbp": "Ishisangu",
"language.sbp_TZ": "Ishisangu (Tansaniya)",
"language.seh": "sena",
"language.seh_MZ": "sena (Moçambique)",
"language.ses": "Koyraboro senni",
"language.ses_ML": "Koyraboro senni (Maali)",
"language.sg": "Sängö",
"language.sg_CF": "Sängö (Ködörösêse tî Bêafrîka)",
"language.shi": "tamazight",
"language.shi_Latn": "tamazight (Latn)",
"language.shi_Latn_MA": "tamazight (Latn, lmɣrib)",
"language.shi_Tfng": "ⵜⴰⵎⴰⵣⵉⵖⵜ (Tfng)",
"language.shi_Tfng_MA": "ⵜⴰⵎⴰⵣⵉⵖⵜ (Tfng, ⵍⵎⵖⵔⵉⴱ)",
"language.si": "සිංහල",
"language.si_LK": "සිංහල (ශ්රී ලංකාව)",
"language.sk": "slovenčina",
"language.sk_SK": "slovenčina (Slovenská republika)",
"language.sl": "slovenščina",
"language.sl_SI": "slovenščina (Slovenija)",
"language.sn": "chiShona",
"language.sn_ZW": "chiShona (Zimbabwe)",
"language.so": "Soomaali",
"language.so_DJ": "Soomaali (Jabuuti)",
"language.so_ET": "Soomaali (Itoobiya)",
"language.so_KE": "Soomaali (Kiiniya)",
"language.so_SO": "Soomaali (Soomaaliya)",
"language.sq": "shqip",
"language.sq_AL": "shqip (Shqipëria)",
"language.sr": "Српски",
"language.sr_Cyrl": "Српски (Ћирилица)",
"language.sr_Cyrl_BA": "Српски (Ћирилица, Босна и Херцеговина)",
"language.sr_Cyrl_ME": "Српски (Ћирилица, Црна Гора)",
"language.sr_Cyrl_RS": "Српски (Ћирилица, Србија)",
"language.sr_Latn": "Srpski (Latinica)",
"language.sr_Latn_BA": "Srpski (Latinica, Bosna i Hercegovina)",
"language.sr_Latn_ME": "Srpski (Latinica, Crna Gora)",
"language.sr_Latn_RS": "Srpski (Latinica, Srbija)",
"language.sv": "svenska",
"language.sv_FI": "svenska (Finland)",
"language.sv_SE": "svenska (Sverige)",
"language.sw": "Kiswahili",
"language.sw_KE": "Kiswahili (Kenya)",
"language.sw_TZ": "Kiswahili (Tanzania)",
"language.swc": "Kiswahili ya Kongo",
"language.swc_CD": "Kiswahili ya Kongo (Jamhuri ya Kidemokrasia ya Kongo)",
"language.ta": "தமிழ்",
"language.ta_IN": "தமிழ் (இந்தியா)",
"language.ta_LK": "தமிழ் (இலங்கை)",
"language.te": "తెలుగు",
"language.te_IN": "తెలుగు (భారత దేశం)",
"language.teo": "Kiteso",
"language.teo_KE": "Kiteso (Kenia)",
"language.teo_UG": "Kiteso (Uganda)",
"language.th": "ไทย",
"language.th_TH": "ไทย (ไทย)",
"language.ti": "ትግርኛ",
"language.ti_ER": "ትግርኛ (ER)",
"language.ti_ET": "ትግርኛ (ET)",
"language.to": "lea fakatonga",
"language.to_TO": "lea fakatonga (Tonga)",
"language.tr": "Türkçe",
"language.tr_TR": "Türkçe (Türkiye)",
"language.twq": "Tasawaq senni",
"language.twq_NE": "Tasawaq senni (Nižer)",
"language.tzm": "Tamaziɣt",
"language.tzm_Latn": "Tamaziɣt (Latn)",
"language.tzm_Latn_MA": "Tamaziɣt (Latn, Meṛṛuk)",
"language.uk": "українська",
"language.uk_UA": "українська (Україна)",
"language.ur": "اردو",
"language.ur_IN": "اردو (بھارت)",
"language.ur_PK": "اردو (پاکستان)",
"language.uz": "Ўзбек",
"language.uz_Arab": "اۉزبېک (Arab)",
"language.uz_Arab_AF": "اۉزبېک (Arab, افغانستان)",
"language.uz_Cyrl": "Ўзбек (Cyrl)",
"language.uz_Cyrl_UZ": "Ўзбек (Cyrl, Ўзбекистон)",
"language.uz_Latn": "oʼzbekcha (Lotin)",
"language.uz_Latn_UZ": "oʼzbekcha (Lotin, Oʼzbekiston)",
"language.vai": "ꕙꔤ",
"language.vai_Latn": "Vai (Latn)",
"language.vai_Latn_LR": "Vai (Latn, Laibhiya)",
"language.vai_Vaii": "ꕙꔤ (Vaii)",
"language.vai_Vaii_LR": "ꕙꔤ (Vaii, ꕞꔤꔫꕩ)",
"language.vi": "Tiếng Việt",
"language.vi_VN": "Tiếng Việt (Việt Nam)",
"language.vun": "Kyivunjo",
"language.vun_TZ": "Kyivunjo (Tanzania)",
"language.xog": "Olusoga",
"language.xog_UG": "Olusoga (Yuganda)",
"language.yav": "nuasue",
"language.yav_CM": "nuasue (Kemelún)",
"language.yo": "Èdè Yorùbá",
"language.yo_NG": "Èdè Yorùbá (Orílẹ́ède Nàìjíríà)",
"language.zh": "中文",
"language.zh_Hans": "中文(简体中文)",
"language.zh_Hans_CN": "中文(简体中文、中国)",
"language.zh_Hans_HK": "中文(简体中文、中国香港特别行政区)",
"language.zh_Hans_MO": "中文(简体中文、中国澳门特别行政区)",
"language.zh_Hans_SG": "中文(简体中文、新加坡)",
"language.zh_Hant": "中文(繁體中文)",
"language.zh_Hant_HK": "中文(繁體中文,中華人民共和國香港特別行政區)",
"language.zh_Hant_MO": "中文(繁體中文,中華人民共和國澳門特別行政區)",
"language.zh_Hant_TW": "中文(繁體中文,台灣)",
"language.zu": "isiZulu",
"language.zu_ZA": "isiZulu (iNingizimu Afrika)",
"list.databases.button.label": "Ajouter une nouvelle connection",
"list.databases.title.plural": "connexions dans cet environnement",
"list.databases.title.singular": "connexion dans cet environnement",
"list.languages.button.label": "Ajouter un nouveau langage",
"list.languages.default.languages": "Langage par défault",
"list.languages.set.languages": "Appliquer par défault",
"list.languages.title.plural": "langages sont disponibles",
"list.languages.title.singular": "langage est disponible",
"menu.item.advanced": "Avancé",
"menu.item.application": "Application",
"menu.item.database": "Base de donnée",
"menu.item.languages": "Langages",
"menu.item.request": "Requête",
"menu.item.response": "Réponse",
"menu.item.security": "Sécurité",
"menu.item.server": "Serveur",
"menu.section.environments": "Environnements",
"menu.section.global-settings": "Configuration générale",
"pageNotFound": "Page introuvable",
"plugin.description.long": "Configurez votre projet en quelques secondes.",
"plugin.description.short": "Configurez votre projet en quelques secondes.",
"popUpWarning.danger.message": "Des models sont toujours reliés à cette connexion.....",
"popUpWarning.danger.ok.message": "Je comprends",
"popUpWarning.databases.danger.message": "Les types de contenu sont toujours liés à cette connexion. En le supprimant, vous pourriez causer des problèmes critiques à votre application. Soyez prudent...",
"popUpWarning.databases.danger.ok.message": "J'ai compris",
"popUpWarning.databases.delete.message": "Etes-vous sûre de vouloir supprimer cette connexion ?",
"popUpWarning.languages.delete.message": "Etes-vous sûre de vouloir supprimer ce language ?",
"popUpWarning.title": "Merci de confirmer",
"request.error.config": "Le fichier de configuration n'éxiste pas.",
"request.error.database.exist": "Cette connexion est déjà utilisée",
"request.error.database.unknow": "Il n'y a pas de connexion de ce genre",
"request.error.environment.required": "L'environnement est obligatoire.",
"request.error.environment.unknow": "L'environnement est inconnu.",
"request.error.languages.exist": "Ce langage existe déjà.",
"request.error.languages.incorrect": "Ce langage est incorrecte.",
"request.error.languages.unknow": "Ce langage n'éxiste pas.",
"request.error.type.boolean": "Un boolean est demandé.",
"request.error.type.number": "Un nombre est demandé.",
"request.error.type.select": "La valeur doit être dans la liste prédéfini.",
"request.error.type.string": "Un texte est demandé.",
"request.error.validation.max": "La valeur est trop grande.",
"request.error.validation.maxLength": "La valeur est trop longue.",
"request.error.validation.min": "La valeur est trop basse.",
"request.error.validation.minLength": "La valeur est trop courte.",
"request.error.validation.regex": "La valeur ne correspond pas au format attendu.",
"request.error.validation.required": "Ce champ est obligatoire.",
"strapi.notification.error": "Une erreur est apparue",
"strapi.notification.info.serverRestart": "Le serveur va redémarrer",
"strapi.notification.info.settingsEqual": "Les settings sont similaires",
"strapi.notification.success.databaseAdd": "La nouvelle base de données a été ajoutée",
"strapi.notification.success.databaseDelete": "Suppression de la base de données",
"strapi.notification.success.databaseDeleted": "La base de données a bien été supprimée",
"strapi.notification.success.databaseEdit": "La base de données a bien été éditée",
"strapi.notification.success.languageAdd": "Le nouveau langage a été ajouté",
"strapi.notification.success.languageDelete": "Le language a été supprimé",
"strapi.notification.success.settingsEdit": "Les modifications ont été effectuées"
}
|
packages/strapi-plugin-settings-manager/admin/src/translations/fr.json
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.0001759786537149921,
0.00017220292647834867,
0.0001624582801014185,
0.0001727172639220953,
0.000002525160198274534
] |
{
"id": 5,
"code_window": [
"\n",
"function adminPageReducer(state = initialState, action) {\n",
" switch (action.type) {\n",
" case GET_ADMIN_DATA_SUCCEEDED:\n",
" return state\n",
" .update('allowGa', () => action.data.allowGa)\n",
" .update('currentEnvironment', () => action.data.currentEnvironment)\n",
" .update('layout', () => Map(action.data.layout))\n",
" .update('strapiVersion', () => action.data.strapiVersion)\n",
" .update('isLoading', () => false);\n",
" default:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .update('uuid', () => action.data.uuid)\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/reducer.js",
"type": "replace",
"edit_start_line_idx": 24
}
|
@mixin float-left {
float: left !important;
}
@mixin float-right {
float: right !important;
}
@mixin float-none {
float: none !important;
}
|
packages/strapi-admin/admin/src/styles/libs/bootstrap/mixins/_float.scss
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00016494886949658394,
0.00016494886949658394,
0.00016494886949658394,
0.00016494886949658394,
0
] |
{
"id": 6,
"code_window": [
" if (hasUserPlugin && auth.getToken() !== null) {\n",
" yield call(request, `${strapi.backendURL}/users/me`, { method: 'GET' });\n",
" }\n",
"\n",
" const [{ allowGa }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([\n",
" call(request, '/admin/gaConfig', { method: 'GET' }),\n",
" call(request, '/admin/strapiVersion', { method: 'GET' }),\n",
" call(request, '/admin/currentEnvironment', { method: 'GET' }),\n",
" call(request, '/admin/layout', { method: 'GET' }),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [{ uuid }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/saga.js",
"type": "replace",
"edit_start_line_idx": 18
}
|
/**
*
* AdminPage reducer
*
*/
import { fromJS, Map } from 'immutable';
import {
GET_ADMIN_DATA_SUCCEEDED,
} from './constants';
const initialState = fromJS({
allowGa: true,
currentEnvironment: 'development',
isLoading: true,
layout: Map({}),
strapiVersion: '3',
});
function adminPageReducer(state = initialState, action) {
switch (action.type) {
case GET_ADMIN_DATA_SUCCEEDED:
return state
.update('allowGa', () => action.data.allowGa)
.update('currentEnvironment', () => action.data.currentEnvironment)
.update('layout', () => Map(action.data.layout))
.update('strapiVersion', () => action.data.strapiVersion)
.update('isLoading', () => false);
default:
return state;
}
}
export default adminPageReducer;
|
packages/strapi-admin/admin/src/containers/AdminPage/reducer.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.9653160572052002,
0.25089722871780396,
0.000166599391377531,
0.019053122028708458,
0.4127580225467682
] |
{
"id": 6,
"code_window": [
" if (hasUserPlugin && auth.getToken() !== null) {\n",
" yield call(request, `${strapi.backendURL}/users/me`, { method: 'GET' });\n",
" }\n",
"\n",
" const [{ allowGa }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([\n",
" call(request, '/admin/gaConfig', { method: 'GET' }),\n",
" call(request, '/admin/strapiVersion', { method: 'GET' }),\n",
" call(request, '/admin/currentEnvironment', { method: 'GET' }),\n",
" call(request, '/admin/layout', { method: 'GET' }),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [{ uuid }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/saga.js",
"type": "replace",
"edit_start_line_idx": 18
}
|
# Don't check auto-generated stuff into git
coverage
node_modules
stats.json
package-lock.json
yarn.lock
# Cruft
.DS_Store
npm-debug.log
.idea
|
packages/strapi-generate-admin/templates/gitignore
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017287081573158503,
0.00017227616626769304,
0.00017168150225188583,
0.00017227616626769304,
5.946567398495972e-7
] |
{
"id": 6,
"code_window": [
" if (hasUserPlugin && auth.getToken() !== null) {\n",
" yield call(request, `${strapi.backendURL}/users/me`, { method: 'GET' });\n",
" }\n",
"\n",
" const [{ allowGa }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([\n",
" call(request, '/admin/gaConfig', { method: 'GET' }),\n",
" call(request, '/admin/strapiVersion', { method: 'GET' }),\n",
" call(request, '/admin/currentEnvironment', { method: 'GET' }),\n",
" call(request, '/admin/layout', { method: 'GET' }),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [{ uuid }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/saga.js",
"type": "replace",
"edit_start_line_idx": 18
}
|
/**
*
* EditForm
*
*/
import React from 'react';
import { findIndex, get, isEmpty, map } from 'lodash';
import PropTypes from 'prop-types';
// You can find these components in either
// ./node_modules/strapi-helper-plugin/lib/src
// or strapi/packages/strapi-helper-plugin/lib/src
import Input from 'components/InputsIndex';
import styles from './styles.scss';
class EditForm extends React.Component {
getProviderForm = () => get(this.props.settings, ['providers', this.props.selectedProviderIndex, 'auth'], {});
generateSelectOptions = () => (
Object.keys(get(this.props.settings, 'providers', {})).reduce((acc, current) => {
const option = {
id: get(this.props.settings, ['providers', current, 'name']),
value: get(this.props.settings, ['providers', current, 'provider']),
};
acc.push(option);
return acc;
}, [])
)
render() {
return (
<div className={styles.editForm}>
<div className="row">
<Input
customBootstrapClass="col-md-6"
inputDescription={{ id: 'upload.EditForm.Input.select.inputDescription' }}
inputClassName={styles.inputStyle}
label={{ id: 'upload.EditForm.Input.select.label' }}
name="provider"
onChange={this.props.onChange}
selectOptions={this.generateSelectOptions()}
type="select"
value={get(this.props.modifiedData, 'provider')}
/>
</div>
{!isEmpty(this.getProviderForm()) && (
<div className={styles.subFormWrapper}>
<div className="row">
{map(this.getProviderForm(), (value, key) => (
<Input
didCheckErrors={this.props.didCheckErrors}
errors={get(this.props.formErrors, [findIndex(this.props.formErrors, ['name', key]), 'errors'])}
key={key}
label={{ id: value.label }}
name={key}
onChange={this.props.onChange}
selectOptions={value.values}
type={value.type === 'enum' ? 'select' : value.type}
validations={{ required: true }}
value={get(this.props.modifiedData, key, '')}
/>
))}
</div>
</div>
)}
<div className={styles.separator} />
<div className="row">
<Input
inputClassName={styles.inputStyle}
label={{ id: 'upload.EditForm.Input.number.label' }}
name="sizeLimit"
onChange={this.props.onChange}
type="number"
value={get(this.props.modifiedData, 'sizeLimit', 1) / 1000}
/>
</div>
<div className={styles.separator} style={{ marginTop: '-4px'}} />
<div className="row">
<Input
label={{ id: 'upload.EditForm.Input.toggle.label' }}
name="enabled"
onChange={this.props.onChange}
type="toggle"
value={get(this.props.modifiedData, 'enabled', false)}
/>
</div>
</div>
);
}
}
EditForm.defaultProps = {
settings: {
providers: [],
},
};
EditForm.propTypes = {
didCheckErrors: PropTypes.bool.isRequired,
formErrors: PropTypes.array.isRequired,
modifiedData: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
selectedProviderIndex: PropTypes.number.isRequired,
settings: PropTypes.object,
};
export default EditForm;
|
packages/strapi-plugin-upload/admin/src/components/EditForm/index.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00024231968563981354,
0.00017791203572414815,
0.00016023368516471237,
0.00017317617312073708,
0.000020724415662698448
] |
{
"id": 6,
"code_window": [
" if (hasUserPlugin && auth.getToken() !== null) {\n",
" yield call(request, `${strapi.backendURL}/users/me`, { method: 'GET' });\n",
" }\n",
"\n",
" const [{ allowGa }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([\n",
" call(request, '/admin/gaConfig', { method: 'GET' }),\n",
" call(request, '/admin/strapiVersion', { method: 'GET' }),\n",
" call(request, '/admin/currentEnvironment', { method: 'GET' }),\n",
" call(request, '/admin/layout', { method: 'GET' }),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [{ uuid }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/saga.js",
"type": "replace",
"edit_start_line_idx": 18
}
|
# Filters
See the [filters' concepts](../concepts/concepts.md#filters) for details.
::: note
by default, the filters can only be used from `find` endpoints generated by the Content Type Builder and the [CLI](../cli/CLI.md). If you need to implement a filters system somewhere else, read the [programmatic usage](#programmatic-usage) section.
:::
## Available operators
The available operators are separated in four different categories:
- [Filters](#filters)
- [Sort](#sort)
- [Limit](#limit)
- [Start](#start)
### Filters
Easily filter results according to fields values.
- `=`: Equals
- `_ne`: Not equals
- `_lt`: Lower than
- `_gt`: Greater than
- `_lte`: Lower than or equal to
- `_gte`: Greater than or equal to
- `_contains`: Contains
- `_containss`: Contains case sensitive
#### Examples
Find users having `John` as first name.
`GET /user?firstName=John`
Find products having a price equal or greater than `3`.
`GET /product?price_gte=3`
### Sort
Sort according to a specific field.
#### Example
Sort users by email.
- ASC: `GET /user?_sort=email:asc`
- DESC: `GET /user?_sort=email:desc`
### Limit
Limit the size of the returned results.
#### Example
Limit the result length to 30.
`GET /user?_limit=30`
### Start
Skip a specific number of entries (especially useful for pagination).
#### Example
Get the second page of results.
`GET /user?_start=10&_limit=10`
## Programmatic usage
Requests system can be implemented in custom code sections.
### Extracting requests filters
To extract the filters from an JavaScript object or a request, you need to call the [`strapi.utils.models.convertParams` helper](../api-reference/reference.md#strapiutils).
::: note
The returned objects is formatted according to the ORM used by the model.
:::
#### Example
**Path —** `./api/user/controllers/User.js`.
```js
// Define a list of params.
const params = {
'_limit': 20,
'_sort': 'email'
};
// Convert params.
const formattedParams = strapi.utils.models.convertParams('user', params); // { limit: 20, sort: 'email' }
```
### Query usage
#### Example
**Path —** `./api/user/controllers/User.js`.
```js
module.exports = {
find: async (ctx) => {
// Convert params.
const formattedParams = strapi.utils.models.convertParams('user', ctx.request.query);
// Get the list of users according to the request query.
const filteredUsers = await User
.find()
.where(formattedParams.where)
.sort(formattedParams.sort)
.skip(formattedParams.start)
.limit(formattedParams.limit);
// Finally, send the results to the client.
ctx.body = filteredUsers;
};
};
```
|
docs/3.x.x/guides/restapi.md
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017090162145905197,
0.0001665027957642451,
0.00015929844812490046,
0.00016707855684217066,
0.0000033010953757184325
] |
{
"id": 7,
"code_window": [
" call(request, '/admin/strapiVersion', { method: 'GET' }),\n",
" call(request, '/admin/currentEnvironment', { method: 'GET' }),\n",
" call(request, '/admin/layout', { method: 'GET' }),\n",
" ]);\n",
" yield put(getAdminDataSucceeded({ allowGa, strapiVersion, currentEnvironment, layout }));\n",
"\n",
" } catch(err) {\n",
" console.log(err); // eslint-disable-line no-console\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" yield put(getAdminDataSucceeded({ uuid, strapiVersion, currentEnvironment, layout }));\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/saga.js",
"type": "replace",
"edit_start_line_idx": 24
}
|
/**
*
* App.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router-dom';
import AdminPage from 'containers/AdminPage';
import NotFoundPage from 'containers/NotFoundPage';
import NotificationProvider from 'containers/NotificationProvider';
import AppLoader from 'containers/AppLoader';
import FullStory from 'components/FullStory';
import LoadingIndicatorPage from 'components/LoadingIndicatorPage';
import '../../styles/main.scss';
import styles from './styles.scss';
export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<FullStory org="GK708" />
<NotificationProvider />
<AppLoader>
{({ shouldLoad }) => {
if (shouldLoad) {
return <LoadingIndicatorPage />;
}
return (
<div className={styles.container}>
<Switch>
<Route path="/" component={AdminPage} />
<Route path="" component={NotFoundPage} />
</Switch>
</div>
);
}}
</AppLoader>
</div>
);
}
}
App.contextTypes = {
router: PropTypes.object.isRequired,
};
App.propTypes = {};
export default App;
|
packages/strapi-admin/admin/src/containers/App/index.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017473616753704846,
0.00017064846178982407,
0.000163946722750552,
0.00017166743054986,
0.000003291638677183073
] |
{
"id": 7,
"code_window": [
" call(request, '/admin/strapiVersion', { method: 'GET' }),\n",
" call(request, '/admin/currentEnvironment', { method: 'GET' }),\n",
" call(request, '/admin/layout', { method: 'GET' }),\n",
" ]);\n",
" yield put(getAdminDataSucceeded({ allowGa, strapiVersion, currentEnvironment, layout }));\n",
"\n",
" } catch(err) {\n",
" console.log(err); // eslint-disable-line no-console\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" yield put(getAdminDataSucceeded({ uuid, strapiVersion, currentEnvironment, layout }));\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/saga.js",
"type": "replace",
"edit_start_line_idx": 24
}
|
<template>
<div class="dropdown-wrapper" :class="{ open }">
<a class="dropdown-title" @click="toggle">
<span class="title">{{ item.text }}</span>
<span class="arrow" :class="open ? 'down' : 'right'"></span>
</a>
<DropdownTransition>
<ul class="nav-dropdown" v-show="open">
<li
class="dropdown-item"
v-for="(subItem, index) in item.items"
:key="subItem.link || index">
<h4 v-if="subItem.type === 'links'">{{ subItem.text }}</h4>
<ul class="dropdown-subitem-wrapper" v-if="subItem.type === 'links'">
<li
class="dropdown-subitem"
v-for="childSubItem in subItem.items"
:key="childSubItem.link">
<NavLink :item="childSubItem"/>
</li>
</ul>
<NavLink v-else :item="subItem"/>
</li>
</ul>
</DropdownTransition>
</div>
</template>
<script>
import NavLink from './NavLink.vue'
import DropdownTransition from './DropdownTransition.vue'
export default {
components: { NavLink, DropdownTransition },
data () {
return {
open: false
}
},
props: {
item: {
required: true
}
},
methods: {
toggle () {
this.open = !this.open
}
}
}
</script>
<style lang="stylus">
@import './styles/config.styl'
.dropdown-wrapper
.dropdown-title
display block
&:hover
border-color transparent
.arrow
vertical-align middle
margin-top -1px
margin-left 0.4rem
.nav-dropdown
.dropdown-item
color inherit
line-height 1.7rem
h4
margin 0.45rem 0 0
border-top 1px solid #eee
padding 0.45rem 1.5rem 0 1.25rem
.dropdown-subitem-wrapper
padding 0
list-style none
.dropdown-subitem
font-size 0.9em
a
display block
line-height 1.7rem
position relative
border-bottom none
font-weight 400
margin-bottom 0
padding 0 1.5rem 0 1.25rem
&:hover
color $accentColor
&.router-link-active
color $accentColor
&::after
content ""
width 0
height 0
border-left 5px solid $accentColor
border-top 3px solid transparent
border-bottom 3px solid transparent
position absolute
top calc(50% - 2px)
left 9px
&:first-child h4
margin-top 0
padding-top 0
border-top 0
@media (max-width: $MQMobile)
.dropdown-wrapper
&.open .dropdown-title
margin-bottom 0.5rem
.nav-dropdown
transition height .1s ease-out
overflow hidden
.dropdown-item
h4
border-top 0
margin-top 0
padding-top 0
h4, & > a
font-size 15px
line-height 2rem
.dropdown-subitem
font-size 14px
padding-left 1rem
@media (min-width: $MQMobile)
.dropdown-wrapper
height 1.8rem
&:hover .nav-dropdown
// override the inline style.
display block !important
.dropdown-title .arrow
// make the arrow always down at desktop
border-left 4px solid transparent
border-right 4px solid transparent
border-top 6px solid $arrowBgColor
border-bottom 0
.nav-dropdown
display none
// Avoid height shaked by clicking
height auto !important
box-sizing border-box;
max-height calc(100vh - 2.7rem)
overflow-y auto
position absolute
top 100%
right 0
background-color #fff
padding 0.6rem 0
border 1px solid #ddd
border-bottom-color #ccc
text-align left
border-radius 0.25rem
white-space nowrap
margin 0
</style>
|
docs/.vuepress/theme/DropdownLink.vue
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017593117081560194,
0.00017419486539438367,
0.00017204908363055438,
0.00017452806059736758,
0.0000012714863260043785
] |
{
"id": 7,
"code_window": [
" call(request, '/admin/strapiVersion', { method: 'GET' }),\n",
" call(request, '/admin/currentEnvironment', { method: 'GET' }),\n",
" call(request, '/admin/layout', { method: 'GET' }),\n",
" ]);\n",
" yield put(getAdminDataSucceeded({ allowGa, strapiVersion, currentEnvironment, layout }));\n",
"\n",
" } catch(err) {\n",
" console.log(err); // eslint-disable-line no-console\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" yield put(getAdminDataSucceeded({ uuid, strapiVersion, currentEnvironment, layout }));\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/saga.js",
"type": "replace",
"edit_start_line_idx": 24
}
|
/**
*
* SettingPage reducer
*/
import { fromJS } from 'immutable';
import {
ON_CLICK_EDIT_FIELD,
ON_CLICK_EDIT_LIST_ITEM,
ON_CLICK_EDIT_RELATION,
} from './constants';
const initialState = fromJS({
fieldToEdit: fromJS({}),
listItemToEdit: fromJS({}),
relationToEdit: fromJS({}),
});
function settingPageReducer(state = initialState, action) {
switch (action.type) {
case ON_CLICK_EDIT_FIELD:
return state
.update('fieldToEdit', () => fromJS(action.fieldToEdit))
.update('relationToEdit', () => fromJS({})); // Both these objects will be used to set the form in order to know which form needs to be displayed
case ON_CLICK_EDIT_LIST_ITEM:
return state.update('listItemToEdit', () => fromJS(action.listItemToEdit));
case ON_CLICK_EDIT_RELATION:
return state
.update('fieldToEdit', () => fromJS({}))
.update('relationToEdit', () => fromJS(action.relationToEdit));
default:
return state;
}
}
export default settingPageReducer;
|
packages/strapi-plugin-content-manager/admin/src/containers/SettingPage/reducer.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017757048772182316,
0.0001751171803334728,
0.00017351898713968694,
0.00017468963051214814,
0.0000015446755696757464
] |
{
"id": 7,
"code_window": [
" call(request, '/admin/strapiVersion', { method: 'GET' }),\n",
" call(request, '/admin/currentEnvironment', { method: 'GET' }),\n",
" call(request, '/admin/layout', { method: 'GET' }),\n",
" ]);\n",
" yield put(getAdminDataSucceeded({ allowGa, strapiVersion, currentEnvironment, layout }));\n",
"\n",
" } catch(err) {\n",
" console.log(err); // eslint-disable-line no-console\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" yield put(getAdminDataSucceeded({ uuid, strapiVersion, currentEnvironment, layout }));\n"
],
"file_path": "packages/strapi-admin/admin/src/containers/AdminPage/saga.js",
"type": "replace",
"edit_start_line_idx": 24
}
|
import {
GET_ARTICLES,
GET_ARTICLES_SUCCEEDED,
ON_CHANGE,
SUBMIT,
SUBMIT_SUCCEEDED,
} from './constants';
export function getArticles() {
return {
type: GET_ARTICLES,
};
}
export function getArticlesSucceeded(articles) {
return {
type: GET_ARTICLES_SUCCEEDED,
articles,
};
}
export function onChange({ target }) {
return {
type: ON_CHANGE,
value: target.value,
};
}
export function submit() {
return {
type: SUBMIT,
};
}
export function submitSucceeded() {
return {
type: SUBMIT_SUCCEEDED,
};
}
|
packages/strapi-admin/admin/src/containers/HomePage/actions.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.0006011216319166124,
0.0003552000562194735,
0.00017110641056206077,
0.00032428608392365277,
0.00018724559049587697
] |
{
"id": 8,
"code_window": [
"import NotFoundPage from 'containers/NotFoundPage';\n",
"import NotificationProvider from 'containers/NotificationProvider';\n",
"import AppLoader from 'containers/AppLoader';\n",
"import FullStory from 'components/FullStory';\n",
"import LoadingIndicatorPage from 'components/LoadingIndicatorPage';\n",
"import '../../styles/main.scss';\n",
"import styles from './styles.scss';\n",
"\n",
"export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-admin/admin/src/containers/App/index.js",
"type": "replace",
"edit_start_line_idx": 20
}
|
import { all, fork, call, put, select, takeLatest } from 'redux-saga/effects';
import auth from 'utils/auth';
import request from 'utils/request';
import { makeSelectAppPlugins } from 'containers/App/selectors';
import {
getAdminDataSucceeded,
} from './actions';
import { GET_ADMIN_DATA } from './constants';
function* getData() {
try {
const appPlugins = yield select(makeSelectAppPlugins());
const hasUserPlugin = appPlugins.indexOf('users-permissions') !== -1;
if (hasUserPlugin && auth.getToken() !== null) {
yield call(request, `${strapi.backendURL}/users/me`, { method: 'GET' });
}
const [{ allowGa }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([
call(request, '/admin/gaConfig', { method: 'GET' }),
call(request, '/admin/strapiVersion', { method: 'GET' }),
call(request, '/admin/currentEnvironment', { method: 'GET' }),
call(request, '/admin/layout', { method: 'GET' }),
]);
yield put(getAdminDataSucceeded({ allowGa, strapiVersion, currentEnvironment, layout }));
} catch(err) {
console.log(err); // eslint-disable-line no-console
}
}
function* defaultSaga() {
yield all([
fork(takeLatest, GET_ADMIN_DATA, getData),
]);
}
export default defaultSaga;
|
packages/strapi-admin/admin/src/containers/AdminPage/saga.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017431114974897355,
0.0001705012982711196,
0.0001670444617047906,
0.00017032476898748428,
0.0000028023525828757556
] |
{
"id": 8,
"code_window": [
"import NotFoundPage from 'containers/NotFoundPage';\n",
"import NotificationProvider from 'containers/NotificationProvider';\n",
"import AppLoader from 'containers/AppLoader';\n",
"import FullStory from 'components/FullStory';\n",
"import LoadingIndicatorPage from 'components/LoadingIndicatorPage';\n",
"import '../../styles/main.scss';\n",
"import styles from './styles.scss';\n",
"\n",
"export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-admin/admin/src/containers/App/index.js",
"type": "replace",
"edit_start_line_idx": 20
}
|
# Migrating from 3.0.0-alpha.8 to 3.0.0-alpha.9
**Here are the major changes:**
- Put roles' permissions in database
- Providers connection (Facebook, GitHub, ...)
> Feel free to [join us on Slack](http://slack.strapi.io) and ask questions about the migration process.
## Getting started
Install Strapi `alpha.9` globally on your computer. To do so run `npm install [email protected] -g`.
When it's done, generate a new empty project `strapi new myNewProject` (don't pay attention to the database configuration).
## Configurations
You will have to update just 2 files: `package.json` and `request.json`
- Edit the Strapi's dependencies version: (move Strapi's dependencies to `3.0.0-alpha.9` version) in `package.json` file
```json
{
"dependencies": {
"lodash": "4.x.x",
"strapi": "3.0.0-alpha.9",
"strapi-mongoose": "3.0.0-alpha.9"
}
}
```
- Edit the `session.enabled` settings to `true` in each environment file: `/configs/environments/***/request.json`
```json
{
"session": {
"enabled": true
}
}
```
## Update the Admin
Delete your old admin folder and replace it by the new one.
## Update the Plugins
Copy this file `/plugins/users-permissions/config/jwt.json` **from your old project** and paste it in the corresponding one in your new project.
Copy the fields and relations you had in your `/plugins/users-permissions/models/User.settings.json` file in the new one.
Then, delete your old `plugins` folder and replace it by the new one.
## ⚠️ Roles update
Roles are now stored in your database. You will have to re-create and configure them via the admin dashboard.
## ⚠️ User collection/table name has changed
If you have an existing set of users in your database you will have to rename the collection/table from `user` to `users-permissions_user`.
Then update all your users by changing the old role id by the new one which is in `users-permissions_role` collection/table.
That's all, you have now upgraded to Strapi `alpha.9`.
|
docs/3.x.x/migration/migration-guide-alpha-8-to-alpha-9.md
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.0001736720878398046,
0.00016937720647547394,
0.00016377844440285116,
0.0001694235543254763,
0.000003427074716455536
] |
{
"id": 8,
"code_window": [
"import NotFoundPage from 'containers/NotFoundPage';\n",
"import NotificationProvider from 'containers/NotificationProvider';\n",
"import AppLoader from 'containers/AppLoader';\n",
"import FullStory from 'components/FullStory';\n",
"import LoadingIndicatorPage from 'components/LoadingIndicatorPage';\n",
"import '../../styles/main.scss';\n",
"import styles from './styles.scss';\n",
"\n",
"export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-admin/admin/src/containers/App/index.js",
"type": "replace",
"edit_start_line_idx": 20
}
|
.pluginHeaderActions {
display: flex;
justify-content: flex-end;
margin-top: 9px;
margin-right: -18px;
}
|
packages/strapi-helper-plugin/lib/src/components/PluginHeaderActions/styles.scss
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00016556748596485704,
0.00016556748596485704,
0.00016556748596485704,
0.00016556748596485704,
0
] |
{
"id": 8,
"code_window": [
"import NotFoundPage from 'containers/NotFoundPage';\n",
"import NotificationProvider from 'containers/NotificationProvider';\n",
"import AppLoader from 'containers/AppLoader';\n",
"import FullStory from 'components/FullStory';\n",
"import LoadingIndicatorPage from 'components/LoadingIndicatorPage';\n",
"import '../../styles/main.scss';\n",
"import styles from './styles.scss';\n",
"\n",
"export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-admin/admin/src/containers/App/index.js",
"type": "replace",
"edit_start_line_idx": 20
}
|
.isDraging {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.pluginInputFile {
position: relative;
height: 146px;
width: 100%;
padding-top: 28px;
border: 2px dashed #E3E9F3;
border-radius: 2px;
text-align: center;
> input {
display: none;
}
.icon{
width: 82px;
path{
fill: #CCD0DA;
transition: fill .3s ease;
}
}
&:hover{
cursor: pointer;
}
}
.textWrapper {
margin-top: 10px;
text-align: center;
font-size: 13px;
color: #9EA7B8;
u {
color: #1C5DE7;
}
}
.pluginInputFileHover {
background-color: rgba(28,93,231,0.01) !important;
border: 2px dashed rgba(28,93,231,0.10) !important;
}
.underline {
color: #1C5DE7;
text-decoration: underline;
cursor: pointer;
}
@mixin smoothBlink($firstColor, $secondColor) {
@-webkit-keyframes blink {
0% {
fill: $firstColor;
background-color: $firstColor;
}
26% {
fill: $secondColor;
background-color: $secondColor;
}
76% {
fill: $firstColor;
background-color: $firstColor;
}
}
@keyframes blink {
0% {
fill: $firstColor;
background-color: $firstColor;
}
26% {
fill: $secondColor;
background-color: $secondColor;
}
76% {
fill: $firstColor;
background-color: $firstColor;
}
}
-webkit-animation: blink 2s linear infinite;
-moz-animation: blink 2s linear infinite;
-o-animation: blink 2s linear infinite;
animation: blink 2s linear infinite;
}
.quadrat {
.icon{
path {
fill: #729BEF;
}
}
@include smoothBlink(transparent, rgba(28, 93, 231, 0.05));
}
|
packages/strapi-plugin-upload/admin/src/components/PluginInputFile/styles.scss
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.0001781238242983818,
0.00017583667067810893,
0.00017329660477116704,
0.0001765534543665126,
0.000001547522174405458
] |
{
"id": 9,
"code_window": [
"\n",
"export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function\n",
" render() {\n",
" return (\n",
" <div>\n",
" <FullStory org=\"GK708\" />\n",
" <NotificationProvider />\n",
" <AppLoader>\n",
" {({ shouldLoad }) => {\n",
" if (shouldLoad) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-admin/admin/src/containers/App/index.js",
"type": "replace",
"edit_start_line_idx": 29
}
|
/*
* AdminPage
*
* This is the first thing users see of our AdminPage, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import ReactGA from 'react-ga';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { Switch, Route } from 'react-router-dom';
import { get, includes, isFunction, map, omit } from 'lodash';
import { bindActionCreators, compose } from 'redux';
// Actions required for disabling and enabling the OverlayBlocker
import { disableGlobalOverlayBlocker, enableGlobalOverlayBlocker } from 'actions/overlayBlocker';
import { pluginLoaded, updatePlugin } from 'containers/App/actions';
import {
makeSelectAppPlugins,
makeSelectBlockApp,
makeSelectIsAppLoading,
makeSelectShowGlobalAppBlocker,
selectHasUserPlugin,
selectPlugins,
} from 'containers/App/selectors';
// Design
import ComingSoonPage from 'containers/ComingSoonPage';
import Content from 'containers/Content';
import LocaleToggle from 'containers/LocaleToggle';
import CTAWrapper from 'components/CtaWrapper';
import Header from 'components/Header/index';
import HomePage from 'containers/HomePage/Loadable';
import InstallPluginPage from 'containers/InstallPluginPage/Loadable';
import LeftMenu from 'containers/LeftMenu';
import ListPluginsPage from 'containers/ListPluginsPage/Loadable';
import LoadingIndicatorPage from 'components/LoadingIndicatorPage';
import Logout from 'components/Logout';
import NotFoundPage from 'containers/NotFoundPage/Loadable';
import OverlayBlocker from 'components/OverlayBlocker';
import PluginPage from 'containers/PluginPage';
// Utils
import auth from 'utils/auth';
import injectReducer from 'utils/injectReducer';
import injectSaga from 'utils/injectSaga';
import { getAdminData } from './actions';
import reducer from './reducer';
import saga from './saga';
import selectAdminPage from './selectors';
import styles from './styles.scss';
const PLUGINS_TO_BLOCK_PRODUCTION = ['content-type-builder', 'settings-manager'];
export class AdminPage extends React.Component {
// eslint-disable-line react/prefer-stateless-function
state = { hasAlreadyRegistereOtherPlugins: false };
getChildContext = () => ({
disableGlobalOverlayBlocker: this.props.disableGlobalOverlayBlocker,
enableGlobalOverlayBlocker: this.props.enableGlobalOverlayBlocker,
plugins: this.props.plugins,
updatePlugin: this.props.updatePlugin,
});
componentDidMount() {
this.props.getAdminData();
this.checkLogin(this.props);
ReactGA.initialize('UA-54313258-9');
}
componentDidUpdate(prevProps) {
const { adminPage: { allowGa }, location: { pathname }, plugins } = this.props;
if (prevProps.location.pathname !== pathname) {
this.checkLogin(this.props);
if (allowGa) {
ReactGA.pageview(pathname);
}
}
const hasAdminPath = ['users-permissions', 'hasAdminUser'];
if (get(prevProps.plugins.toJS(), hasAdminPath) !== get(plugins.toJS(), hasAdminPath)) {
this.checkLogin(this.props, true);
}
if (!this.hasUserPluginLoaded(prevProps) && this.hasUserPluginLoaded(this.props)) {
this.checkLogin(this.props);
}
}
checkLogin = (props, skipAction = false) => {
if (props.hasUserPlugin && this.isUrlProtected(props) && !auth.getToken()) {
if (!this.hasUserPluginLoaded(props)) {
return;
}
const endPoint = this.hasAdminUser(props) ? 'login' : 'register';
this.props.history.push(`/plugins/users-permissions/auth/${endPoint}`);
}
if (
!this.isUrlProtected(props) &&
includes(props.location.pathname, 'auth/register') &&
this.hasAdminUser(props) &&
!skipAction
) {
this.props.history.push('/plugins/users-permissions/auth/login');
}
if (
props.hasUserPlugin &&
!this.isUrlProtected(props) &&
!includes(props.location.pathname, 'auth/register') &&
!this.hasAdminUser(props)
) {
this.props.history.push('/plugins/users-permissions/auth/register');
}
if (!props.hasUserPlugin || (auth.getToken() && !this.state.hasAlreadyRegistereOtherPlugins)) {
map(omit(this.props.plugins.toJS(), ['users-permissions', 'email']), plugin => {
switch (true) {
case isFunction(plugin.bootstrap) && isFunction(plugin.pluginRequirements):
plugin
.pluginRequirements(plugin)
.then(plugin => {
return plugin.bootstrap(plugin);
})
.then(plugin => this.props.pluginLoaded(plugin));
break;
case isFunction(plugin.pluginRequirements):
plugin.pluginRequirements(plugin).then(plugin => this.props.pluginLoaded(plugin));
break;
case isFunction(plugin.bootstrap):
plugin.bootstrap(plugin).then(plugin => this.props.pluginLoaded(plugin));
break;
default:
}
});
this.setState({ hasAlreadyRegistereOtherPlugins: true });
}
};
hasUserPluginInstalled = () => {
const { appPlugins } = this.props;
return appPlugins.indexOf('users-permissions') !== -1;
}
hasUserPluginLoaded = props =>
typeof get(props.plugins.toJS(), ['users-permissions', 'hasAdminUser']) !== 'undefined';
hasAdminUser = props => get(props.plugins.toJS(), ['users-permissions', 'hasAdminUser']);
isUrlProtected = props =>
!includes(props.location.pathname, get(props.plugins.toJS(), ['users-permissions', 'nonProtectedUrl']));
shouldDisplayLogout = () => auth.getToken() && this.props.hasUserPlugin && this.isUrlProtected(this.props);
showLeftMenu = () => !includes(this.props.location.pathname, 'users-permissions/auth/');
showLoading = () => {
const { isAppLoading, adminPage: { isLoading } } = this.props;
return isAppLoading || isLoading || (this.hasUserPluginInstalled() && !this.hasUserPluginLoaded(this.props));
}
retrievePlugins = () => {
const {
adminPage: { currentEnvironment },
plugins,
} = this.props;
if (currentEnvironment === 'production') {
let pluginsToDisplay = plugins;
PLUGINS_TO_BLOCK_PRODUCTION.map(plugin => (pluginsToDisplay = pluginsToDisplay.delete(plugin)));
return pluginsToDisplay;
}
return plugins;
};
render() {
const { adminPage } = this.props;
const header = this.showLeftMenu() ? <Header /> : '';
const style = this.showLeftMenu() ? {} : { width: '100%' };
if (this.showLoading()) {
return <LoadingIndicatorPage />;
}
return (
<div className={styles.adminPage}>
{this.showLeftMenu() && (
<LeftMenu
plugins={this.retrievePlugins()}
layout={adminPage.layout}
version={adminPage.strapiVersion}
/>
)}
<CTAWrapper>
{this.shouldDisplayLogout() && <Logout />}
<LocaleToggle isLogged={this.shouldDisplayLogout() === true} />
</CTAWrapper>
<div className={styles.adminPageRightWrapper} style={style}>
{header}
<Content {...this.props} showLeftMenu={this.showLeftMenu()}>
<Switch>
<Route path="/" component={HomePage} exact />
<Route path="/plugins/:pluginId" component={PluginPage} />
<Route path="/plugins" component={ComingSoonPage} />
<Route path="/list-plugins" component={ListPluginsPage} exact />
<Route path="/install-plugin" component={InstallPluginPage} exact />
<Route path="/configuration" component={ComingSoonPage} exact />
<Route path="" component={NotFoundPage} />
<Route path="404" component={NotFoundPage} />
</Switch>
</Content>
</div>
<OverlayBlocker isOpen={this.props.blockApp && this.props.showGlobalAppBlocker} />
</div>
);
}
}
AdminPage.childContextTypes = {
disableGlobalOverlayBlocker: PropTypes.func,
enableGlobalOverlayBlocker: PropTypes.func,
plugins: PropTypes.object,
updatePlugin: PropTypes.func,
};
AdminPage.contextTypes = {
router: PropTypes.object.isRequired,
};
AdminPage.defaultProps = {
adminPage: {},
appPlugins: [],
hasUserPlugin: true,
isAppLoading: true,
};
AdminPage.propTypes = {
adminPage: PropTypes.object,
appPlugins: PropTypes.array,
blockApp: PropTypes.bool.isRequired,
disableGlobalOverlayBlocker: PropTypes.func.isRequired,
enableGlobalOverlayBlocker: PropTypes.func.isRequired,
hasUserPlugin: PropTypes.bool,
history: PropTypes.object.isRequired,
isAppLoading: PropTypes.bool,
location: PropTypes.object.isRequired,
pluginLoaded: PropTypes.func.isRequired,
plugins: PropTypes.object.isRequired,
showGlobalAppBlocker: PropTypes.bool.isRequired,
updatePlugin: PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
adminPage: selectAdminPage(),
appPlugins: makeSelectAppPlugins(),
blockApp: makeSelectBlockApp(),
hasUserPlugin: selectHasUserPlugin(),
isAppLoading: makeSelectIsAppLoading(),
plugins: selectPlugins(),
showGlobalAppBlocker: makeSelectShowGlobalAppBlocker(),
});
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
disableGlobalOverlayBlocker,
enableGlobalOverlayBlocker,
getAdminData,
pluginLoaded,
updatePlugin,
},
dispatch,
);
}
const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({ key: 'adminPage', reducer });
const withSaga = injectSaga({ key: 'adminPage', saga });
export default compose(withReducer, withSaga, withConnect)(AdminPage);
|
packages/strapi-admin/admin/src/containers/AdminPage/index.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.0008086197776719928,
0.00021431341883726418,
0.00016044237418100238,
0.00016956364561337978,
0.00014351736172102392
] |
{
"id": 9,
"code_window": [
"\n",
"export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function\n",
" render() {\n",
" return (\n",
" <div>\n",
" <FullStory org=\"GK708\" />\n",
" <NotificationProvider />\n",
" <AppLoader>\n",
" {({ shouldLoad }) => {\n",
" if (shouldLoad) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-admin/admin/src/containers/App/index.js",
"type": "replace",
"edit_start_line_idx": 29
}
|
'use strict';
/**
* Mutation.js service
*
* @description: A set of functions similar to controller's actions to avoid code duplication.
*/
const _ = require('lodash');
const pluralize = require('pluralize');
const policyUtils = require('strapi-utils').policy;
const Query = require('./Query.js');
/* eslint-disable no-unused-vars */
module.exports = {
/**
* Convert parameters to valid filters parameters.
*
* @return Object
*/
convertToParams: params => {
return Object.keys(params).reduce((acc, current) => {
return Object.assign(acc, {
[`_${current}`]: params[current],
});
}, {});
},
/**
* Execute policies before the specified resolver.
*
* @return Promise or Error.
*/
composeMutationResolver: function(_schema, plugin, name, action) {
// Extract custom resolver or type description.
const { resolver: handler = {} } = _schema;
const queryName = `${action}${_.capitalize(name)}`;
// Retrieve policies.
const policies = _.get(handler, `Mutation.${queryName}.policies`, []);
// Retrieve resolverOf.
const resolverOf = _.get(handler, `Mutation.${queryName}.resolverOf`, '');
const policiesFn = [];
// Boolean to define if the resolver is going to be a resolver or not.
let isController = false;
// Retrieve resolver. It could be the custom resolver of the user
// or the shadow CRUD resolver (aka Content-Manager).
const resolver = (() => {
// Try to retrieve custom resolver.
const resolver = _.get(handler, `Mutation.${queryName}.resolver`);
if (_.isString(resolver) || _.isPlainObject(resolver)) {
const { handler = resolver } = _.isPlainObject(resolver)
? resolver
: {};
// Retrieve the controller's action to be executed.
const [name, action] = handler.split('.');
const controller = plugin
? _.get(strapi.plugins, `${plugin}.controllers.${_.toLower(name)}.${action}`)
: _.get(strapi.controllers, `${_.toLower(name)}.${action}`);
if (!controller) {
return new Error(
`Cannot find the controller's action ${name}.${action}`,
);
}
// We're going to return a controller instead.
isController = true;
// Push global policy to make sure the permissions will work as expected.
policiesFn.push(
policyUtils.globalPolicy(
undefined,
{
handler: `${name}.${action}`,
},
undefined,
plugin,
),
);
// Return the controller.
return controller;
} else if (resolver) {
// Function.
return resolver;
}
// We're going to return a controller instead.
isController = true;
const controllers = plugin
? strapi.plugins[plugin].controllers
: strapi.controllers;
// Try to find the controller that should be related to this model.
const controller = _.get(
controllers,
`${name}.${action === 'delete' ? 'destroy' : action}`,
);
if (!controller) {
return new Error(
`Cannot find the controller's action ${name}.${action}`,
);
}
// Push global policy to make sure the permissions will work as expected.
// We're trying to detect the controller name.
policiesFn.push(
policyUtils.globalPolicy(
undefined,
{
handler: `${name}.${action === 'delete' ? 'destroy' : action}`,
},
undefined,
plugin,
),
);
// Make the query compatible with our controller by
// setting in the context the parameters.
return async (ctx, next) => {
return controller(ctx, next);
};
})();
// The controller hasn't been found.
if (_.isError(resolver)) {
return resolver;
}
// Force policies of another action on a custom resolver.
if (_.isString(resolverOf) && !_.isEmpty(resolverOf)) {
// Retrieve the controller's action to be executed.
const [name, action] = resolverOf.split('.');
const controller = plugin
? _.get(strapi.plugins, `${plugin}.controllers.${_.toLower(name)}.${action}`)
: _.get(strapi.controllers, `${_.toLower(name)}.${action}`);
if (!controller) {
return new Error(
`Cannot find the controller's action ${name}.${action}`,
);
}
policiesFn[0] = policyUtils.globalPolicy(
undefined,
{
handler: `${name}.${action}`,
},
undefined,
plugin,
);
}
if (strapi.plugins['users-permissions']) {
policies.push('plugins.users-permissions.permissions');
}
// Populate policies.
policies.forEach(policy =>
policyUtils.get(
policy,
plugin,
policiesFn,
`GraphQL query "${queryName}"`,
name,
),
);
return async (obj, options, { context }) => {
// Hack to be able to handle permissions for each query.
const ctx = Object.assign(_.clone(context), {
request: Object.assign(_.clone(context.request), {
graphql: null,
}),
});
// Execute policies stack.
const policy = await strapi.koaMiddlewares.compose(policiesFn)(ctx);
// Policy doesn't always return errors but they update the current context.
if (
_.isError(ctx.request.graphql) ||
_.get(ctx.request.graphql, 'isBoom')
) {
return ctx.request.graphql;
}
// Something went wrong in the policy.
if (policy) {
return policy;
}
// Resolver can be a function. Be also a native resolver or a controller's action.
if (_.isFunction(resolver)) {
context.params = Query.convertToParams(options.input.where || {});
context.request.body = options.input.data || {};
if (isController) {
const values = await resolver.call(null, context);
if (ctx.body) {
return {
[pluralize.singular(name)]: ctx.body,
};
}
const body = values && values.toJSON ? values.toJSON() : values;
return {
[pluralize.singular(name)]: body,
};
}
return resolver.call(null, obj, options, context);
}
// Resolver can be a promise.
return resolver;
};
},
};
|
packages/strapi-plugin-graphql/services/Mutation.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017322655185125768,
0.0001704075839370489,
0.0001655719242990017,
0.00017072849732358009,
0.000001690800672804471
] |
{
"id": 9,
"code_window": [
"\n",
"export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function\n",
" render() {\n",
" return (\n",
" <div>\n",
" <FullStory org=\"GK708\" />\n",
" <NotificationProvider />\n",
" <AppLoader>\n",
" {({ shouldLoad }) => {\n",
" if (shouldLoad) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-admin/admin/src/containers/App/index.js",
"type": "replace",
"edit_start_line_idx": 29
}
|
const _ = require('lodash');
module.exports = async (ctx, next) => {
const { source } = ctx.request.query;
if (source && _.get(strapi.plugins, [source, 'config', 'layout', ctx.params.model, 'actions', ctx.request.route.action])) {
const [ controller, action ] = _.get(strapi.plugins, [source, 'config', 'layout', ctx.params.model, 'actions', ctx.request.route.action], []).split('.');
if (controller && action) {
// Redirect to specific controller.
if (ctx.request.body.hasOwnProperty('fields') && ctx.request.body.hasOwnProperty('files')) {
let {files, fields} = ctx.request.body;
const parser = (value) => {
try {
value = JSON.parse(value);
} catch (e) {
// Silent.
}
return _.isArray(value) ? value.map(obj => parser(obj)) : value;
};
fields = Object.keys(fields).reduce((acc, current) => {
acc[current] = parser(fields[current]);
return acc;
}, {});
ctx.request.body = fields;
await strapi.plugins[source].controllers[controller.toLowerCase()][action](ctx);
const resBody = ctx.body;
await Promise.all(Object.keys(files).map(async field => {
ctx.request.body = {
files: {
files: files[field]
},
fields: {
refId: resBody.id || resBody._id,
ref: ctx.params.model,
source,
field
}
};
return strapi.plugins.upload.controllers.upload.upload(ctx);
}));
return ctx.send(resBody);
}
return await strapi.plugins[source].controllers[controller.toLowerCase()][action](ctx);
}
}
await next();
};
|
packages/strapi-plugin-content-manager/config/policies/routing.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017208961071446538,
0.00016985526599455625,
0.00016683815920259804,
0.00017068562738131732,
0.000001938964715009206
] |
{
"id": 9,
"code_window": [
"\n",
"export class App extends React.Component { // eslint-disable-line react/prefer-stateless-function\n",
" render() {\n",
" return (\n",
" <div>\n",
" <FullStory org=\"GK708\" />\n",
" <NotificationProvider />\n",
" <AppLoader>\n",
" {({ shouldLoad }) => {\n",
" if (shouldLoad) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/strapi-admin/admin/src/containers/App/index.js",
"type": "replace",
"edit_start_line_idx": 29
}
|
'use strict';
/**
* Module dependencies
*/
/**
* CSRF hook
*/
module.exports = strapi => {
return {
/**
* Initialize the hook
*/
initialize: function(cb) {
strapi.app.use(
async (ctx, next) => {
if (ctx.request.admin) return await next();
return await strapi.koaMiddlewares.convert(
strapi.koaMiddlewares.lusca.csrf({
key: strapi.config.middleware.settings.csrf.key,
secret: strapi.config.middleware.settings.csrf.secret
})
)(ctx, next);
}
);
cb();
}
};
};
|
packages/strapi/lib/middlewares/csrf/index.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.000183960422873497,
0.0001744731853250414,
0.00017113903595600277,
0.00017139664851129055,
0.000005480791060108459
] |
{
"id": 10,
"code_window": [
" },\n",
"\n",
" getGaConfig: async ctx => {\n",
" try {\n",
" const allowGa = _.get(strapi.config, 'info.customs.allowGa', true);\n",
" ctx.send({ allowGa });\n",
" } catch(err) {\n",
" ctx.badRequest(null, [{ messages: [{ id: 'An error occurred' }] }]);\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ctx.send({ uuid: _.get(strapi.config, 'uuid', false) });\n"
],
"file_path": "packages/strapi-admin/controllers/Admin.js",
"type": "replace",
"edit_start_line_idx": 30
}
|
# DISCLAIMER:
Google Analytics allows us to analyze the usage of Strapi. The aim is to
improve the product and helps us to understand how you interact with the Admin.
Note: The collected data are anonymous and aren't sold to anyone!
If you don't want to share your data with us, you can simply modify the `strapi` object in the package.json as follows:
```json
{
"strapi": {
"allowGa": false
}
}
```
|
packages/strapi-admin/doc/disable-tracking.md
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00028626888524740934,
0.00022502147476188838,
0.00016377406427636743,
0.00022502147476188838,
0.00006124741048552096
] |
{
"id": 10,
"code_window": [
" },\n",
"\n",
" getGaConfig: async ctx => {\n",
" try {\n",
" const allowGa = _.get(strapi.config, 'info.customs.allowGa', true);\n",
" ctx.send({ allowGa });\n",
" } catch(err) {\n",
" ctx.badRequest(null, [{ messages: [{ id: 'An error occurred' }] }]);\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ctx.send({ uuid: _.get(strapi.config, 'uuid', false) });\n"
],
"file_path": "packages/strapi-admin/controllers/Admin.js",
"type": "replace",
"edit_start_line_idx": 30
}
|
'use strict';
/**
* Creates Joi based object schemas from JSON
*/
module.exports = require('joi-json');
|
packages/strapi-utils/lib/joi-json.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017264513007830828,
0.00017264513007830828,
0.00017264513007830828,
0.00017264513007830828,
0
] |
{
"id": 10,
"code_window": [
" },\n",
"\n",
" getGaConfig: async ctx => {\n",
" try {\n",
" const allowGa = _.get(strapi.config, 'info.customs.allowGa', true);\n",
" ctx.send({ allowGa });\n",
" } catch(err) {\n",
" ctx.badRequest(null, [{ messages: [{ id: 'An error occurred' }] }]);\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ctx.send({ uuid: _.get(strapi.config, 'uuid', false) });\n"
],
"file_path": "packages/strapi-admin/controllers/Admin.js",
"type": "replace",
"edit_start_line_idx": 30
}
|
<?xml version="1.0" encoding="UTF-8"?>
<svg width="1078px" height="229px" viewBox="0 0 1078 229" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 46.2 (44496) - http://www.bohemiancoding.com/sketch -->
<title>Background image</title>
<desc>Created with Sketch.</desc>
<defs>
<rect id="path-1" x="-5.68434189e-14" y="0" width="1070" height="221" rx="2"></rect>
<filter x="-0.7%" y="-2.3%" width="101.3%" height="106.3%" filterUnits="objectBoundingBox" id="filter-3">
<feOffset dx="0" dy="2" in="SourceAlpha" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="2" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feColorMatrix values="0 0 0 0 0.890196078 0 0 0 0 0.91372549 0 0 0 0 0.952941176 0 0 0 1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
</defs>
<g id="Pages" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" opacity="0.5">
<g id="Content-Type-Builder---Home-view" transform="translate(-262.000000, -158.000000)">
<g id="Container" transform="translate(265.000000, 82.000000)">
<g id="Content">
<g id="Empty" transform="translate(1.000000, 78.000000)">
<g id="Background-image">
<mask id="mask-2" fill="white">
<use xlink:href="#path-1"></use>
</mask>
<g id="Background">
<use fill="black" fill-opacity="1" filter="url(#filter-3)" xlink:href="#path-1"></use>
<use fill="#FFFFFF" fill-rule="evenodd" xlink:href="#path-1"></use>
</g>
<g id="paint-brush" mask="url(#mask-2)" fill-rule="nonzero" fill="#F3F3F4">
<g transform="translate(25.000000, -12.000000)" id="Shape">
<path d="M225.558659,0 C232.07635,0 237.77933,2.16480447 242.667598,6.49441341 C247.555866,10.8240223 250,16.2476723 250,22.7653631 C250,28.6312849 247.905028,35.6610801 243.715084,43.8547486 C212.802607,102.420857 191.154562,137.430168 178.77095,148.882682 C169.739292,157.35568 159.590317,161.592179 148.324022,161.592179 C136.592179,161.592179 126.513035,157.285847 118.086592,148.673184 C109.660149,140.060521 105.446927,129.841713 105.446927,118.01676 C105.446927,106.098696 109.729981,96.2290503 118.296089,88.4078212 L207.402235,7.54189944 C212.895717,2.51396648 218.947858,0 225.558659,0 Z M98.603352,144.413408 C102.234637,151.489758 107.192737,157.541899 113.477654,162.569832 C119.76257,167.597765 126.769088,171.13594 134.497207,173.184358 L134.636872,183.100559 C135.009311,202.932961 128.980447,219.087523 116.550279,231.564246 C104.120112,244.040968 87.8957169,250.27933 67.877095,250.27933 C56.424581,250.27933 46.2756052,248.114525 37.4301676,243.784916 C28.58473,239.455307 21.4851024,233.519553 16.1312849,225.977654 C10.7774674,218.435754 6.75046555,209.916201 4.05027933,200.418994 C1.35009311,190.921788 0,180.679702 0,169.692737 C0.651769088,170.158287 2.56052142,171.554935 5.72625698,173.882682 C8.89199255,176.210428 11.7783985,178.282123 14.3854749,180.097765 C16.9925512,181.913408 19.7392924,183.612663 22.6256983,185.195531 C25.5121043,186.778399 27.6536313,187.569832 29.0502793,187.569832 C32.867784,187.569832 35.4283054,185.8473 36.7318436,182.402235 C39.0595903,176.256983 41.7364991,171.019553 44.7625698,166.689944 C47.7886406,162.360335 51.0242086,158.82216 54.4692737,156.075419 C57.9143389,153.328678 62.0111732,151.117318 66.7597765,149.441341 C71.5083799,147.765363 76.3035382,146.578212 81.1452514,145.879888 C85.9869646,145.181564 91.8063315,144.692737 98.603352,144.413408 Z"></path>
</g>
</g>
<rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" mask="url(#mask-2)" x="313" y="67" width="8" height="8" rx="4"></rect>
<rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" mask="url(#mask-2)" x="243" y="117" width="4" height="4" rx="2"></rect>
<rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" mask="url(#mask-2)" x="333" y="217" width="2" height="2" rx="1"></rect>
<rect id="Rectangle-9" fill="#F0F0F3" mask="url(#mask-2)" x="222" y="196" width="12" height="12" rx="5"></rect>
<rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" mask="url(#mask-2)" x="363" y="147" width="10" height="10" rx="5"></rect>
<rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" mask="url(#mask-2)" x="753" y="157" width="12" height="12" rx="6"></rect>
<rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" mask="url(#mask-2)" x="863" y="97" width="5" height="5" rx="2.5"></rect>
<rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" mask="url(#mask-2)" x="663" y="197" width="3" height="3" rx="1.5"></rect>
<rect id="Rectangle-9" fill="#F0F0F3" mask="url(#mask-2)" x="742" y="56" width="10" height="10" rx="5"></rect>
<rect id="Rectangle-9" fill="#F0F0F3" mask="url(#mask-2)" x="442" y="176" width="9" height="9" rx="4.5"></rect>
<g id="star" mask="url(#mask-2)" fill-rule="nonzero" fill="#E3E3E5">
<g transform="translate(629.000000, 121.000000)" id="Shape">
<path d="M10,3.69591346 C10,3.78405449 9.94791667,3.88020833 9.84375,3.984375 L7.66225962,6.11177885 L8.17908654,9.11658654 C8.18309295,9.14463141 8.18509615,9.18469551 8.18509615,9.23677885 C8.18509615,9.32091346 8.1640625,9.39202724 8.12199519,9.45012019 C8.07992788,9.50821314 8.01883013,9.53725962 7.93870192,9.53725962 C7.86258013,9.53725962 7.78245192,9.51322115 7.69831731,9.46514423 L5,8.046875 L2.30168269,9.46514423 C2.21354167,9.51322115 2.13341346,9.53725962 2.06129808,9.53725962 C1.97716346,9.53725962 1.9140625,9.50821314 1.87199519,9.45012019 C1.82992788,9.39202724 1.80889423,9.32091346 1.80889423,9.23677885 C1.80889423,9.21274038 1.81290064,9.17267628 1.82091346,9.11658654 L2.33774038,6.11177885 L0.150240385,3.984375 C0.0500801282,3.87620192 0,3.78004808 0,3.69591346 C0,3.54767628 0.112179487,3.45552885 0.336538462,3.41947115 L3.35336538,2.98076923 L4.70552885,0.246394231 C4.78165064,0.0821314103 4.87980769,0 5,0 C5.12019231,0 5.21834936,0.0821314103 5.29447115,0.246394231 L6.64663462,2.98076923 L9.66346154,3.41947115 C9.88782051,3.45552885 10,3.54767628 10,3.69591346 Z"></path>
</g>
</g>
<g id="star" mask="url(#mask-2)" fill-rule="nonzero" fill="#E3E3E5">
<g transform="translate(389.000000, 1.000000)" id="Shape">
<path d="M10,3.69591346 C10,3.78405449 9.94791667,3.88020833 9.84375,3.984375 L7.66225962,6.11177885 L8.17908654,9.11658654 C8.18309295,9.14463141 8.18509615,9.18469551 8.18509615,9.23677885 C8.18509615,9.32091346 8.1640625,9.39202724 8.12199519,9.45012019 C8.07992788,9.50821314 8.01883013,9.53725962 7.93870192,9.53725962 C7.86258013,9.53725962 7.78245192,9.51322115 7.69831731,9.46514423 L5,8.046875 L2.30168269,9.46514423 C2.21354167,9.51322115 2.13341346,9.53725962 2.06129808,9.53725962 C1.97716346,9.53725962 1.9140625,9.50821314 1.87199519,9.45012019 C1.82992788,9.39202724 1.80889423,9.32091346 1.80889423,9.23677885 C1.80889423,9.21274038 1.81290064,9.17267628 1.82091346,9.11658654 L2.33774038,6.11177885 L0.150240385,3.984375 C0.0500801282,3.87620192 0,3.78004808 0,3.69591346 C0,3.54767628 0.112179487,3.45552885 0.336538462,3.41947115 L3.35336538,2.98076923 L4.70552885,0.246394231 C4.78165064,0.0821314103 4.87980769,0 5,0 C5.12019231,0 5.21834936,0.0821314103 5.29447115,0.246394231 L6.64663462,2.98076923 L9.66346154,3.41947115 C9.88782051,3.45552885 10,3.54767628 10,3.69591346 Z"></path>
</g>
</g>
</g>
</g>
</g>
</g>
</g>
</g>
</svg>
|
packages/strapi-plugin-content-type-builder/admin/src/assets/images/background_paint.svg
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017596925317775458,
0.00017192614905070513,
0.00016599429363850504,
0.00017210330406669527,
0.0000031657039016863564
] |
{
"id": 10,
"code_window": [
" },\n",
"\n",
" getGaConfig: async ctx => {\n",
" try {\n",
" const allowGa = _.get(strapi.config, 'info.customs.allowGa', true);\n",
" ctx.send({ allowGa });\n",
" } catch(err) {\n",
" ctx.badRequest(null, [{ messages: [{ id: 'An error occurred' }] }]);\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ctx.send({ uuid: _.get(strapi.config, 'uuid', false) });\n"
],
"file_path": "packages/strapi-admin/controllers/Admin.js",
"type": "replace",
"edit_start_line_idx": 30
}
|
/*
* NotFoundPage Messages
*
* This contains all the text for the NotFoundPage component.
*/
import { defineMessages } from 'react-intl';
export default defineMessages({
pageNotFound: {
id: 'app.components.NotFoundPage.pageNotFound',
defaultMessage: 'Page not found.',
},
});
|
packages/strapi-plugin-settings-manager/admin/src/containers/NotFoundPage/messages.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017416346236132085,
0.0001723706373013556,
0.00017057779768947512,
0.0001723706373013556,
0.000001792832335922867
] |
{
"id": 11,
"code_window": [
"If you don't want to share your data with us, you can simply modify the `strapi` object in the package.json as follows:\n",
"\n",
"```json\n",
"{\n",
" \"strapi\": {\n",
" \"allowGa\": false\n",
" }\n",
"}\n",
"```"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"uuid\": false\n"
],
"file_path": "packages/strapi-admin/doc/disable-tracking.md",
"type": "replace",
"edit_start_line_idx": 12
}
|
import { all, fork, call, put, select, takeLatest } from 'redux-saga/effects';
import auth from 'utils/auth';
import request from 'utils/request';
import { makeSelectAppPlugins } from 'containers/App/selectors';
import {
getAdminDataSucceeded,
} from './actions';
import { GET_ADMIN_DATA } from './constants';
function* getData() {
try {
const appPlugins = yield select(makeSelectAppPlugins());
const hasUserPlugin = appPlugins.indexOf('users-permissions') !== -1;
if (hasUserPlugin && auth.getToken() !== null) {
yield call(request, `${strapi.backendURL}/users/me`, { method: 'GET' });
}
const [{ allowGa }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([
call(request, '/admin/gaConfig', { method: 'GET' }),
call(request, '/admin/strapiVersion', { method: 'GET' }),
call(request, '/admin/currentEnvironment', { method: 'GET' }),
call(request, '/admin/layout', { method: 'GET' }),
]);
yield put(getAdminDataSucceeded({ allowGa, strapiVersion, currentEnvironment, layout }));
} catch(err) {
console.log(err); // eslint-disable-line no-console
}
}
function* defaultSaga() {
yield all([
fork(takeLatest, GET_ADMIN_DATA, getData),
]);
}
export default defaultSaga;
|
packages/strapi-admin/admin/src/containers/AdminPage/saga.js
| 1 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.0034453850239515305,
0.001131168333813548,
0.0001683408918324858,
0.0004554734332486987,
0.0013562662061303854
] |
{
"id": 11,
"code_window": [
"If you don't want to share your data with us, you can simply modify the `strapi` object in the package.json as follows:\n",
"\n",
"```json\n",
"{\n",
" \"strapi\": {\n",
" \"allowGa\": false\n",
" }\n",
"}\n",
"```"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"uuid\": false\n"
],
"file_path": "packages/strapi-admin/doc/disable-tracking.md",
"type": "replace",
"edit_start_line_idx": 12
}
|
/*eslint-disable*/
// No need to build the DLL in production
if (process.env.NODE_ENV === 'production') {
process.exit(0);
}
require('shelljs/global');
const path = require('path');
const fs = require('fs');
const exists = fs.existsSync;
const writeFile = fs.writeFileSync;
const defaults = require('lodash/defaultsDeep');
const pkg = require(path.join(process.cwd(), 'package.json'));
const config = require('../config');
const dllConfig = defaults(pkg.dllPlugin, config.dllPlugin.defaults);
const outputPath = path.join(process.cwd(), dllConfig.path);
const dllManifestPath = path.join(outputPath, 'package.json');
/**
* I use node_modules/strapi-plugin-dlls by default just because
* it isn't going to be version controlled and babel wont try to parse it.
*/
mkdir('-p', outputPath);
echo('Building the Webpack DLL...');
/**
* Create a manifest so npm install doesnt warn us
*/
if (!exists(dllManifestPath)) {
writeFile(
dllManifestPath,
JSON.stringify(defaults({
name: 'strapi-plugin-dlls',
private: true,
author: pkg.author,
repository: pkg.repository,
version: pkg.version
}), null, 2),
'utf8'
)
}
// the BUILDING_DLL env var is set to avoid confusing the development environment
exec('./node_modules/strapi-helper-plugin/node_modules/cross-env/bin/cross-env.js BUILDING_DLL=true ./node_modules/strapi-helper-plugin/node_modules/webpack/bin/webpack.js --display-chunks --color --config ./node_modules/strapi-helper-plugin/lib/internals/webpack/webpack.dll.babel.js');
|
packages/strapi-helper-plugin/lib/internals/scripts/dependencies.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.001448382856324315,
0.0006614059093408287,
0.00016616737411823124,
0.00021983009355608374,
0.0005864486447535455
] |
{
"id": 11,
"code_window": [
"If you don't want to share your data with us, you can simply modify the `strapi` object in the package.json as follows:\n",
"\n",
"```json\n",
"{\n",
" \"strapi\": {\n",
" \"allowGa\": false\n",
" }\n",
"}\n",
"```"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"uuid\": false\n"
],
"file_path": "packages/strapi-admin/doc/disable-tracking.md",
"type": "replace",
"edit_start_line_idx": 12
}
|
/**
*
* WysiwygDropUpload
*
*/
import React from 'react';
import styles from './styles.scss';
/* eslint-disable jsx-a11y/label-has-for */
const WysiwygDropUpload = (props) => {
return (
<label
{...props}
className={styles.wysiwygDropUpload}
>
<input
onChange={() => {}}
type="file"
tabIndex="-1"
/>
</label>
);
};
export default WysiwygDropUpload;
|
packages/strapi-plugin-content-manager/admin/src/components/WysiwygDropUpload/index.js
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.00017203004972543567,
0.00016798346769064665,
0.00016499258344992995,
0.0001669277553446591,
0.0000029684306355193257
] |
{
"id": 11,
"code_window": [
"If you don't want to share your data with us, you can simply modify the `strapi` object in the package.json as follows:\n",
"\n",
"```json\n",
"{\n",
" \"strapi\": {\n",
" \"allowGa\": false\n",
" }\n",
"}\n",
"```"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"uuid\": false\n"
],
"file_path": "packages/strapi-admin/doc/disable-tracking.md",
"type": "replace",
"edit_start_line_idx": 12
}
|
{
"session": {
"enabled": true,
"client": "cookie",
"key": "strapi.sid",
"prefix": "strapi:sess:",
"secretKeys": ["mySecretKey1", "mySecretKey2"],
"httpOnly": true,
"maxAge": 86400000,
"overwrite": true,
"signed": false,
"rolling": false
},
"logger": {
"level": "info",
"exposeInContext": true,
"requests": false
},
"parser": {
"enabled": true,
"multipart": true
}
}
|
packages/strapi-generate-new/files/config/environments/production/request.json
| 0 |
https://github.com/strapi/strapi/commit/4ad6417e6275d9516c7e7fa4e5e663d13f7b6c5d
|
[
0.0007610498578287661,
0.0003652366285677999,
0.00016690068878233433,
0.00016775923722889274,
0.0002798824571073055
] |
{
"id": 0,
"code_window": [
"import PropTypes from 'prop-types';\n",
"import { refType } from '@mui/utils';\n",
"import { unstable_composeClasses as composeClasses } from '@mui/base';\n",
"import NotchedOutline from './NotchedOutline';\n",
"import styled, { rootShouldForwardProp } from '../styles/styled';\n",
"import outlinedInputClasses, { getOutlinedInputUtilityClass } from './outlinedInputClasses';\n",
"import InputBase, {\n",
" rootOverridesResolver as inputBaseRootOverridesResolver,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import useFormControl from '../FormControl/useFormControl';\n",
"import formControlState from '../FormControl/formControlState';\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "add",
"edit_start_line_idx": 5
}
|
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses } from '@mui/base';
import { refType, unstable_useId as useId } from '@mui/utils';
import styled from '../styles/styled';
import useThemeProps from '../styles/useThemeProps';
import Input from '../Input';
import FilledInput from '../FilledInput';
import OutlinedInput from '../OutlinedInput';
import InputLabel from '../InputLabel';
import FormControl from '../FormControl';
import FormHelperText from '../FormHelperText';
import Select from '../Select';
import { getTextFieldUtilityClass } from './textFieldClasses';
const variantComponent = {
standard: Input,
filled: FilledInput,
outlined: OutlinedInput,
};
const useUtilityClasses = (ownerState) => {
const { classes } = ownerState;
const slots = {
root: ['root'],
};
return composeClasses(slots, getTextFieldUtilityClass, classes);
};
const TextFieldRoot = styled(FormControl, {
name: 'MuiTextField',
slot: 'Root',
overridesResolver: (props, styles) => styles.root,
})({});
/**
* The `TextField` is a convenience wrapper for the most common cases (80%).
* It cannot be all things to all people, otherwise the API would grow out of control.
*
* ## Advanced Configuration
*
* It's important to understand that the text field is a simple abstraction
* on top of the following components:
*
* - [FormControl](/api/form-control/)
* - [InputLabel](/api/input-label/)
* - [FilledInput](/api/filled-input/)
* - [OutlinedInput](/api/outlined-input/)
* - [Input](/api/input/)
* - [FormHelperText](/api/form-helper-text/)
*
* If you wish to alter the props applied to the `input` element, you can do so as follows:
*
* ```jsx
* const inputProps = {
* step: 300,
* };
*
* return <TextField id="time" type="time" inputProps={inputProps} />;
* ```
*
* For advanced cases, please look at the source of TextField by clicking on the
* "Edit this page" button above. Consider either:
*
* - using the upper case props for passing values directly to the components
* - using the underlying components directly as shown in the demos
*/
const TextField = React.forwardRef(function TextField(inProps, ref) {
const props = useThemeProps({ props: inProps, name: 'MuiTextField' });
const {
autoComplete,
autoFocus = false,
children,
className,
color = 'primary',
defaultValue,
disabled = false,
error = false,
FormHelperTextProps,
fullWidth = false,
helperText,
id: idOverride,
InputLabelProps,
inputProps,
InputProps,
inputRef,
label,
maxRows,
minRows,
multiline = false,
name,
onBlur,
onChange,
onFocus,
placeholder,
required = false,
rows,
select = false,
SelectProps,
type,
value,
variant = 'outlined',
...other
} = props;
const ownerState = {
...props,
autoFocus,
color,
disabled,
error,
fullWidth,
multiline,
required,
select,
variant,
};
const classes = useUtilityClasses(ownerState);
if (process.env.NODE_ENV !== 'production') {
if (select && !children) {
console.error(
'MUI: `children` must be passed when using the `TextField` component with `select`.',
);
}
}
const InputMore = {};
if (variant === 'outlined') {
if (InputLabelProps && typeof InputLabelProps.shrink !== 'undefined') {
InputMore.notched = InputLabelProps.shrink;
}
if (label) {
const displayRequired = InputLabelProps?.required ?? required;
InputMore.label = (
<React.Fragment>
{label}
{displayRequired && '\u00a0*'}
</React.Fragment>
);
}
}
if (select) {
// unset defaults from textbox inputs
if (!SelectProps || !SelectProps.native) {
InputMore.id = undefined;
}
InputMore['aria-describedby'] = undefined;
}
const id = useId(idOverride);
const helperTextId = helperText && id ? `${id}-helper-text` : undefined;
const inputLabelId = label && id ? `${id}-label` : undefined;
const InputComponent = variantComponent[variant];
const InputElement = (
<InputComponent
aria-describedby={helperTextId}
autoComplete={autoComplete}
autoFocus={autoFocus}
defaultValue={defaultValue}
fullWidth={fullWidth}
multiline={multiline}
name={name}
rows={rows}
maxRows={maxRows}
minRows={minRows}
type={type}
value={value}
id={id}
inputRef={inputRef}
onBlur={onBlur}
onChange={onChange}
onFocus={onFocus}
placeholder={placeholder}
inputProps={inputProps}
{...InputMore}
{...InputProps}
/>
);
return (
<TextFieldRoot
className={clsx(classes.root, className)}
disabled={disabled}
error={error}
fullWidth={fullWidth}
ref={ref}
required={required}
color={color}
variant={variant}
ownerState={ownerState}
{...other}
>
{label && (
<InputLabel htmlFor={id} id={inputLabelId} {...InputLabelProps}>
{label}
</InputLabel>
)}
{select ? (
<Select
aria-describedby={helperTextId}
id={id}
labelId={inputLabelId}
value={value}
input={InputElement}
{...SelectProps}
>
{children}
</Select>
) : (
InputElement
)}
{helperText && (
<FormHelperText id={helperTextId} {...FormHelperTextProps}>
{helperText}
</FormHelperText>
)}
</TextFieldRoot>
);
});
TextField.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the `input` element is focused during the first mount.
* @default false
*/
autoFocus: PropTypes.bool,
/**
* @ignore
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* @default 'primary'
*/
color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['primary', 'secondary', 'error', 'info', 'success', 'warning']),
PropTypes.string,
]),
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the component is disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, the label is displayed in an error state.
* @default false
*/
error: PropTypes.bool,
/**
* Props applied to the [`FormHelperText`](/api/form-helper-text/) element.
*/
FormHelperTextProps: PropTypes.object,
/**
* If `true`, the input will take up the full width of its container.
* @default false
*/
fullWidth: PropTypes.bool,
/**
* The helper text content.
*/
helperText: PropTypes.node,
/**
* The id of the `input` element.
* Use this prop to make `label` and `helperText` accessible for screen readers.
*/
id: PropTypes.string,
/**
* Props applied to the [`InputLabel`](/api/input-label/) element.
*/
InputLabelProps: PropTypes.object,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Props applied to the Input element.
* It will be a [`FilledInput`](/api/filled-input/),
* [`OutlinedInput`](/api/outlined-input/) or [`Input`](/api/input/)
* component depending on the `variant` prop value.
*/
InputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* The label content.
*/
label: PropTypes.node,
/**
* If `dense` or `normal`, will adjust vertical spacing of this and contained components.
* @default 'none'
*/
margin: PropTypes.oneOf(['dense', 'none', 'normal']),
/**
* Maximum number of rows to display when multiline option is set to true.
*/
maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Minimum number of rows to display when multiline option is set to true.
*/
minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* If `true`, a `textarea` element is rendered instead of an input.
* @default false
*/
multiline: PropTypes.bool,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired when the value is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* The short hint displayed in the `input` before the user enters a value.
*/
placeholder: PropTypes.string,
/**
* If `true`, the label is displayed as required and the `input` element is required.
* @default false
*/
required: PropTypes.bool,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Render a [`Select`](/api/select/) element while passing the Input element to `Select` as `input` parameter.
* If this option is set you must pass the options of the select as children.
* @default false
*/
select: PropTypes.bool,
/**
* Props applied to the [`Select`](/api/select/) element.
*/
SelectProps: PropTypes.object,
/**
* The size of the component.
*/
size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['medium', 'small']),
PropTypes.string,
]),
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])),
PropTypes.func,
PropTypes.object,
]),
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
*/
type: PropTypes /* @typescript-to-proptypes-ignore */.string,
/**
* The value of the `input` element, required for a controlled component.
*/
value: PropTypes.any,
/**
* The variant to use.
* @default 'outlined'
*/
variant: PropTypes.oneOf(['filled', 'outlined', 'standard']),
};
export default TextField;
|
packages/mui-material/src/TextField/TextField.js
| 1 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.004519924987107515,
0.00030237488681450486,
0.00016126369882840663,
0.00016725044406484812,
0.000678159121889621
] |
{
"id": 0,
"code_window": [
"import PropTypes from 'prop-types';\n",
"import { refType } from '@mui/utils';\n",
"import { unstable_composeClasses as composeClasses } from '@mui/base';\n",
"import NotchedOutline from './NotchedOutline';\n",
"import styled, { rootShouldForwardProp } from '../styles/styled';\n",
"import outlinedInputClasses, { getOutlinedInputUtilityClass } from './outlinedInputClasses';\n",
"import InputBase, {\n",
" rootOverridesResolver as inputBaseRootOverridesResolver,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import useFormControl from '../FormControl/useFormControl';\n",
"import formControlState from '../FormControl/formControlState';\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "add",
"edit_start_line_idx": 5
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M12 4h2v2h-2V4zM7 14H5v-2h2v2zm12 6h-2v-2h2v2z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M15 16v1.26l-6-3v-3.17L11.7 8H16V2h-6v4.9L7.3 10H3v6h5l7 3.5V22h6v-6h-6zM12 4h2v2h-2V4zM7 14H5v-2h2v2zm12 6h-2v-2h2v2z"
}, "1")], 'PolylineTwoTone');
|
packages/mui-icons-material/lib/esm/PolylineTwoTone.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.0001762184256222099,
0.0001762184256222099,
0.0001762184256222099,
0.0001762184256222099,
0
] |
{
"id": 0,
"code_window": [
"import PropTypes from 'prop-types';\n",
"import { refType } from '@mui/utils';\n",
"import { unstable_composeClasses as composeClasses } from '@mui/base';\n",
"import NotchedOutline from './NotchedOutline';\n",
"import styled, { rootShouldForwardProp } from '../styles/styled';\n",
"import outlinedInputClasses, { getOutlinedInputUtilityClass } from './outlinedInputClasses';\n",
"import InputBase, {\n",
" rootOverridesResolver as inputBaseRootOverridesResolver,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import useFormControl from '../FormControl/useFormControl';\n",
"import formControlState from '../FormControl/formControlState';\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "add",
"edit_start_line_idx": 5
}
|
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><path d="M20,10V8h-4V4h-2v4h-4V4H8v4H4v2h4v4H4v2h4v4h2v-4h4v4h2v-4h4v-2h-4v-4H20z M14,14h-4v-4h4V14z"/></g></svg>
|
packages/mui-icons-material/material-icons/tag_sharp_24px.svg
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.00017132631910499185,
0.00017132631910499185,
0.00017132631910499185,
0.00017132631910499185,
0
] |
{
"id": 0,
"code_window": [
"import PropTypes from 'prop-types';\n",
"import { refType } from '@mui/utils';\n",
"import { unstable_composeClasses as composeClasses } from '@mui/base';\n",
"import NotchedOutline from './NotchedOutline';\n",
"import styled, { rootShouldForwardProp } from '../styles/styled';\n",
"import outlinedInputClasses, { getOutlinedInputUtilityClass } from './outlinedInputClasses';\n",
"import InputBase, {\n",
" rootOverridesResolver as inputBaseRootOverridesResolver,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import useFormControl from '../FormControl/useFormControl';\n",
"import formControlState from '../FormControl/formControlState';\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "add",
"edit_start_line_idx": 5
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M14.75 6c-1.37 0-2.5 1.52-2.5 3.4 0 1.48.7 2.71 1.67 3.18l.08.04V19h1.5v-6.38l.08-.03c.97-.47 1.67-1.7 1.67-3.18 0-1.88-1.12-3.41-2.5-3.41M10.5 6c-.27 0-.5.22-.5.5V9h-.75V6.5c0-.28-.22-.5-.5-.5s-.5.22-.5.5V9H7.5V6.5c0-.28-.22-.5-.5-.5s-.5.22-.5.5v3.8c0 .93.64 1.71 1.5 1.93V19h1.5v-6.77c.86-.22 1.5-1 1.5-1.93V6.5c0-.28-.22-.5-.5-.5zM20 4H4v16h16V4m0-2c1.1 0 2 .9 2 2v16c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h16z"
}), 'DiningOutlined');
|
packages/mui-icons-material/lib/esm/DiningOutlined.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.0002660262689460069,
0.0002660262689460069,
0.0002660262689460069,
0.0002660262689460069,
0
] |
{
"id": 1,
"code_window": [
" ...other\n",
" } = props;\n",
"\n",
" const classes = useUtilityClasses(props);\n",
"\n",
" return (\n",
" <InputBase\n",
" components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }}\n",
" renderSuffix={(state) => (\n",
" <NotchedOutlineRoot\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const muiFormControl = useFormControl();\n",
" const fcs = formControlState({\n",
" props,\n",
" muiFormControl,\n",
" states: ['required'],\n",
" });\n",
"\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "add",
"edit_start_line_idx": 126
}
|
import * as React from 'react';
import PropTypes from 'prop-types';
import { refType } from '@mui/utils';
import { unstable_composeClasses as composeClasses } from '@mui/base';
import NotchedOutline from './NotchedOutline';
import styled, { rootShouldForwardProp } from '../styles/styled';
import outlinedInputClasses, { getOutlinedInputUtilityClass } from './outlinedInputClasses';
import InputBase, {
rootOverridesResolver as inputBaseRootOverridesResolver,
inputOverridesResolver as inputBaseInputOverridesResolver,
InputBaseRoot,
InputBaseComponent as InputBaseInput,
} from '../InputBase/InputBase';
import useThemeProps from '../styles/useThemeProps';
const useUtilityClasses = (ownerState) => {
const { classes } = ownerState;
const slots = {
root: ['root'],
notchedOutline: ['notchedOutline'],
input: ['input'],
};
const composedClasses = composeClasses(slots, getOutlinedInputUtilityClass, classes);
return {
...classes, // forward classes to the InputBase
...composedClasses,
};
};
const OutlinedInputRoot = styled(InputBaseRoot, {
shouldForwardProp: (prop) => rootShouldForwardProp(prop) || prop === 'classes',
name: 'MuiOutlinedInput',
slot: 'Root',
overridesResolver: inputBaseRootOverridesResolver,
})(({ theme, ownerState }) => {
const borderColor =
theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';
return {
position: 'relative',
borderRadius: theme.shape.borderRadius,
[`&:hover .${outlinedInputClasses.notchedOutline}`]: {
borderColor: theme.palette.text.primary,
},
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
[`&:hover .${outlinedInputClasses.notchedOutline}`]: {
borderColor,
},
},
[`&.${outlinedInputClasses.focused} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: theme.palette[ownerState.color].main,
borderWidth: 2,
},
[`&.${outlinedInputClasses.error} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: theme.palette.error.main,
},
[`&.${outlinedInputClasses.disabled} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: theme.palette.action.disabled,
},
...(ownerState.startAdornment && {
paddingLeft: 14,
}),
...(ownerState.endAdornment && {
paddingRight: 14,
}),
...(ownerState.multiline && {
padding: '16.5px 14px',
...(ownerState.size === 'small' && {
padding: '8.5px 14px',
}),
}),
};
});
const NotchedOutlineRoot = styled(NotchedOutline, {
name: 'MuiOutlinedInput',
slot: 'NotchedOutline',
overridesResolver: (props, styles) => styles.notchedOutline,
})(({ theme }) => ({
borderColor: theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)',
}));
const OutlinedInputInput = styled(InputBaseInput, {
name: 'MuiOutlinedInput',
slot: 'Input',
overridesResolver: inputBaseInputOverridesResolver,
})(({ theme, ownerState }) => ({
padding: '16.5px 14px',
'&:-webkit-autofill': {
WebkitBoxShadow: theme.palette.mode === 'light' ? null : '0 0 0 100px #266798 inset',
WebkitTextFillColor: theme.palette.mode === 'light' ? null : '#fff',
caretColor: theme.palette.mode === 'light' ? null : '#fff',
borderRadius: 'inherit',
},
...(ownerState.size === 'small' && {
padding: '8.5px 14px',
}),
...(ownerState.multiline && {
padding: 0,
}),
...(ownerState.startAdornment && {
paddingLeft: 0,
}),
...(ownerState.endAdornment && {
paddingRight: 0,
}),
}));
const OutlinedInput = React.forwardRef(function OutlinedInput(inProps, ref) {
const props = useThemeProps({ props: inProps, name: 'MuiOutlinedInput' });
const {
components = {},
fullWidth = false,
inputComponent = 'input',
label,
multiline = false,
notched,
type = 'text',
...other
} = props;
const classes = useUtilityClasses(props);
return (
<InputBase
components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }}
renderSuffix={(state) => (
<NotchedOutlineRoot
className={classes.notchedOutline}
label={label}
notched={
typeof notched !== 'undefined'
? notched
: Boolean(state.startAdornment || state.filled || state.focused)
}
/>
)}
fullWidth={fullWidth}
inputComponent={inputComponent}
multiline={multiline}
ref={ref}
type={type}
{...other}
classes={{
...classes,
notchedOutline: null,
}}
/>
);
});
OutlinedInput.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the `input` element is focused during the first mount.
*/
autoFocus: PropTypes.bool,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* The prop defaults to the value (`'primary'`) inherited from the parent FormControl component.
*/
color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['primary', 'secondary']),
PropTypes.string,
]),
/**
* The components used for each slot inside the InputBase.
* Either a string to use a HTML element or a component.
* @default {}
*/
components: PropTypes.shape({
Input: PropTypes.elementType,
Root: PropTypes.elementType,
}),
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the component is disabled.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
disabled: PropTypes.bool,
/**
* End `InputAdornment` for this component.
*/
endAdornment: PropTypes.node,
/**
* If `true`, the `input` will indicate an error.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
error: PropTypes.bool,
/**
* If `true`, the `input` will take up the full width of its container.
* @default false
*/
fullWidth: PropTypes.bool,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* The component used for the `input` element.
* Either a string to use a HTML element or a component.
* @default 'input'
*/
inputComponent: PropTypes.elementType,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
* @default {}
*/
inputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* The label of the `input`. It is only used for layout. The actual labelling
* is handled by `InputLabel`.
*/
label: PropTypes.node,
/**
* If `dense`, will adjust vertical spacing. This is normally obtained via context from
* FormControl.
* The prop defaults to the value (`'none'`) inherited from the parent FormControl component.
*/
margin: PropTypes.oneOf(['dense', 'none']),
/**
* Maximum number of rows to display when multiline option is set to true.
*/
maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Minimum number of rows to display when multiline option is set to true.
*/
minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* If `true`, a `textarea` element is rendered.
* @default false
*/
multiline: PropTypes.bool,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* If `true`, the outline is notched to accommodate the label.
*/
notched: PropTypes.bool,
/**
* Callback fired when the value is changed.
*
* @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* The short hint displayed in the `input` before the user enters a value.
*/
placeholder: PropTypes.string,
/**
* It prevents the user from changing the value of the field
* (not from interacting with the field).
*/
readOnly: PropTypes.bool,
/**
* If `true`, the `input` element is required.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
required: PropTypes.bool,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Start `InputAdornment` for this component.
*/
startAdornment: PropTypes.node,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])),
PropTypes.func,
PropTypes.object,
]),
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
* @default 'text'
*/
type: PropTypes.string,
/**
* The value of the `input` element, required for a controlled component.
*/
value: PropTypes.any,
};
OutlinedInput.muiName = 'Input';
export default OutlinedInput;
|
packages/mui-material/src/OutlinedInput/OutlinedInput.js
| 1 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.9981179237365723,
0.06521504372358322,
0.0001599102542968467,
0.00017391661822330207,
0.23650771379470825
] |
{
"id": 1,
"code_window": [
" ...other\n",
" } = props;\n",
"\n",
" const classes = useUtilityClasses(props);\n",
"\n",
" return (\n",
" <InputBase\n",
" components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }}\n",
" renderSuffix={(state) => (\n",
" <NotchedOutlineRoot\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const muiFormControl = useFormControl();\n",
" const fcs = formControlState({\n",
" props,\n",
" muiFormControl,\n",
" states: ['required'],\n",
" });\n",
"\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "add",
"edit_start_line_idx": 126
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 4C7.31 4 3.07 5.9 0 8.98L12 21 24 8.98C20.93 5.9 16.69 4 12 4zM2.92 9.07C5.51 7.08 8.67 6 12 6s6.49 1.08 9.08 3.07L12 18.17l-9.08-9.1z"
}), 'SignalWifi0BarTwoTone');
|
packages/mui-icons-material/lib/esm/SignalWifi0BarTwoTone.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.00017503148410469294,
0.00017503148410469294,
0.00017503148410469294,
0.00017503148410469294,
0
] |
{
"id": 1,
"code_window": [
" ...other\n",
" } = props;\n",
"\n",
" const classes = useUtilityClasses(props);\n",
"\n",
" return (\n",
" <InputBase\n",
" components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }}\n",
" renderSuffix={(state) => (\n",
" <NotchedOutlineRoot\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const muiFormControl = useFormControl();\n",
" const fcs = formControlState({\n",
" props,\n",
" muiFormControl,\n",
" states: ['required'],\n",
" });\n",
"\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "add",
"edit_start_line_idx": 126
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M19 15.18V7c0-2.21-1.79-4-4-4s-4 1.79-4 4v10c0 1.1-.9 2-2 2s-2-.9-2-2V8.82C8.16 8.4 9 7.3 9 6c0-1.66-1.34-3-3-3S3 4.34 3 6c0 1.3.84 2.4 2 2.82V17c0 2.21 1.79 4 4 4s4-1.79 4-4V7c0-1.1.9-2 2-2s2 .9 2 2v8.18c-1.16.41-2 1.51-2 2.82 0 1.66 1.34 3 3 3s3-1.34 3-3c0-1.3-.84-2.4-2-2.82z"
}), 'Route');
exports.default = _default;
|
packages/mui-icons-material/lib/Route.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.00017663714243099093,
0.0001725867623463273,
0.00016853636770974845,
0.0001725867623463273,
0.000004050387360621244
] |
{
"id": 1,
"code_window": [
" ...other\n",
" } = props;\n",
"\n",
" const classes = useUtilityClasses(props);\n",
"\n",
" return (\n",
" <InputBase\n",
" components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }}\n",
" renderSuffix={(state) => (\n",
" <NotchedOutlineRoot\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const muiFormControl = useFormControl();\n",
" const fcs = formControlState({\n",
" props,\n",
" muiFormControl,\n",
" states: ['required'],\n",
" });\n",
"\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "add",
"edit_start_line_idx": 126
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M21.98 11 24 8.98C20.93 5.9 16.69 4 12 4S3.07 5.9 0 8.98l6.35 6.36L12 21l3.05-3.05V15c0-.45.09-.88.23-1.29.54-1.57 2.01-2.71 3.77-2.71h2.93z"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M22 16v-1c0-1.1-.9-2-2-2s-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1zm-1 0h-2v-1c0-.55.45-1 1-1s1 .45 1 1v1z"
}, "1")], 'SignalWifi4BarLockTwoTone');
exports.default = _default;
|
packages/mui-icons-material/lib/SignalWifi4BarLockTwoTone.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.00017663714243099093,
0.0001720621803542599,
0.00016434240387752652,
0.00017520698020234704,
0.000005489839168149047
] |
{
"id": 2,
"code_window": [
" <InputBase\n",
" components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }}\n",
" renderSuffix={(state) => (\n",
" <NotchedOutlineRoot\n",
" className={classes.notchedOutline}\n",
" label={label}\n",
" notched={\n",
" typeof notched !== 'undefined'\n",
" ? notched\n",
" : Boolean(state.startAdornment || state.filled || state.focused)\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" label={\n",
" label && fcs.required ? (\n",
" <React.Fragment>\n",
" {label}\n",
" {'*'}\n",
" </React.Fragment>\n",
" ) : (\n",
" label\n",
" )\n",
" }\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "replace",
"edit_start_line_idx": 132
}
|
import * as React from 'react';
import PropTypes from 'prop-types';
import { refType } from '@mui/utils';
import { unstable_composeClasses as composeClasses } from '@mui/base';
import NotchedOutline from './NotchedOutline';
import styled, { rootShouldForwardProp } from '../styles/styled';
import outlinedInputClasses, { getOutlinedInputUtilityClass } from './outlinedInputClasses';
import InputBase, {
rootOverridesResolver as inputBaseRootOverridesResolver,
inputOverridesResolver as inputBaseInputOverridesResolver,
InputBaseRoot,
InputBaseComponent as InputBaseInput,
} from '../InputBase/InputBase';
import useThemeProps from '../styles/useThemeProps';
const useUtilityClasses = (ownerState) => {
const { classes } = ownerState;
const slots = {
root: ['root'],
notchedOutline: ['notchedOutline'],
input: ['input'],
};
const composedClasses = composeClasses(slots, getOutlinedInputUtilityClass, classes);
return {
...classes, // forward classes to the InputBase
...composedClasses,
};
};
const OutlinedInputRoot = styled(InputBaseRoot, {
shouldForwardProp: (prop) => rootShouldForwardProp(prop) || prop === 'classes',
name: 'MuiOutlinedInput',
slot: 'Root',
overridesResolver: inputBaseRootOverridesResolver,
})(({ theme, ownerState }) => {
const borderColor =
theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';
return {
position: 'relative',
borderRadius: theme.shape.borderRadius,
[`&:hover .${outlinedInputClasses.notchedOutline}`]: {
borderColor: theme.palette.text.primary,
},
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
[`&:hover .${outlinedInputClasses.notchedOutline}`]: {
borderColor,
},
},
[`&.${outlinedInputClasses.focused} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: theme.palette[ownerState.color].main,
borderWidth: 2,
},
[`&.${outlinedInputClasses.error} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: theme.palette.error.main,
},
[`&.${outlinedInputClasses.disabled} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: theme.palette.action.disabled,
},
...(ownerState.startAdornment && {
paddingLeft: 14,
}),
...(ownerState.endAdornment && {
paddingRight: 14,
}),
...(ownerState.multiline && {
padding: '16.5px 14px',
...(ownerState.size === 'small' && {
padding: '8.5px 14px',
}),
}),
};
});
const NotchedOutlineRoot = styled(NotchedOutline, {
name: 'MuiOutlinedInput',
slot: 'NotchedOutline',
overridesResolver: (props, styles) => styles.notchedOutline,
})(({ theme }) => ({
borderColor: theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)',
}));
const OutlinedInputInput = styled(InputBaseInput, {
name: 'MuiOutlinedInput',
slot: 'Input',
overridesResolver: inputBaseInputOverridesResolver,
})(({ theme, ownerState }) => ({
padding: '16.5px 14px',
'&:-webkit-autofill': {
WebkitBoxShadow: theme.palette.mode === 'light' ? null : '0 0 0 100px #266798 inset',
WebkitTextFillColor: theme.palette.mode === 'light' ? null : '#fff',
caretColor: theme.palette.mode === 'light' ? null : '#fff',
borderRadius: 'inherit',
},
...(ownerState.size === 'small' && {
padding: '8.5px 14px',
}),
...(ownerState.multiline && {
padding: 0,
}),
...(ownerState.startAdornment && {
paddingLeft: 0,
}),
...(ownerState.endAdornment && {
paddingRight: 0,
}),
}));
const OutlinedInput = React.forwardRef(function OutlinedInput(inProps, ref) {
const props = useThemeProps({ props: inProps, name: 'MuiOutlinedInput' });
const {
components = {},
fullWidth = false,
inputComponent = 'input',
label,
multiline = false,
notched,
type = 'text',
...other
} = props;
const classes = useUtilityClasses(props);
return (
<InputBase
components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }}
renderSuffix={(state) => (
<NotchedOutlineRoot
className={classes.notchedOutline}
label={label}
notched={
typeof notched !== 'undefined'
? notched
: Boolean(state.startAdornment || state.filled || state.focused)
}
/>
)}
fullWidth={fullWidth}
inputComponent={inputComponent}
multiline={multiline}
ref={ref}
type={type}
{...other}
classes={{
...classes,
notchedOutline: null,
}}
/>
);
});
OutlinedInput.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the `input` element is focused during the first mount.
*/
autoFocus: PropTypes.bool,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* The prop defaults to the value (`'primary'`) inherited from the parent FormControl component.
*/
color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['primary', 'secondary']),
PropTypes.string,
]),
/**
* The components used for each slot inside the InputBase.
* Either a string to use a HTML element or a component.
* @default {}
*/
components: PropTypes.shape({
Input: PropTypes.elementType,
Root: PropTypes.elementType,
}),
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the component is disabled.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
disabled: PropTypes.bool,
/**
* End `InputAdornment` for this component.
*/
endAdornment: PropTypes.node,
/**
* If `true`, the `input` will indicate an error.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
error: PropTypes.bool,
/**
* If `true`, the `input` will take up the full width of its container.
* @default false
*/
fullWidth: PropTypes.bool,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* The component used for the `input` element.
* Either a string to use a HTML element or a component.
* @default 'input'
*/
inputComponent: PropTypes.elementType,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
* @default {}
*/
inputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* The label of the `input`. It is only used for layout. The actual labelling
* is handled by `InputLabel`.
*/
label: PropTypes.node,
/**
* If `dense`, will adjust vertical spacing. This is normally obtained via context from
* FormControl.
* The prop defaults to the value (`'none'`) inherited from the parent FormControl component.
*/
margin: PropTypes.oneOf(['dense', 'none']),
/**
* Maximum number of rows to display when multiline option is set to true.
*/
maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Minimum number of rows to display when multiline option is set to true.
*/
minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* If `true`, a `textarea` element is rendered.
* @default false
*/
multiline: PropTypes.bool,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* If `true`, the outline is notched to accommodate the label.
*/
notched: PropTypes.bool,
/**
* Callback fired when the value is changed.
*
* @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* The short hint displayed in the `input` before the user enters a value.
*/
placeholder: PropTypes.string,
/**
* It prevents the user from changing the value of the field
* (not from interacting with the field).
*/
readOnly: PropTypes.bool,
/**
* If `true`, the `input` element is required.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
required: PropTypes.bool,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Start `InputAdornment` for this component.
*/
startAdornment: PropTypes.node,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])),
PropTypes.func,
PropTypes.object,
]),
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
* @default 'text'
*/
type: PropTypes.string,
/**
* The value of the `input` element, required for a controlled component.
*/
value: PropTypes.any,
};
OutlinedInput.muiName = 'Input';
export default OutlinedInput;
|
packages/mui-material/src/OutlinedInput/OutlinedInput.js
| 1 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.8901413083076477,
0.028540724888443947,
0.00016102461086120456,
0.00016886735102161765,
0.15475207567214966
] |
{
"id": 2,
"code_window": [
" <InputBase\n",
" components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }}\n",
" renderSuffix={(state) => (\n",
" <NotchedOutlineRoot\n",
" className={classes.notchedOutline}\n",
" label={label}\n",
" notched={\n",
" typeof notched !== 'undefined'\n",
" ? notched\n",
" : Boolean(state.startAdornment || state.filled || state.focused)\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" label={\n",
" label && fcs.required ? (\n",
" <React.Fragment>\n",
" {label}\n",
" {'*'}\n",
" </React.Fragment>\n",
" ) : (\n",
" label\n",
" )\n",
" }\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "replace",
"edit_start_line_idx": 132
}
|
import * as React from 'react';
import { DialogContentText } from '@mui/material';
const DialogContentTextTest = () => {
const CustomComponent: React.FC<{ prop1: string; prop2: number }> = () => <div />;
return (
<div>
<DialogContentText />
<DialogContentText classes={{ root: 'rootClass' }} />
{/* @ts-expect-error */}
<DialogContentText classes={{ body1: 'body1Class' }} />
<DialogContentText align="inherit" color="inherit" display="block" />
<DialogContentText align="left" color="initial" display="inline" />
<DialogContentText align="right" color="primary" display="initial" />
<DialogContentText align="justify" color="secondary" display="initial" />
<DialogContentText align="inherit" color="text.primary" />
<DialogContentText align="inherit" color="text.secondary" />
<DialogContentText align="inherit" color="error" />
{/* TODO: system props did not catch this error. Add @ts-expect-error after it is fixed. */}
<DialogContentText display="incorrectValue" />
<DialogContentText component="a" href="url" display="block" />
<DialogContentText component="label" htmlFor="html" display="block" />
{/* TODO: system props did not catch this error. Add @ts-expect-error after it is fixed. */}
<DialogContentText component="a" href="url" display="incorrectValue" />
{/* @ts-expect-error */}
<DialogContentText component="a" incorrectAttribute="url" />
{/* @ts-expect-error */}
<DialogContentText component="incorrectComponent" href="url" />
{/* @ts-expect-error */}
<DialogContentText component="div" href="url" />
{/* @ts-expect-error */}
<DialogContentText href="url" />
<DialogContentText component={CustomComponent} prop1="1" prop2={12} />
{/* @ts-expect-error */}
<DialogContentText component={CustomComponent} prop1="1" prop2={12} id="1" />
{/* @ts-expect-error */}
<DialogContentText component={CustomComponent} prop1="1" />
{/* @ts-expect-error */}
<DialogContentText component={CustomComponent} prop1="1" prop2="12" />
</div>
);
};
|
packages/mui-material/src/DialogContentText/DialogContentText.spec.tsx
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.00017629035573918372,
0.00017470406601205468,
0.00017106432642322034,
0.00017535238293930888,
0.0000019207734567316948
] |
{
"id": 2,
"code_window": [
" <InputBase\n",
" components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }}\n",
" renderSuffix={(state) => (\n",
" <NotchedOutlineRoot\n",
" className={classes.notchedOutline}\n",
" label={label}\n",
" notched={\n",
" typeof notched !== 'undefined'\n",
" ? notched\n",
" : Boolean(state.startAdornment || state.filled || state.focused)\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" label={\n",
" label && fcs.required ? (\n",
" <React.Fragment>\n",
" {label}\n",
" {'*'}\n",
" </React.Fragment>\n",
" ) : (\n",
" label\n",
" )\n",
" }\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "replace",
"edit_start_line_idx": 132
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M4 15h16v-2H4v2zm0 4h16v-2H4v2zm0-8h16V9H4v2zm0-6v2h16V5H4z"
}), 'ViewHeadlineSharp');
|
packages/mui-icons-material/lib/esm/ViewHeadlineSharp.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.0001754975673975423,
0.0001754975673975423,
0.0001754975673975423,
0.0001754975673975423,
0
] |
{
"id": 2,
"code_window": [
" <InputBase\n",
" components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }}\n",
" renderSuffix={(state) => (\n",
" <NotchedOutlineRoot\n",
" className={classes.notchedOutline}\n",
" label={label}\n",
" notched={\n",
" typeof notched !== 'undefined'\n",
" ? notched\n",
" : Boolean(state.startAdornment || state.filled || state.focused)\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" label={\n",
" label && fcs.required ? (\n",
" <React.Fragment>\n",
" {label}\n",
" {'*'}\n",
" </React.Fragment>\n",
" ) : (\n",
" label\n",
" )\n",
" }\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.js",
"type": "replace",
"edit_start_line_idx": 132
}
|
import React from 'react';
import { styled } from '@mui/material/styles';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { connect } from 'react-redux';
import NoSsr from '@material-ui/core/NoSsr';
import IconClose from '@material-ui/icons/Close';
import IconMenu from '@material-ui/icons/Menu';
import Typography from '@material-ui/core/Typography';
import { compose } from 'recompose';
import AppBar from 'modules/components/AppBar';
import Logo from 'modules/components/Logo';
import Link from 'modules/components/Link';
import AppAppBarAuthenticated from 'modules/components/AppAppBarAuthenticated';
import AppAppBarUnauthenticated from 'modules/components/AppAppBarUnauthenticated';
// import SearchBar from 'modules/components/SearchBar';
import actionTypes from 'modules/redux/actionTypes';
import getUser from 'modules/getUser';
import getCart from 'modules/getCart';
const PREFIX = 'AppAppBar';
const classes = {
grow: `${PREFIX}-grow`,
wrap: `${PREFIX}-wrap`,
wrapOpened: `${PREFIX}-wrapOpened`,
menu: `${PREFIX}-menu`,
menuIcon: `${PREFIX}-menuIcon`,
closeIcon: `${PREFIX}-closeIcon`,
burgerIcon: `${PREFIX}-burgerIcon`,
white: `${PREFIX}-white`,
content: `${PREFIX}-content`,
contentOpened: `${PREFIX}-contentOpened`,
item: `${PREFIX}-item`
};
const StyledAppBar = styled(AppBar)((
{
theme
}
) => ({
[`& .${classes.grow}`]: {
display: 'block',
flexGrow: 1,
[theme.breakpoints.down('sm')]: {
display: 'none',
},
},
[`& .${classes.wrap}`]: {
display: 'flex',
flex: '1 1 auto',
alignItems: 'center',
zIndex: 1,
[theme.breakpoints.down('sm')]: {
alignItems: 'baseline',
padding: `calc(${theme.spacing(2)} - 1px) 0`,
flexWrap: 'wrap',
},
},
[`& .${classes.wrapOpened}`]: {
[theme.breakpoints.down('sm')]: {
color: theme.palette.common.white,
alignItems: 'flex-start',
backgroundColor: theme.palette.primary.main,
bottom: 0,
left: 0,
padding: theme.spacing(2),
position: 'fixed',
right: 0,
top: 0,
},
},
[`& .${classes.menu}`]: {
display: 'none',
[theme.breakpoints.down('sm')]: {
display: 'block',
position: 'absolute',
right: 0,
top: theme.spacing(2),
},
},
[`& .${classes.menuIcon}`]: {
fontSize: 32,
marginTop: -theme.spacing(1 / 2),
},
[`& .${classes.closeIcon}`]: {
marginRight: theme.spacing(2),
},
[`& .${classes.burgerIcon}`]: {
color: theme.palette.text.secondary,
},
[`& .${classes.white}`]: {
color: theme.palette.common.white,
},
[`& .${classes.content}`]: {
display: 'flex',
alignItems: 'center',
flex: '1 1 auto',
[theme.breakpoints.down('sm')]: {
display: 'none',
},
},
[`& .${classes.contentOpened}`]: {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
[theme.breakpoints.down('sm')]: {
display: 'flex',
},
},
// searchBar: {
// [theme.breakpoints.down('xs')]: {
// flex: '1 0 100%',
// marginTop: theme.spacing(2),
// },
// },
[`& .${classes.item}`]: {
[theme.breakpoints.down('sm')]: {
backgroundColor: 'transparent',
border: 0,
color: theme.palette.common.white,
fontSize: 24,
height: theme.spacing(5),
margin: theme.spacing(1),
},
[theme.breakpoints.up('sm')]: {
marginRight: theme.spacing(2),
},
}
}));
class AppAppBar extends React.Component {
state = {
menuOpen: false,
};
async componentDidMount() {
const cart = await getCart();
this.props.dispatch({
type: actionTypes.CART_UPDATE,
payload: cart,
});
if (this.props.user.logged != null) {
return;
}
const user = await getUser();
this.props.dispatch({
type: actionTypes.USER_UPDATE,
payload: user,
});
}
handleToggleMenu = (event, forceClose) => {
if (event) {
event.preventDefault();
}
this.setState({ menuOpen: forceClose ? false : !this.state.menuOpen });
};
render() {
const { children, essential, position, user } = this.props;
const { menuOpen } = this.state;
return (
<StyledAppBar essential={essential} position={position}>
<div className={clsx(classes.wrap, { [classes.wrapOpened]: menuOpen })}>
<Link to="/" aria-label="Back to homepage" color="inherit">
<Logo color={menuOpen ? 'inherit' : 'textPrimary'} />
</Link>
{/*essential || menuOpen ? null : (
<SearchBar
id="app-bar-search"
className={classes.searchBar}
/>
)*/}
<div
className={clsx(classes.content, {
[classes.contentOpened]: menuOpen,
'mui-fixed': menuOpen,
})}
>
{children || <div className={classes.grow} />}
{essential ? null : (
<Typography
className={classes.item}
component={Link}
to="https://support.mui.com/hc/en-us"
target="_blank"
>
{'Help'}
</Typography>
)}
<NoSsr>
{user.logged === true ? (
<AppAppBarAuthenticated essential={essential} menuOpen={menuOpen} />
) : null}
{user.logged === false ? (
<AppAppBarUnauthenticated essential={essential} menuOpen={menuOpen} />
) : null}
</NoSsr>
</div>
{essential ? null : (
<div className={clsx(classes.menu, 'mui-fixed')}>
<a href="#" onClick={this.handleToggleMenu}>
{menuOpen ? (
<IconClose
className={clsx(classes.menuIcon, classes.closeIcon, classes.white, {
[classes.hide]: menuOpen,
})}
/>
) : (
<IconMenu
className={clsx(classes.menuIcon, classes.burgerIcon, {
[classes.hide]: menuOpen,
})}
/>
)}
</a>
</div>
)}
</div>
</StyledAppBar>
);
}
}
AppAppBar.propTypes = {
children: PropTypes.node,
classes: PropTypes.object.isRequired,
essential: PropTypes.bool,
position: PropTypes.string,
user: PropTypes.object,
};
export default compose(
connect((state) => ({ user: state.data.user })),
)(AppAppBar);
|
packages/mui-codemod/src/v5.0.0/jss-to-styled.test/first.expected.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.0011919110547751188,
0.00021459112758748233,
0.00016182097897399217,
0.00017476033826824278,
0.0001957055792445317
] |
{
"id": 3,
"code_window": [
" );\n",
"\n",
" expect(container.querySelector('.notched-outlined')).not.to.equal(null);\n",
" });\n",
"\n",
" it('should forward classes to InputBase', () => {\n",
" render(<OutlinedInput error classes={{ error: 'error' }} />);\n",
" expect(document.querySelector('.error')).not.to.equal(null);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should set correct label prop on outline', () => {\n",
" const { container } = render(\n",
" <OutlinedInput\n",
" classes={{ notchedOutline: 'notched-outlined' }}\n",
" label={<div data-testid=\"label\">label</div>}\n",
" required\n",
" />,\n",
" );\n",
" const notchOutlined = container.querySelector('.notched-outlined legend');\n",
" expect(notchOutlined).to.have.text('label\\xa0*');\n",
" });\n",
"\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.test.js",
"type": "add",
"edit_start_line_idx": 29
}
|
import * as React from 'react';
import { expect } from 'chai';
import { createRenderer, describeConformance } from 'test/utils';
import OutlinedInput, { outlinedInputClasses as classes } from '@mui/material/OutlinedInput';
import InputBase from '@mui/material/InputBase';
describe('<OutlinedInput />', () => {
const { render } = createRenderer();
describeConformance(<OutlinedInput />, () => ({
classes,
inheritComponent: InputBase,
render,
refInstanceof: window.HTMLDivElement,
muiName: 'MuiOutlinedInput',
testDeepOverrides: { slotName: 'input', slotClassName: classes.input },
testVariantProps: { variant: 'contained', fullWidth: true },
testStateOverrides: { prop: 'size', value: 'small', styleKey: 'sizeSmall' },
skip: ['componentProp', 'componentsProp'],
}));
it('should render a NotchedOutline', () => {
const { container } = render(
<OutlinedInput classes={{ notchedOutline: 'notched-outlined' }} />,
);
expect(container.querySelector('.notched-outlined')).not.to.equal(null);
});
it('should forward classes to InputBase', () => {
render(<OutlinedInput error classes={{ error: 'error' }} />);
expect(document.querySelector('.error')).not.to.equal(null);
});
it('should respects the componentsProps if passed', () => {
render(<OutlinedInput componentsProps={{ root: { 'data-test': 'test' } }} />);
expect(document.querySelector('[data-test=test]')).not.to.equal(null);
});
});
|
packages/mui-material/src/OutlinedInput/OutlinedInput.test.js
| 1 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.03864781931042671,
0.014010511338710785,
0.0004440845805220306,
0.00847507081925869,
0.015133805572986603
] |
{
"id": 3,
"code_window": [
" );\n",
"\n",
" expect(container.querySelector('.notched-outlined')).not.to.equal(null);\n",
" });\n",
"\n",
" it('should forward classes to InputBase', () => {\n",
" render(<OutlinedInput error classes={{ error: 'error' }} />);\n",
" expect(document.querySelector('.error')).not.to.equal(null);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should set correct label prop on outline', () => {\n",
" const { container } = render(\n",
" <OutlinedInput\n",
" classes={{ notchedOutline: 'notched-outlined' }}\n",
" label={<div data-testid=\"label\">label</div>}\n",
" required\n",
" />,\n",
" );\n",
" const notchOutlined = container.querySelector('.notched-outlined legend');\n",
" expect(notchOutlined).to.have.text('label\\xa0*');\n",
" });\n",
"\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.test.js",
"type": "add",
"edit_start_line_idx": 29
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M10 12c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM6 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-4 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"
}), 'GrainRounded');
exports.default = _default;
|
packages/mui-icons-material/lib/GrainRounded.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.0002281444176333025,
0.00020288598898332566,
0.0001776275603333488,
0.00020288598898332566,
0.00002525842864997685
] |
{
"id": 3,
"code_window": [
" );\n",
"\n",
" expect(container.querySelector('.notched-outlined')).not.to.equal(null);\n",
" });\n",
"\n",
" it('should forward classes to InputBase', () => {\n",
" render(<OutlinedInput error classes={{ error: 'error' }} />);\n",
" expect(document.querySelector('.error')).not.to.equal(null);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should set correct label prop on outline', () => {\n",
" const { container } = render(\n",
" <OutlinedInput\n",
" classes={{ notchedOutline: 'notched-outlined' }}\n",
" label={<div data-testid=\"label\">label</div>}\n",
" required\n",
" />,\n",
" );\n",
" const notchOutlined = container.querySelector('.notched-outlined legend');\n",
" expect(notchOutlined).to.have.text('label\\xa0*');\n",
" });\n",
"\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.test.js",
"type": "add",
"edit_start_line_idx": 29
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M18 6H9V4H7v2H6l-4 4v9h20v-9l-4-4zM4 12h10v5H4v-5zm16 5h-4v-6.17l2-2 2 2V17z"
}), 'GiteOutlined');
exports.default = _default;
|
packages/mui-icons-material/lib/GiteOutlined.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.00018507761706132442,
0.00018135250138584524,
0.00017762738571036607,
0.00018135250138584524,
0.0000037251156754791737
] |
{
"id": 3,
"code_window": [
" );\n",
"\n",
" expect(container.querySelector('.notched-outlined')).not.to.equal(null);\n",
" });\n",
"\n",
" it('should forward classes to InputBase', () => {\n",
" render(<OutlinedInput error classes={{ error: 'error' }} />);\n",
" expect(document.querySelector('.error')).not.to.equal(null);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should set correct label prop on outline', () => {\n",
" const { container } = render(\n",
" <OutlinedInput\n",
" classes={{ notchedOutline: 'notched-outlined' }}\n",
" label={<div data-testid=\"label\">label</div>}\n",
" required\n",
" />,\n",
" );\n",
" const notchOutlined = container.querySelector('.notched-outlined legend');\n",
" expect(notchOutlined).to.have.text('label\\xa0*');\n",
" });\n",
"\n"
],
"file_path": "packages/mui-material/src/OutlinedInput/OutlinedInput.test.js",
"type": "add",
"edit_start_line_idx": 29
}
|
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><path d="M0,0h24v24H0V0z" fill="none"/></g><g><g><path d="M13,2.05v3.03c3.39,0.49,6,3.39,6,6.92c0,0.9-0.18,1.75-0.48,2.54l2.6,1.53C21.68,14.83,22,13.45,22,12 C22,6.82,18.05,2.55,13,2.05z M12,19c-3.87,0-7-3.13-7-7c0-3.53,2.61-6.43,6-6.92V2.05C5.94,2.55,2,6.81,2,12 c0,5.52,4.47,10,9.99,10c3.31,0,6.24-1.61,8.06-4.09l-2.6-1.53C16.17,17.98,14.21,19,12,19z"/></g></g></svg>
|
packages/mui-icons-material/material-icons/data_saver_off_24px.svg
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.0001745839399518445,
0.0001745839399518445,
0.0001745839399518445,
0.0001745839399518445,
0
] |
{
"id": 4,
"code_window": [
"\n",
" if (variant === 'outlined') {\n",
" if (InputLabelProps && typeof InputLabelProps.shrink !== 'undefined') {\n",
" InputMore.notched = InputLabelProps.shrink;\n",
" }\n",
" if (label) {\n",
" const displayRequired = InputLabelProps?.required ?? required;\n",
" InputMore.label = (\n",
" <React.Fragment>\n",
" {label}\n",
" {displayRequired && '\\u00a0*'}\n",
" </React.Fragment>\n",
" );\n",
" }\n",
" }\n",
" if (select) {\n",
" // unset defaults from textbox inputs\n",
" if (!SelectProps || !SelectProps.native) {\n",
" InputMore.id = undefined;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" InputMore.label = label;\n"
],
"file_path": "packages/mui-material/src/TextField/TextField.js",
"type": "replace",
"edit_start_line_idx": 137
}
|
import * as React from 'react';
import { expect } from 'chai';
import { createRenderer, describeConformance } from 'test/utils';
import OutlinedInput, { outlinedInputClasses as classes } from '@mui/material/OutlinedInput';
import InputBase from '@mui/material/InputBase';
describe('<OutlinedInput />', () => {
const { render } = createRenderer();
describeConformance(<OutlinedInput />, () => ({
classes,
inheritComponent: InputBase,
render,
refInstanceof: window.HTMLDivElement,
muiName: 'MuiOutlinedInput',
testDeepOverrides: { slotName: 'input', slotClassName: classes.input },
testVariantProps: { variant: 'contained', fullWidth: true },
testStateOverrides: { prop: 'size', value: 'small', styleKey: 'sizeSmall' },
skip: ['componentProp', 'componentsProp'],
}));
it('should render a NotchedOutline', () => {
const { container } = render(
<OutlinedInput classes={{ notchedOutline: 'notched-outlined' }} />,
);
expect(container.querySelector('.notched-outlined')).not.to.equal(null);
});
it('should forward classes to InputBase', () => {
render(<OutlinedInput error classes={{ error: 'error' }} />);
expect(document.querySelector('.error')).not.to.equal(null);
});
it('should respects the componentsProps if passed', () => {
render(<OutlinedInput componentsProps={{ root: { 'data-test': 'test' } }} />);
expect(document.querySelector('[data-test=test]')).not.to.equal(null);
});
});
|
packages/mui-material/src/OutlinedInput/OutlinedInput.test.js
| 1 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.00017321151972282678,
0.00016840049647726119,
0.00016578345093876123,
0.00016730351489968598,
0.000002932640427388833
] |
{
"id": 4,
"code_window": [
"\n",
" if (variant === 'outlined') {\n",
" if (InputLabelProps && typeof InputLabelProps.shrink !== 'undefined') {\n",
" InputMore.notched = InputLabelProps.shrink;\n",
" }\n",
" if (label) {\n",
" const displayRequired = InputLabelProps?.required ?? required;\n",
" InputMore.label = (\n",
" <React.Fragment>\n",
" {label}\n",
" {displayRequired && '\\u00a0*'}\n",
" </React.Fragment>\n",
" );\n",
" }\n",
" }\n",
" if (select) {\n",
" // unset defaults from textbox inputs\n",
" if (!SelectProps || !SelectProps.native) {\n",
" InputMore.id = undefined;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" InputMore.label = label;\n"
],
"file_path": "packages/mui-material/src/TextField/TextField.js",
"type": "replace",
"edit_start_line_idx": 137
}
|
import path from 'path';
import { expect } from 'chai';
import jscodeshift from 'jscodeshift';
import transform from './material-ui-styles';
import readFile from '../util/readFile';
function read(fileName) {
return readFile(path.join(__dirname, fileName));
}
describe('@mui/codemod', () => {
describe('v5.0.0', () => {
describe('material-ui-styles', () => {
it('transforms props as needed', () => {
const actual = transform(
{
source: read('./material-ui-styles.test/actual.js'),
path: require.resolve('./material-ui-styles.test/actual.js'),
},
{ jscodeshift },
{},
);
const expected = read('./material-ui-styles.test/expected.js');
expect(actual).to.equal(expected, 'The transformed version should be correct');
});
it('should be idempotent', () => {
const actual = transform(
{
source: read('./material-ui-styles.test/expected.js'),
path: require.resolve('./material-ui-styles.test/expected.js'),
},
{ jscodeshift },
{},
);
const expected = read('./material-ui-styles.test/expected.js');
expect(actual).to.equal(expected, 'The transformed version should be correct');
});
it('remove no variable import', () => {
const actual = transform(
{
source: read('./material-ui-styles.test/single-import.actual.js'),
path: require.resolve('./material-ui-styles.test/single-import.actual.js'),
},
{ jscodeshift },
{},
);
const expected = read('./material-ui-styles.test/single-import.expected.js');
expect(actual).to.equal(expected, 'The transformed version should be correct');
});
it('transform core import', () => {
const actual = transform(
{
source: read('./material-ui-styles.test/core-import.actual.js'),
path: require.resolve('./material-ui-styles.test/core-import.actual.js'),
},
{ jscodeshift },
{},
);
const expected = read('./material-ui-styles.test/core-import.expected.js');
expect(actual).to.equal(expected, 'The transformed version should be correct');
});
it('transform types import', () => {
const actual = transform(
{
source: read('./material-ui-styles.test/types-import.actual.js'),
path: require.resolve('./material-ui-styles.test/types-import.actual.js'),
},
{ jscodeshift },
{},
);
const expected = read('./material-ui-styles.test/types-import.expected.js');
expect(actual).to.equal(expected, 'The transformed version should be correct');
});
});
});
});
|
packages/mui-codemod/src/v5.0.0/material-ui-styles.test.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.00017807897529564798,
0.00017589474737178534,
0.00017229894001502544,
0.0001767254143487662,
0.00000204854654839437
] |
{
"id": 4,
"code_window": [
"\n",
" if (variant === 'outlined') {\n",
" if (InputLabelProps && typeof InputLabelProps.shrink !== 'undefined') {\n",
" InputMore.notched = InputLabelProps.shrink;\n",
" }\n",
" if (label) {\n",
" const displayRequired = InputLabelProps?.required ?? required;\n",
" InputMore.label = (\n",
" <React.Fragment>\n",
" {label}\n",
" {displayRequired && '\\u00a0*'}\n",
" </React.Fragment>\n",
" );\n",
" }\n",
" }\n",
" if (select) {\n",
" // unset defaults from textbox inputs\n",
" if (!SelectProps || !SelectProps.native) {\n",
" InputMore.id = undefined;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" InputMore.label = label;\n"
],
"file_path": "packages/mui-material/src/TextField/TextField.js",
"type": "replace",
"edit_start_line_idx": 137
}
|
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><g><circle cx="19" cy="3" r="3"/><path d="M6,8V6h9.03c-1.21-1.6-1.08-3.21-0.92-4H4.01c-1.1,0-2,0.89-2,2L2,22l4-4h14c1.1,0,2-0.9,2-2V6.97 C21.16,7.61,20.13,8,19,8H6z M14,14H6v-2h8V14z M18,11H6V9h12V11z"/></g></g></svg>
|
packages/mui-icons-material/material-icons/mark_unread_chat_alt_24px.svg
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.0001734161050990224,
0.0001734161050990224,
0.0001734161050990224,
0.0001734161050990224,
0
] |
{
"id": 4,
"code_window": [
"\n",
" if (variant === 'outlined') {\n",
" if (InputLabelProps && typeof InputLabelProps.shrink !== 'undefined') {\n",
" InputMore.notched = InputLabelProps.shrink;\n",
" }\n",
" if (label) {\n",
" const displayRequired = InputLabelProps?.required ?? required;\n",
" InputMore.label = (\n",
" <React.Fragment>\n",
" {label}\n",
" {displayRequired && '\\u00a0*'}\n",
" </React.Fragment>\n",
" );\n",
" }\n",
" }\n",
" if (select) {\n",
" // unset defaults from textbox inputs\n",
" if (!SelectProps || !SelectProps.native) {\n",
" InputMore.id = undefined;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" InputMore.label = label;\n"
],
"file_path": "packages/mui-material/src/TextField/TextField.js",
"type": "replace",
"edit_start_line_idx": 137
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M7 24h2v-2H7v2zm5-11c1.66 0 2.99-1.34 2.99-3L15 4c0-1.66-1.34-3-3-3S9 2.34 9 4v6c0 1.66 1.34 3 3 3zm-1 11h2v-2h-2v2zm4 0h2v-2h-2v2zm4-14h-1.7c0 3-2.54 5.1-5.3 5.1S6.7 13 6.7 10H5c0 3.41 2.72 6.23 6 6.72V20h2v-3.28c3.28-.49 6-3.31 6-6.72z"
}), 'SettingsVoiceSharp');
|
packages/mui-icons-material/lib/esm/SettingsVoiceSharp.js
| 0 |
https://github.com/mui/material-ui/commit/2851e53c19023b8e048f1f2caba9903c281cd7bc
|
[
0.00017592731455806643,
0.00017592731455806643,
0.00017592731455806643,
0.00017592731455806643,
0
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
".list[inset] {\n",
" ion-header {\n",
" background-color: $list-background-color;\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: hidden;\n",
" transform: translateZ(0);\n",
" \n"
],
"file_path": "ionic/components/list/list.scss",
"type": "add",
"edit_start_line_idx": 20
}
|
// iOS List
// --------------------------------------------------
$list-ios-margin-top: 10px !default;
$list-ios-margin-right: 0 !default;
$list-ios-margin-bottom: 32px !default;
$list-ios-margin-left: 0 !default;
$list-inset-ios-margin-top: 16px !default;
$list-inset-ios-margin-right: 16px !default;
$list-inset-ios-margin-bottom: 16px !default;
$list-inset-ios-margin-left: 16px !default;
$list-inset-ios-border-radius: 4px !default;
$list-ios-header-padding: 10px $item-ios-padding-right 10px $item-ios-padding-left !default;
$list-ios-header-font-size: 1.2rem !default;
$list-ios-header-font-weight: 500 !default;
$list-ios-header-letter-spacing: 0.1rem !default;
$list-ios-header-color: #333 !default;
$list-ios-border-color: $list-border-color !default;
/****************/
/* DEFAULT LIST */
/****************/
.list {
margin: -1px $list-ios-margin-right $list-ios-margin-bottom $list-ios-margin-left;
ion-header {
position: relative;
padding: $list-ios-header-padding;
font-size: $list-ios-header-font-size;
font-weight: $list-ios-header-font-weight;
letter-spacing: $list-ios-header-letter-spacing;
text-transform: uppercase;
color: $list-ios-header-color;
border-bottom: 1px solid $list-ios-border-color;
}
> .item:first-child {
border-top: 1px solid $list-ios-border-color;
}
> .item:last-child,
> ion-item-sliding:last-child .item {
border-bottom: 1px solid $list-ios-border-color;
.item-inner {
border-bottom: none;
}
}
.item-inner {
border-bottom: 1px solid $list-ios-border-color;
}
// If the item has the no-lines attribute remove the bottom border from:
// the item itself (for last-child items)
// the item-inner class (if it is not last)
.item[no-lines],
.item[no-lines] .item-inner, {
border-width: 0;
}
ion-item-options {
border-bottom: 1px solid $list-ios-border-color;
button, [button] {
min-height: 100%;
height: 100%;
margin: 0;
border: none;
border-radius: 0;
display: inline-flex;
align-items: center;
box-sizing: border-box;
&:before{
margin: 0 auto;
}
}
}
}
.list + .list {
margin-top: $list-ios-margin-top + $list-ios-margin-bottom;
ion-header {
margin-top: -$list-ios-margin-top;
padding-top: 0;
}
}
&.hairlines .list {
ion-item-options {
border-width: 0.55px;
}
ion-header {
border-bottom-width: 0.55px;
}
.item {
.item-inner {
border-width: 0.55px;
}
}
> .item:first-child {
border-top-width: 0.55px;
}
> .item:last-child,
> ion-item-sliding:last-child .item {
border-bottom-width: 0.55px;
}
}
/**************/
/* INSET LIST */
/**************/
.list[inset] {
margin: $list-inset-ios-margin-top $list-inset-ios-margin-right $list-inset-ios-margin-bottom $list-inset-ios-margin-left;
border-radius: $list-inset-ios-border-radius;
.item {
border-bottom: 1px solid $list-ios-border-color;
.item-inner {
border-bottom: none;
}
}
> .item:first-child,
ion-header {
border-top-right-radius: $list-inset-ios-border-radius;
border-top-left-radius: $list-inset-ios-border-radius;
}
> .item:first-child {
border-top: none;
}
> .item:last-child,
> ion-item-sliding:last-child .item {
border-bottom-right-radius: $list-inset-ios-border-radius;
border-bottom-left-radius: $list-inset-ios-border-radius;
border-bottom: none;
}
}
.list[inset] + .list[inset] {
margin-top: 0;
}
&.hairlines .list[inset] {
.item {
border-width: 0.55px;
}
}
/*****************/
/* NO LINES LIST */
/*****************/
.list[no-lines],
&.hairlines .list[no-lines] {
ion-header,
.item,
.item .item-inner {
border-width: 0;
}
}
|
ionic/components/list/modes/ios.scss
| 1 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.04462304338812828,
0.008566541597247124,
0.0001725725451251492,
0.0019353603711351752,
0.012020210735499859
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
".list[inset] {\n",
" ion-header {\n",
" background-color: $list-background-color;\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: hidden;\n",
" transform: translateZ(0);\n",
" \n"
],
"file_path": "ionic/components/list/list.scss",
"type": "add",
"edit_start_line_idx": 20
}
|
// iOS App
// --------------------------------------------------
hr {
border-width: 0;
height: 1px;
background-color: rgba(0, 0, 0, 0.12);
}
&.hairlines hr {
height: 0.55px;
}
|
ionic/components/app/modes/ios.scss
| 0 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.00016958739433903247,
0.0001673324004514143,
0.0001650774065637961,
0.0001673324004514143,
0.000002254993887618184
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
".list[inset] {\n",
" ion-header {\n",
" background-color: $list-background-color;\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: hidden;\n",
" transform: translateZ(0);\n",
" \n"
],
"file_path": "ionic/components/list/list.scss",
"type": "add",
"edit_start_line_idx": 20
}
|
<ion-navbar *navbar class="android-attr">
<ion-title>Modals</ion-title>
</ion-navbar>
<ion-content class="has-header">
<ion-list>
<ion-header>
Hobbits
</ion-header>
<a ion-item (click)="openModal({charNum: 0})">
Gollum
</a>
<a ion-item (click)="openModal({charNum: 1})">
Frodo Baggins
</a>
<a ion-item (click)="openModal({charNum: 2})">
Sam
</a>
</ion-list>
</ion-content>
|
demos/component-docs/modals/basic/template.html
| 0 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.007517074700444937,
0.0027353393379598856,
0.00029190501663833857,
0.00039703818038105965,
0.003381469752639532
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
".list[inset] {\n",
" ion-header {\n",
" background-color: $list-background-color;\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: hidden;\n",
" transform: translateZ(0);\n",
" \n"
],
"file_path": "ionic/components/list/list.scss",
"type": "add",
"edit_start_line_idx": 20
}
|
/*! normalize.css v3.0.2 | MIT License | github.com/necolas/normalize.css */
// HTML5 display definitions
// ==========================================================================
// 1. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
audio,
canvas,
progress,
video {
vertical-align: baseline; // 1
}
// Prevent modern browsers from displaying `audio` without controls.
// Remove excess height in iOS 5 devices.
audio:not([controls]) {
display: none;
height: 0;
}
// Text-level semantics
// ==========================================================================
// Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
b,
strong {
font-weight: bold;
}
// Embedded content
// ==========================================================================
// Remove border when inside `a` element in IE 8/9/10.
img {
border: 0;
}
// Correct overflow not hidden in IE 9/10/11.
svg:not(:root) {
overflow: hidden;
}
// Grouping content
// ==========================================================================
// Address margin not present in IE 8/9 and Safari.
figure {
margin: 1em 40px;
}
// Address differences between Firefox and other browsers.
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
// Contain overflow in all browsers.
pre {
overflow: auto;
}
// Address odd `em`-unit font size rendering in all browsers.
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
// Forms
// ==========================================================================
// Known limitation: by default, Chrome and Safari on OS X allow very limited
// styling of `select`, unless a `border` property is set.
// 1. Correct color not being inherited.
// Known issue: affects color of disabled elements.
// 2. Correct font properties not being inherited.
// 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
//
label,
input,
select,
textarea {
line-height: normal;
font-family: inherit;
}
form,
input,
optgroup,
select {
color: inherit; // 1
font: inherit; // 2
margin: 0; // 3
}
// 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
// and `video` controls.
// 2. Correct inability to style clickable `input` types in iOS.
// 3. Improve usability and consistency of cursor style between image-type
// `input` and others.
html input[type="button"], // 1
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; // 2
cursor: pointer; // 3
}
// Re-set default cursor for disabled elements.
button[disabled],
html input[disabled] {
cursor: default;
}
// Remove inner padding and border in Firefox 4+.
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
// Firefox's implementation doesn't respect box-sizing, padding, or width.
// 1. Address box sizing set to `content-box` in IE 8/9/10.
// 2. Remove excess padding in IE 8/9/10.
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; // 1
padding: 0; // 2
}
// Fix the cursor style for Chrome's increment/decrement buttons. For certain
// `font-size` values of the `input`, it causes the cursor style of the
// decrement button to change from `default` to `text`.
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
// Remove inner padding and search cancel button in Safari and Chrome on OS X.
// Safari (but not Chrome) clips the cancel button when the search input has
// padding (and `textfield` appearance).
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
// Tables
// ==========================================================================//
// Remove most spacing between table cells.
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
|
ionic/components/app/normalize.scss
| 0 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.00017880259838420898,
0.0001686800387687981,
0.00016497574688401073,
0.00016801554011180997,
0.00000308118296743487
] |
{
"id": 1,
"code_window": [
" border-bottom: none;\n",
" }\n",
" }\n",
"\n",
" > .item:first-child,\n",
" ion-header {\n",
" border-top-right-radius: $list-inset-ios-border-radius;\n",
" border-top-left-radius: $list-inset-ios-border-radius;\n",
" }\n",
"\n",
" > .item:first-child {\n",
" border-top: none;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" > ion-item-sliding:first-child .item {\n"
],
"file_path": "ionic/components/list/modes/ios.scss",
"type": "replace",
"edit_start_line_idx": 141
}
|
// iOS List
// --------------------------------------------------
$list-ios-margin-top: 10px !default;
$list-ios-margin-right: 0 !default;
$list-ios-margin-bottom: 32px !default;
$list-ios-margin-left: 0 !default;
$list-inset-ios-margin-top: 16px !default;
$list-inset-ios-margin-right: 16px !default;
$list-inset-ios-margin-bottom: 16px !default;
$list-inset-ios-margin-left: 16px !default;
$list-inset-ios-border-radius: 4px !default;
$list-ios-header-padding: 10px $item-ios-padding-right 10px $item-ios-padding-left !default;
$list-ios-header-font-size: 1.2rem !default;
$list-ios-header-font-weight: 500 !default;
$list-ios-header-letter-spacing: 0.1rem !default;
$list-ios-header-color: #333 !default;
$list-ios-border-color: $list-border-color !default;
/****************/
/* DEFAULT LIST */
/****************/
.list {
margin: -1px $list-ios-margin-right $list-ios-margin-bottom $list-ios-margin-left;
ion-header {
position: relative;
padding: $list-ios-header-padding;
font-size: $list-ios-header-font-size;
font-weight: $list-ios-header-font-weight;
letter-spacing: $list-ios-header-letter-spacing;
text-transform: uppercase;
color: $list-ios-header-color;
border-bottom: 1px solid $list-ios-border-color;
}
> .item:first-child {
border-top: 1px solid $list-ios-border-color;
}
> .item:last-child,
> ion-item-sliding:last-child .item {
border-bottom: 1px solid $list-ios-border-color;
.item-inner {
border-bottom: none;
}
}
.item-inner {
border-bottom: 1px solid $list-ios-border-color;
}
// If the item has the no-lines attribute remove the bottom border from:
// the item itself (for last-child items)
// the item-inner class (if it is not last)
.item[no-lines],
.item[no-lines] .item-inner, {
border-width: 0;
}
ion-item-options {
border-bottom: 1px solid $list-ios-border-color;
button, [button] {
min-height: 100%;
height: 100%;
margin: 0;
border: none;
border-radius: 0;
display: inline-flex;
align-items: center;
box-sizing: border-box;
&:before{
margin: 0 auto;
}
}
}
}
.list + .list {
margin-top: $list-ios-margin-top + $list-ios-margin-bottom;
ion-header {
margin-top: -$list-ios-margin-top;
padding-top: 0;
}
}
&.hairlines .list {
ion-item-options {
border-width: 0.55px;
}
ion-header {
border-bottom-width: 0.55px;
}
.item {
.item-inner {
border-width: 0.55px;
}
}
> .item:first-child {
border-top-width: 0.55px;
}
> .item:last-child,
> ion-item-sliding:last-child .item {
border-bottom-width: 0.55px;
}
}
/**************/
/* INSET LIST */
/**************/
.list[inset] {
margin: $list-inset-ios-margin-top $list-inset-ios-margin-right $list-inset-ios-margin-bottom $list-inset-ios-margin-left;
border-radius: $list-inset-ios-border-radius;
.item {
border-bottom: 1px solid $list-ios-border-color;
.item-inner {
border-bottom: none;
}
}
> .item:first-child,
ion-header {
border-top-right-radius: $list-inset-ios-border-radius;
border-top-left-radius: $list-inset-ios-border-radius;
}
> .item:first-child {
border-top: none;
}
> .item:last-child,
> ion-item-sliding:last-child .item {
border-bottom-right-radius: $list-inset-ios-border-radius;
border-bottom-left-radius: $list-inset-ios-border-radius;
border-bottom: none;
}
}
.list[inset] + .list[inset] {
margin-top: 0;
}
&.hairlines .list[inset] {
.item {
border-width: 0.55px;
}
}
/*****************/
/* NO LINES LIST */
/*****************/
.list[no-lines],
&.hairlines .list[no-lines] {
ion-header,
.item,
.item .item-inner {
border-width: 0;
}
}
|
ionic/components/list/modes/ios.scss
| 1 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.9975428581237793,
0.057890526950359344,
0.00017683448095340282,
0.0016743227606639266,
0.2216215431690216
] |
{
"id": 1,
"code_window": [
" border-bottom: none;\n",
" }\n",
" }\n",
"\n",
" > .item:first-child,\n",
" ion-header {\n",
" border-top-right-radius: $list-inset-ios-border-radius;\n",
" border-top-left-radius: $list-inset-ios-border-radius;\n",
" }\n",
"\n",
" > .item:first-child {\n",
" border-top: none;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" > ion-item-sliding:first-child .item {\n"
],
"file_path": "ionic/components/list/modes/ios.scss",
"type": "replace",
"edit_start_line_idx": 141
}
|
ionic/components/text-input/test/fixed-inline-labels/e2e.ts
| 0 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.00017454332555644214,
0.00017454332555644214,
0.00017454332555644214,
0.00017454332555644214,
0
] |
|
{
"id": 1,
"code_window": [
" border-bottom: none;\n",
" }\n",
" }\n",
"\n",
" > .item:first-child,\n",
" ion-header {\n",
" border-top-right-radius: $list-inset-ios-border-radius;\n",
" border-top-left-radius: $list-inset-ios-border-radius;\n",
" }\n",
"\n",
" > .item:first-child {\n",
" border-top: none;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" > ion-item-sliding:first-child .item {\n"
],
"file_path": "ionic/components/list/modes/ios.scss",
"type": "replace",
"edit_start_line_idx": 141
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ionic E2E</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link href="../../../css/ionic.css" rel="stylesheet">
<script>
if (!console.time) {
console.time = console.log;
}
if (!console.timeEnd) {
console.timeEnd = console.log;
}
console.time('script init');
if (location.href.indexOf('snapshot=true') > -1) {
document.documentElement.classList.add('snapshot');
} else {
document.documentElement.classList.remove('snapshot');
}
if (location.href.indexOf('cordova=true') > -1) {
window.cordova = {};
}
</script>
<style>
.snapshot body {
/* crop an exact size */
max-height: 700px !important;
}
.snapshot scroll-content {
/* disable scrollbars */
overflow: hidden !important;
}
.snapshot *,
.snapshot *:before,
.snapshot *:after {
/* do not allow css animations during snapshot */
-webkit-transition-duration: 0ms !important;
transition-duration: 0ms !important;
}
.snapshot md-ripple {
display: none !important;
}
/* hack to create tall scrollable areas for testing using <f></f> */
f {
display: block;
margin: 15px auto;
max-width: 150px;
height: 150px;
background: blue;
}
f:last-of-type {
background: red;
}
ion-tab:nth-of-type(2) f,
.green f {
background: green;
max-width: 250px;
height: 100px;
}
ion-tab:nth-of-type(3) f,
.yellow f {
background: yellow;
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<ion-app>
<ion-loading-icon></ion-loading-icon>
</ion-app>
<script src="../../../js/ionic.bundle.js"></script>
<script>
System.config({
"paths": {
"*": "*.js",
"ionic/*": "ionic/*",
"angular2/*": "angular2/*",
"rx": "rx"
}
})
System.import("index").then(function(m) {}, console.error.bind(console));
console.timeEnd('script init');
</script>
</body>
</html>
|
scripts/e2e/e2e.template.html
| 0 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.00027209363179281354,
0.00018292799359187484,
0.0001677261316217482,
0.00017203879542648792,
0.00003010635009559337
] |
{
"id": 1,
"code_window": [
" border-bottom: none;\n",
" }\n",
" }\n",
"\n",
" > .item:first-child,\n",
" ion-header {\n",
" border-top-right-radius: $list-inset-ios-border-radius;\n",
" border-top-left-radius: $list-inset-ios-border-radius;\n",
" }\n",
"\n",
" > .item:first-child {\n",
" border-top: none;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" > ion-item-sliding:first-child .item {\n"
],
"file_path": "ionic/components/list/modes/ios.scss",
"type": "replace",
"edit_start_line_idx": 141
}
|
import {Directive, ElementRef} from 'angular2/angular2';
import {Ion} from '../ion';
import {IonicApp} from '../app/app';
/**
* TODO
*/
@Directive({
selector: '[menu-close]',
inputs: [
'menuClose'
],
host: {
'(click)': 'close()'
}
})
export class MenuClose extends Ion {
constructor(
app: IonicApp,
elementRef: ElementRef
) {
super(elementRef, null);
this.app = app;
}
close() {
let menu = this.app.getComponent(this.menuClose || 'menu');
menu && menu.close();
}
}
|
ionic/components/menu/menu-close.ts
| 0 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.000272295786999166,
0.00019357804558239877,
0.00016575437621213496,
0.0001681310241110623,
0.00004547590287984349
] |
{
"id": 2,
"code_window": [
" border-top: none;\n",
" }\n",
"\n",
" > .item:last-child,\n",
" > ion-item-sliding:last-child .item {\n",
" border-bottom-right-radius: $list-inset-ios-border-radius;\n",
" border-bottom-left-radius: $list-inset-ios-border-radius;\n",
" border-bottom: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "ionic/components/list/modes/ios.scss",
"type": "replace",
"edit_start_line_idx": 152
}
|
// iOS List
// --------------------------------------------------
$list-ios-margin-top: 10px !default;
$list-ios-margin-right: 0 !default;
$list-ios-margin-bottom: 32px !default;
$list-ios-margin-left: 0 !default;
$list-inset-ios-margin-top: 16px !default;
$list-inset-ios-margin-right: 16px !default;
$list-inset-ios-margin-bottom: 16px !default;
$list-inset-ios-margin-left: 16px !default;
$list-inset-ios-border-radius: 4px !default;
$list-ios-header-padding: 10px $item-ios-padding-right 10px $item-ios-padding-left !default;
$list-ios-header-font-size: 1.2rem !default;
$list-ios-header-font-weight: 500 !default;
$list-ios-header-letter-spacing: 0.1rem !default;
$list-ios-header-color: #333 !default;
$list-ios-border-color: $list-border-color !default;
/****************/
/* DEFAULT LIST */
/****************/
.list {
margin: -1px $list-ios-margin-right $list-ios-margin-bottom $list-ios-margin-left;
ion-header {
position: relative;
padding: $list-ios-header-padding;
font-size: $list-ios-header-font-size;
font-weight: $list-ios-header-font-weight;
letter-spacing: $list-ios-header-letter-spacing;
text-transform: uppercase;
color: $list-ios-header-color;
border-bottom: 1px solid $list-ios-border-color;
}
> .item:first-child {
border-top: 1px solid $list-ios-border-color;
}
> .item:last-child,
> ion-item-sliding:last-child .item {
border-bottom: 1px solid $list-ios-border-color;
.item-inner {
border-bottom: none;
}
}
.item-inner {
border-bottom: 1px solid $list-ios-border-color;
}
// If the item has the no-lines attribute remove the bottom border from:
// the item itself (for last-child items)
// the item-inner class (if it is not last)
.item[no-lines],
.item[no-lines] .item-inner, {
border-width: 0;
}
ion-item-options {
border-bottom: 1px solid $list-ios-border-color;
button, [button] {
min-height: 100%;
height: 100%;
margin: 0;
border: none;
border-radius: 0;
display: inline-flex;
align-items: center;
box-sizing: border-box;
&:before{
margin: 0 auto;
}
}
}
}
.list + .list {
margin-top: $list-ios-margin-top + $list-ios-margin-bottom;
ion-header {
margin-top: -$list-ios-margin-top;
padding-top: 0;
}
}
&.hairlines .list {
ion-item-options {
border-width: 0.55px;
}
ion-header {
border-bottom-width: 0.55px;
}
.item {
.item-inner {
border-width: 0.55px;
}
}
> .item:first-child {
border-top-width: 0.55px;
}
> .item:last-child,
> ion-item-sliding:last-child .item {
border-bottom-width: 0.55px;
}
}
/**************/
/* INSET LIST */
/**************/
.list[inset] {
margin: $list-inset-ios-margin-top $list-inset-ios-margin-right $list-inset-ios-margin-bottom $list-inset-ios-margin-left;
border-radius: $list-inset-ios-border-radius;
.item {
border-bottom: 1px solid $list-ios-border-color;
.item-inner {
border-bottom: none;
}
}
> .item:first-child,
ion-header {
border-top-right-radius: $list-inset-ios-border-radius;
border-top-left-radius: $list-inset-ios-border-radius;
}
> .item:first-child {
border-top: none;
}
> .item:last-child,
> ion-item-sliding:last-child .item {
border-bottom-right-radius: $list-inset-ios-border-radius;
border-bottom-left-radius: $list-inset-ios-border-radius;
border-bottom: none;
}
}
.list[inset] + .list[inset] {
margin-top: 0;
}
&.hairlines .list[inset] {
.item {
border-width: 0.55px;
}
}
/*****************/
/* NO LINES LIST */
/*****************/
.list[no-lines],
&.hairlines .list[no-lines] {
ion-header,
.item,
.item .item-inner {
border-width: 0;
}
}
|
ionic/components/list/modes/ios.scss
| 1 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.9898058772087097,
0.06289636343717575,
0.0001769544032867998,
0.0024375650100409985,
0.22063742578029633
] |
{
"id": 2,
"code_window": [
" border-top: none;\n",
" }\n",
"\n",
" > .item:last-child,\n",
" > ion-item-sliding:last-child .item {\n",
" border-bottom-right-radius: $list-inset-ios-border-radius;\n",
" border-bottom-left-radius: $list-inset-ios-border-radius;\n",
" border-bottom: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "ionic/components/list/modes/ios.scss",
"type": "replace",
"edit_start_line_idx": 152
}
|
import {App, IonicApp, Page} from 'ionic/ionic';
@Page({templateUrl: 'page1.html'})
class Page1 {}
@App({
templateUrl: 'main.html'
})
class E2EApp {
constructor(app: IonicApp) {
this.app = app;
this.rootView = Page1;
}
openPage(menu, page) {
// close the menu when clicking a link from the menu
menu.close();
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
let nav = this.app.getComponent('nav');
nav.setRoot(page.component);
}
}
|
ionic/components/menu/test/push/index.ts
| 0 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.00017343577928841114,
0.00016856362344697118,
0.00016607741417828947,
0.00016617767687421292,
0.00000344537761520769
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.