Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions docs/migration/feedback.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,15 +14,15 @@ Below you can find a list of relevant feedback changes and issues that have been
We have streamlined the interface for interacting with the Feedback widget. Below is a list of public functions that
existed in 7.x and a description of how they have changed in v8.

| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<FeedbackDialog>` so you can control showing and hiding of the feedback form directly. |
| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<ReturnType<FeedbackModalIntegration['createDialog']>>` so you can control showing and hiding of the feedback form directly. |

### API Examples

Expand Down
15 changes: 10 additions & 5 deletions packages/feedback/src/core/integration.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import { getClient } from '@sentry/core';
import type {
FeedbackDialog,
FeedbackInternalOptions,
FeedbackModalIntegration,
FeedbackScreenshotIntegration,
Expand DownExpand Up@@ -56,7 +55,9 @@ export const buildFeedbackIntegration = ({
}: BuilderOptions): IntegrationFn<
Integration & {
attachTo(el: Element | string, optionOverrides?: OverrideFeedbackConfiguration): Unsubscribe;
createForm(optionOverrides?: OverrideFeedbackConfiguration): Promise<FeedbackDialog>;
createForm(
optionOverrides?: OverrideFeedbackConfiguration,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>>;
createWidget(optionOverrides?: OverrideFeedbackConfiguration): ActorComponent;
remove(): void;
}
Expand DownExpand Up@@ -179,7 +180,9 @@ export const buildFeedbackIntegration = ({
return integration as I;
};

const _loadAndRenderDialog = async (options: FeedbackInternalOptions): Promise<FeedbackDialog> => {
const _loadAndRenderDialog = async (
options: FeedbackInternalOptions,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> => {
const screenshotRequired = options.enableScreenshot && isScreenshotSupported();
const [modalIntegration, screenshotIntegration] = await Promise.all([
_findIntegration<FeedbackModalIntegration>('FeedbackModal', getModalIntegration, 'feedbackModalIntegration'),
Expand DownExpand Up@@ -223,7 +226,7 @@ export const buildFeedbackIntegration = ({
throw new Error('Unable to attach to target element');
}

let dialog: FeedbackDialog | null = null;
let dialog: ReturnType<FeedbackModalIntegration['createDialog']> | null = null;
const handleClick = async (): Promise<void> => {
if (!dialog) {
dialog = await _loadAndRenderDialog({
Expand DownExpand Up@@ -306,7 +309,9 @@ export const buildFeedbackIntegration = ({
* Creates a new Form which you can
* Accepts partial options to override any options passed to constructor.
*/
async createForm(optionOverrides: OverrideFeedbackConfiguration = {}): Promise<FeedbackDialog> {
async createForm(
optionOverrides: OverrideFeedbackConfiguration = {},
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> {
return _loadAndRenderDialog(mergeOptions(_options, optionOverrides));
},

Expand Down
1 change: 1 addition & 0 deletions packages/feedback/src/modal/components/Dialog.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import type { FeedbackFormData, FeedbackInternalOptions } from '@sentry/types';
import { Fragment, h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import type { VNode } from 'preact';
import { useCallback, useMemo, useState } from 'preact/hooks';

import { SUCCESS_MESSAGE_TIMEOUT } from '../../constants';
import { DialogHeader } from './DialogHeader';
import type { Props as HeaderProps } from './DialogHeader';
Expand Down
16 changes: 5 additions & 11 deletions packages/feedback/src/modal/integration.tsx
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
import { getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';
import type {
CreateDialogProps,
FeedbackDialog,
FeedbackFormData,
FeedbackModalIntegration,
IntegrationFn,
User,
} from '@sentry/types';
import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/types';
import { h, render } from 'preact';
import * as hooks from 'preact/hooks';
import { DOCUMENT } from '../constants';
import { Dialog } from './components/Dialog';
import { createDialogStyles } from './components/Dialog.css';
Expand All@@ -30,7 +24,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
name: 'FeedbackModal',
// eslint-disable-next-line @typescript-eslint/no-empty-function
setupOnce() {},
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }: CreateDialogProps) => {
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }) => {
const shadowRoot = shadow as unknown as ShadowRoot;
const userKey = options.useSentryUser;
const user = getUser();
Expand All@@ -39,7 +33,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
const style = createDialogStyles();

let originalOverflow = '';
const dialog: FeedbackDialog = {
const dialog: ReturnType<FeedbackModalIntegration['createDialog']> = {
get el() {
return el;
},
Expand All@@ -66,7 +60,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
},
};

const screenshotInput = screenshotIntegration && screenshotIntegration.createInput(h, dialog, options);
const screenshotInput = screenshotIntegration && screenshotIntegration.createInput({ h, hooks, dialog, options });

const renderContent = (open: boolean): void => {
render(
Expand Down
47 changes: 27 additions & 20 deletions packages/feedback/src/screenshot/components/ScreenshotEditor.tsx
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
import type { FeedbackDialog, FeedbackInternalOptions } from '@sentry/types';
/* eslint-disable max-lines */
import type { FeedbackInternalOptions, FeedbackModalIntegration } from '@sentry/types';
import type { ComponentType, VNode, h as hType } from 'preact';
// biome-ignore lint: needed for preact
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, WINDOW } from '../../constants';
import { createScreenshotInputStyles } from './ScreenshotInput.css';
import { useTakeScreenshot } from './useTakeScreenshot';
import { useTakeScreenshotFactory } from './useTakeScreenshot';

const CROP_BUTTON_SIZE = 30;
const CROP_BUTTON_BORDER = 3;
Expand All@@ -15,8 +13,9 @@ const DPI = WINDOW.devicePixelRatio;

interface FactoryParams {
h: typeof hType;
hooks: typeof Hooks;
imageBuffer: HTMLCanvasElement;
dialog: FeedbackDialog;
dialog: ReturnType<FeedbackModalIntegration['createDialog']>;
options: FeedbackInternalOptions;
}

Expand DownExpand Up@@ -62,17 +61,25 @@ const getContainedSize = (img: HTMLCanvasElement): Box => {
return { startX: x, startY: y, endX: width + x, endY: height + y };
};

export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }: FactoryParams): ComponentType<Props> {
export function ScreenshotEditorFactory({
h, // eslint-disable-line @typescript-eslint/no-unused-vars
hooks,
imageBuffer,
dialog,
options,
}: FactoryParams): ComponentType<Props> {
const useTakeScreenshot = useTakeScreenshotFactory({ hooks });

return function ScreenshotEditor({ onError }: Props): VNode {
const styles = useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);
const styles = hooks.useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);

const canvasContainerRef = useRef<HTMLDivElement>(null);
const cropContainerRef = useRef<HTMLDivElement>(null);
const croppingRef = useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = useState(false);
const canvasContainerRef = hooks.useRef<HTMLDivElement>(null);
const cropContainerRef = hooks.useRef<HTMLDivElement>(null);
const croppingRef = hooks.useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = hooks.useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = hooks.useState(false);

useEffect(() => {
hooks.useEffect(() => {
WINDOW.addEventListener('resize', resizeCropper, false);
}, []);

Expand All@@ -99,7 +106,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
setCroppingRect({ startX: 0, startY: 0, endX: imageDimensions.width, endY: imageDimensions.height });
}

useEffect(() => {
hooks.useEffect(() => {
const cropper = croppingRef.current;
if (!cropper) {
return;
Expand DownExpand Up@@ -141,7 +148,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
DOCUMENT.addEventListener('mousemove', handleMouseMove);
}

const makeHandleMouseMove = useCallback((corner: string) => {
const makeHandleMouseMove = hooks.useCallback((corner: string) => {
return function (e: MouseEvent) {
if (!croppingRef.current) {
return;
Expand DownExpand Up@@ -218,10 +225,10 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
}

useTakeScreenshot({
onBeforeScreenshot: useCallback(() => {
onBeforeScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'none';
}, []),
onScreenshot: useCallback(
onScreenshot: hooks.useCallback(
(imageSource: HTMLVideoElement) => {
const context = imageBuffer.getContext('2d');
if (!context) {
Expand All@@ -235,13 +242,13 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
},
[imageBuffer],
),
onAfterScreenshot: useCallback(() => {
onAfterScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'block';
const container = canvasContainerRef.current;
container && container.appendChild(imageBuffer);
resizeCropper();
}, []),
onError: useCallback(error => {
onError: hooks.useCallback(error => {
(dialog.el as HTMLElement).style.display = 'block';
onError(error);
}, []),
Expand Down
74 changes: 40 additions & 34 deletions packages/feedback/src/screenshot/components/useTakeScreenshot.tsx
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,51 @@
// biome-ignore lint/nursery/noUnusedImports: reason
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useEffect } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, NAVIGATOR, WINDOW } from '../../constants';

interface FactoryParams {
hooks: typeof Hooks;
}

interface Props {
onBeforeScreenshot: () => void;
onScreenshot: (imageSource: HTMLVideoElement) => void;
onAfterScreenshot: () => void;
onError: (error: Error) => void;
}

export const useTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props): void => {
useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});
type UseTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) => void;

const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};
export function useTakeScreenshotFactory({ hooks }: FactoryParams): UseTakeScreenshot {
return function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) {
hooks.useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});

takeScreenshot().catch(onError);
}, []);
};
const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};

takeScreenshot().catch(onError);
}, []);
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions docs/migration/feedback.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,15 +14,15 @@ Below you can find a list of relevant feedback changes and issues that have been
We have streamlined the interface for interacting with the Feedback widget. Below is a list of public functions that
existed in 7.x and a description of how they have changed in v8.

| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<FeedbackDialog>` so you can control showing and hiding of the feedback form directly. |
| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<ReturnType<FeedbackModalIntegration['createDialog']>>` so you can control showing and hiding of the feedback form directly. |

### API Examples

Expand Down
15 changes: 10 additions & 5 deletions packages/feedback/src/core/integration.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import { getClient } from '@sentry/core';
import type {
FeedbackDialog,
FeedbackInternalOptions,
FeedbackModalIntegration,
FeedbackScreenshotIntegration,
Expand DownExpand Up@@ -56,7 +55,9 @@ export const buildFeedbackIntegration = ({
}: BuilderOptions): IntegrationFn<
Integration & {
attachTo(el: Element | string, optionOverrides?: OverrideFeedbackConfiguration): Unsubscribe;
createForm(optionOverrides?: OverrideFeedbackConfiguration): Promise<FeedbackDialog>;
createForm(
optionOverrides?: OverrideFeedbackConfiguration,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>>;
createWidget(optionOverrides?: OverrideFeedbackConfiguration): ActorComponent;
remove(): void;
}
Expand DownExpand Up@@ -179,7 +180,9 @@ export const buildFeedbackIntegration = ({
return integration as I;
};

const _loadAndRenderDialog = async (options: FeedbackInternalOptions): Promise<FeedbackDialog> => {
const _loadAndRenderDialog = async (
options: FeedbackInternalOptions,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> => {
const screenshotRequired = options.enableScreenshot && isScreenshotSupported();
const [modalIntegration, screenshotIntegration] = await Promise.all([
_findIntegration<FeedbackModalIntegration>('FeedbackModal', getModalIntegration, 'feedbackModalIntegration'),
Expand DownExpand Up@@ -223,7 +226,7 @@ export const buildFeedbackIntegration = ({
throw new Error('Unable to attach to target element');
}

let dialog: FeedbackDialog | null = null;
let dialog: ReturnType<FeedbackModalIntegration['createDialog']> | null = null;
const handleClick = async (): Promise<void> => {
if (!dialog) {
dialog = await _loadAndRenderDialog({
Expand DownExpand Up@@ -306,7 +309,9 @@ export const buildFeedbackIntegration = ({
* Creates a new Form which you can
* Accepts partial options to override any options passed to constructor.
*/
async createForm(optionOverrides: OverrideFeedbackConfiguration = {}): Promise<FeedbackDialog> {
async createForm(
optionOverrides: OverrideFeedbackConfiguration = {},
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> {
return _loadAndRenderDialog(mergeOptions(_options, optionOverrides));
},

Expand Down
1 change: 1 addition & 0 deletions packages/feedback/src/modal/components/Dialog.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import type { FeedbackFormData, FeedbackInternalOptions } from '@sentry/types';
import { Fragment, h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import type { VNode } from 'preact';
import { useCallback, useMemo, useState } from 'preact/hooks';

import { SUCCESS_MESSAGE_TIMEOUT } from '../../constants';
import { DialogHeader } from './DialogHeader';
import type { Props as HeaderProps } from './DialogHeader';
Expand Down
16 changes: 5 additions & 11 deletions packages/feedback/src/modal/integration.tsx
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
import { getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';
import type {
CreateDialogProps,
FeedbackDialog,
FeedbackFormData,
FeedbackModalIntegration,
IntegrationFn,
User,
} from '@sentry/types';
import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/types';
import { h, render } from 'preact';
import * as hooks from 'preact/hooks';
import { DOCUMENT } from '../constants';
import { Dialog } from './components/Dialog';
import { createDialogStyles } from './components/Dialog.css';
Expand All@@ -30,7 +24,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
name: 'FeedbackModal',
// eslint-disable-next-line @typescript-eslint/no-empty-function
setupOnce() {},
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }: CreateDialogProps) => {
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }) => {
const shadowRoot = shadow as unknown as ShadowRoot;
const userKey = options.useSentryUser;
const user = getUser();
Expand All@@ -39,7 +33,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
const style = createDialogStyles();

let originalOverflow = '';
const dialog: FeedbackDialog = {
const dialog: ReturnType<FeedbackModalIntegration['createDialog']> = {
get el() {
return el;
},
Expand All@@ -66,7 +60,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
},
};

const screenshotInput = screenshotIntegration && screenshotIntegration.createInput(h, dialog, options);
const screenshotInput = screenshotIntegration && screenshotIntegration.createInput({ h, hooks, dialog, options });

const renderContent = (open: boolean): void => {
render(
Expand Down
47 changes: 27 additions & 20 deletions packages/feedback/src/screenshot/components/ScreenshotEditor.tsx
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
import type { FeedbackDialog, FeedbackInternalOptions } from '@sentry/types';
/* eslint-disable max-lines */
import type { FeedbackInternalOptions, FeedbackModalIntegration } from '@sentry/types';
import type { ComponentType, VNode, h as hType } from 'preact';
// biome-ignore lint: needed for preact
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, WINDOW } from '../../constants';
import { createScreenshotInputStyles } from './ScreenshotInput.css';
import { useTakeScreenshot } from './useTakeScreenshot';
import { useTakeScreenshotFactory } from './useTakeScreenshot';

const CROP_BUTTON_SIZE = 30;
const CROP_BUTTON_BORDER = 3;
Expand All@@ -15,8 +13,9 @@ const DPI = WINDOW.devicePixelRatio;

interface FactoryParams {
h: typeof hType;
hooks: typeof Hooks;
imageBuffer: HTMLCanvasElement;
dialog: FeedbackDialog;
dialog: ReturnType<FeedbackModalIntegration['createDialog']>;
options: FeedbackInternalOptions;
}

Expand DownExpand Up@@ -62,17 +61,25 @@ const getContainedSize = (img: HTMLCanvasElement): Box => {
return { startX: x, startY: y, endX: width + x, endY: height + y };
};

export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }: FactoryParams): ComponentType<Props> {
export function ScreenshotEditorFactory({
h, // eslint-disable-line @typescript-eslint/no-unused-vars
hooks,
imageBuffer,
dialog,
options,
}: FactoryParams): ComponentType<Props> {
const useTakeScreenshot = useTakeScreenshotFactory({ hooks });

return function ScreenshotEditor({ onError }: Props): VNode {
const styles = useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);
const styles = hooks.useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);

const canvasContainerRef = useRef<HTMLDivElement>(null);
const cropContainerRef = useRef<HTMLDivElement>(null);
const croppingRef = useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = useState(false);
const canvasContainerRef = hooks.useRef<HTMLDivElement>(null);
const cropContainerRef = hooks.useRef<HTMLDivElement>(null);
const croppingRef = hooks.useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = hooks.useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = hooks.useState(false);

useEffect(() => {
hooks.useEffect(() => {
WINDOW.addEventListener('resize', resizeCropper, false);
}, []);

Expand All@@ -99,7 +106,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
setCroppingRect({ startX: 0, startY: 0, endX: imageDimensions.width, endY: imageDimensions.height });
}

useEffect(() => {
hooks.useEffect(() => {
const cropper = croppingRef.current;
if (!cropper) {
return;
Expand DownExpand Up@@ -141,7 +148,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
DOCUMENT.addEventListener('mousemove', handleMouseMove);
}

const makeHandleMouseMove = useCallback((corner: string) => {
const makeHandleMouseMove = hooks.useCallback((corner: string) => {
return function (e: MouseEvent) {
if (!croppingRef.current) {
return;
Expand DownExpand Up@@ -218,10 +225,10 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
}

useTakeScreenshot({
onBeforeScreenshot: useCallback(() => {
onBeforeScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'none';
}, []),
onScreenshot: useCallback(
onScreenshot: hooks.useCallback(
(imageSource: HTMLVideoElement) => {
const context = imageBuffer.getContext('2d');
if (!context) {
Expand All@@ -235,13 +242,13 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
},
[imageBuffer],
),
onAfterScreenshot: useCallback(() => {
onAfterScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'block';
const container = canvasContainerRef.current;
container && container.appendChild(imageBuffer);
resizeCropper();
}, []),
onError: useCallback(error => {
onError: hooks.useCallback(error => {
(dialog.el as HTMLElement).style.display = 'block';
onError(error);
}, []),
Expand Down
74 changes: 40 additions & 34 deletions packages/feedback/src/screenshot/components/useTakeScreenshot.tsx
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,51 @@
// biome-ignore lint/nursery/noUnusedImports: reason
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useEffect } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, NAVIGATOR, WINDOW } from '../../constants';

interface FactoryParams {
hooks: typeof Hooks;
}

interface Props {
onBeforeScreenshot: () => void;
onScreenshot: (imageSource: HTMLVideoElement) => void;
onAfterScreenshot: () => void;
onError: (error: Error) => void;
}

export const useTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props): void => {
useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});
type UseTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) => void;

const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};
export function useTakeScreenshotFactory({ hooks }: FactoryParams): UseTakeScreenshot {
return function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) {
hooks.useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});

takeScreenshot().catch(onError);
}, []);
};
const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};

takeScreenshot().catch(onError);
}, []);
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions docs/migration/feedback.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,15 +14,15 @@ Below you can find a list of relevant feedback changes and issues that have been
We have streamlined the interface for interacting with the Feedback widget. Below is a list of public functions that
existed in 7.x and a description of how they have changed in v8.

| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<FeedbackDialog>` so you can control showing and hiding of the feedback form directly. |
| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<ReturnType<FeedbackModalIntegration['createDialog']>>` so you can control showing and hiding of the feedback form directly. |

### API Examples

Expand Down
15 changes: 10 additions & 5 deletions packages/feedback/src/core/integration.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import { getClient } from '@sentry/core';
import type {
FeedbackDialog,
FeedbackInternalOptions,
FeedbackModalIntegration,
FeedbackScreenshotIntegration,
Expand DownExpand Up@@ -56,7 +55,9 @@ export const buildFeedbackIntegration = ({
}: BuilderOptions): IntegrationFn<
Integration & {
attachTo(el: Element | string, optionOverrides?: OverrideFeedbackConfiguration): Unsubscribe;
createForm(optionOverrides?: OverrideFeedbackConfiguration): Promise<FeedbackDialog>;
createForm(
optionOverrides?: OverrideFeedbackConfiguration,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>>;
createWidget(optionOverrides?: OverrideFeedbackConfiguration): ActorComponent;
remove(): void;
}
Expand DownExpand Up@@ -179,7 +180,9 @@ export const buildFeedbackIntegration = ({
return integration as I;
};

const _loadAndRenderDialog = async (options: FeedbackInternalOptions): Promise<FeedbackDialog> => {
const _loadAndRenderDialog = async (
options: FeedbackInternalOptions,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> => {
const screenshotRequired = options.enableScreenshot && isScreenshotSupported();
const [modalIntegration, screenshotIntegration] = await Promise.all([
_findIntegration<FeedbackModalIntegration>('FeedbackModal', getModalIntegration, 'feedbackModalIntegration'),
Expand DownExpand Up@@ -223,7 +226,7 @@ export const buildFeedbackIntegration = ({
throw new Error('Unable to attach to target element');
}

let dialog: FeedbackDialog | null = null;
let dialog: ReturnType<FeedbackModalIntegration['createDialog']> | null = null;
const handleClick = async (): Promise<void> => {
if (!dialog) {
dialog = await _loadAndRenderDialog({
Expand DownExpand Up@@ -306,7 +309,9 @@ export const buildFeedbackIntegration = ({
* Creates a new Form which you can
* Accepts partial options to override any options passed to constructor.
*/
async createForm(optionOverrides: OverrideFeedbackConfiguration = {}): Promise<FeedbackDialog> {
async createForm(
optionOverrides: OverrideFeedbackConfiguration = {},
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> {
return _loadAndRenderDialog(mergeOptions(_options, optionOverrides));
},

Expand Down
1 change: 1 addition & 0 deletions packages/feedback/src/modal/components/Dialog.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import type { FeedbackFormData, FeedbackInternalOptions } from '@sentry/types';
import { Fragment, h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import type { VNode } from 'preact';
import { useCallback, useMemo, useState } from 'preact/hooks';

import { SUCCESS_MESSAGE_TIMEOUT } from '../../constants';
import { DialogHeader } from './DialogHeader';
import type { Props as HeaderProps } from './DialogHeader';
Expand Down
16 changes: 5 additions & 11 deletions packages/feedback/src/modal/integration.tsx
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
import { getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';
import type {
CreateDialogProps,
FeedbackDialog,
FeedbackFormData,
FeedbackModalIntegration,
IntegrationFn,
User,
} from '@sentry/types';
import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/types';
import { h, render } from 'preact';
import * as hooks from 'preact/hooks';
import { DOCUMENT } from '../constants';
import { Dialog } from './components/Dialog';
import { createDialogStyles } from './components/Dialog.css';
Expand All@@ -30,7 +24,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
name: 'FeedbackModal',
// eslint-disable-next-line @typescript-eslint/no-empty-function
setupOnce() {},
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }: CreateDialogProps) => {
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }) => {
const shadowRoot = shadow as unknown as ShadowRoot;
const userKey = options.useSentryUser;
const user = getUser();
Expand All@@ -39,7 +33,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
const style = createDialogStyles();

let originalOverflow = '';
const dialog: FeedbackDialog = {
const dialog: ReturnType<FeedbackModalIntegration['createDialog']> = {
get el() {
return el;
},
Expand All@@ -66,7 +60,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
},
};

const screenshotInput = screenshotIntegration && screenshotIntegration.createInput(h, dialog, options);
const screenshotInput = screenshotIntegration && screenshotIntegration.createInput({ h, hooks, dialog, options });

const renderContent = (open: boolean): void => {
render(
Expand Down
47 changes: 27 additions & 20 deletions packages/feedback/src/screenshot/components/ScreenshotEditor.tsx
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
import type { FeedbackDialog, FeedbackInternalOptions } from '@sentry/types';
/* eslint-disable max-lines */
import type { FeedbackInternalOptions, FeedbackModalIntegration } from '@sentry/types';
import type { ComponentType, VNode, h as hType } from 'preact';
// biome-ignore lint: needed for preact
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, WINDOW } from '../../constants';
import { createScreenshotInputStyles } from './ScreenshotInput.css';
import { useTakeScreenshot } from './useTakeScreenshot';
import { useTakeScreenshotFactory } from './useTakeScreenshot';

const CROP_BUTTON_SIZE = 30;
const CROP_BUTTON_BORDER = 3;
Expand All@@ -15,8 +13,9 @@ const DPI = WINDOW.devicePixelRatio;

interface FactoryParams {
h: typeof hType;
hooks: typeof Hooks;
imageBuffer: HTMLCanvasElement;
dialog: FeedbackDialog;
dialog: ReturnType<FeedbackModalIntegration['createDialog']>;
options: FeedbackInternalOptions;
}

Expand DownExpand Up@@ -62,17 +61,25 @@ const getContainedSize = (img: HTMLCanvasElement): Box => {
return { startX: x, startY: y, endX: width + x, endY: height + y };
};

export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }: FactoryParams): ComponentType<Props> {
export function ScreenshotEditorFactory({
h, // eslint-disable-line @typescript-eslint/no-unused-vars
hooks,
imageBuffer,
dialog,
options,
}: FactoryParams): ComponentType<Props> {
const useTakeScreenshot = useTakeScreenshotFactory({ hooks });

return function ScreenshotEditor({ onError }: Props): VNode {
const styles = useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);
const styles = hooks.useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);

const canvasContainerRef = useRef<HTMLDivElement>(null);
const cropContainerRef = useRef<HTMLDivElement>(null);
const croppingRef = useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = useState(false);
const canvasContainerRef = hooks.useRef<HTMLDivElement>(null);
const cropContainerRef = hooks.useRef<HTMLDivElement>(null);
const croppingRef = hooks.useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = hooks.useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = hooks.useState(false);

useEffect(() => {
hooks.useEffect(() => {
WINDOW.addEventListener('resize', resizeCropper, false);
}, []);

Expand All@@ -99,7 +106,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
setCroppingRect({ startX: 0, startY: 0, endX: imageDimensions.width, endY: imageDimensions.height });
}

useEffect(() => {
hooks.useEffect(() => {
const cropper = croppingRef.current;
if (!cropper) {
return;
Expand DownExpand Up@@ -141,7 +148,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
DOCUMENT.addEventListener('mousemove', handleMouseMove);
}

const makeHandleMouseMove = useCallback((corner: string) => {
const makeHandleMouseMove = hooks.useCallback((corner: string) => {
return function (e: MouseEvent) {
if (!croppingRef.current) {
return;
Expand DownExpand Up@@ -218,10 +225,10 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
}

useTakeScreenshot({
onBeforeScreenshot: useCallback(() => {
onBeforeScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'none';
}, []),
onScreenshot: useCallback(
onScreenshot: hooks.useCallback(
(imageSource: HTMLVideoElement) => {
const context = imageBuffer.getContext('2d');
if (!context) {
Expand All@@ -235,13 +242,13 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
},
[imageBuffer],
),
onAfterScreenshot: useCallback(() => {
onAfterScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'block';
const container = canvasContainerRef.current;
container && container.appendChild(imageBuffer);
resizeCropper();
}, []),
onError: useCallback(error => {
onError: hooks.useCallback(error => {
(dialog.el as HTMLElement).style.display = 'block';
onError(error);
}, []),
Expand Down
74 changes: 40 additions & 34 deletions packages/feedback/src/screenshot/components/useTakeScreenshot.tsx
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,51 @@
// biome-ignore lint/nursery/noUnusedImports: reason
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useEffect } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, NAVIGATOR, WINDOW } from '../../constants';

interface FactoryParams {
hooks: typeof Hooks;
}

interface Props {
onBeforeScreenshot: () => void;
onScreenshot: (imageSource: HTMLVideoElement) => void;
onAfterScreenshot: () => void;
onError: (error: Error) => void;
}

export const useTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props): void => {
useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});
type UseTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) => void;

const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};
export function useTakeScreenshotFactory({ hooks }: FactoryParams): UseTakeScreenshot {
return function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) {
hooks.useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});

takeScreenshot().catch(onError);
}, []);
};
const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};

takeScreenshot().catch(onError);
}, []);
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions docs/migration/feedback.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,15 +14,15 @@ Below you can find a list of relevant feedback changes and issues that have been
We have streamlined the interface for interacting with the Feedback widget. Below is a list of public functions that
existed in 7.x and a description of how they have changed in v8.

| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<FeedbackDialog>` so you can control showing and hiding of the feedback form directly. |
| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<ReturnType<FeedbackModalIntegration['createDialog']>>` so you can control showing and hiding of the feedback form directly. |

### API Examples

Expand Down
15 changes: 10 additions & 5 deletions packages/feedback/src/core/integration.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import { getClient } from '@sentry/core';
import type {
FeedbackDialog,
FeedbackInternalOptions,
FeedbackModalIntegration,
FeedbackScreenshotIntegration,
Expand DownExpand Up@@ -56,7 +55,9 @@ export const buildFeedbackIntegration = ({
}: BuilderOptions): IntegrationFn<
Integration & {
attachTo(el: Element | string, optionOverrides?: OverrideFeedbackConfiguration): Unsubscribe;
createForm(optionOverrides?: OverrideFeedbackConfiguration): Promise<FeedbackDialog>;
createForm(
optionOverrides?: OverrideFeedbackConfiguration,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>>;
createWidget(optionOverrides?: OverrideFeedbackConfiguration): ActorComponent;
remove(): void;
}
Expand DownExpand Up@@ -179,7 +180,9 @@ export const buildFeedbackIntegration = ({
return integration as I;
};

const _loadAndRenderDialog = async (options: FeedbackInternalOptions): Promise<FeedbackDialog> => {
const _loadAndRenderDialog = async (
options: FeedbackInternalOptions,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> => {
const screenshotRequired = options.enableScreenshot && isScreenshotSupported();
const [modalIntegration, screenshotIntegration] = await Promise.all([
_findIntegration<FeedbackModalIntegration>('FeedbackModal', getModalIntegration, 'feedbackModalIntegration'),
Expand DownExpand Up@@ -223,7 +226,7 @@ export const buildFeedbackIntegration = ({
throw new Error('Unable to attach to target element');
}

let dialog: FeedbackDialog | null = null;
let dialog: ReturnType<FeedbackModalIntegration['createDialog']> | null = null;
const handleClick = async (): Promise<void> => {
if (!dialog) {
dialog = await _loadAndRenderDialog({
Expand DownExpand Up@@ -306,7 +309,9 @@ export const buildFeedbackIntegration = ({
* Creates a new Form which you can
* Accepts partial options to override any options passed to constructor.
*/
async createForm(optionOverrides: OverrideFeedbackConfiguration = {}): Promise<FeedbackDialog> {
async createForm(
optionOverrides: OverrideFeedbackConfiguration = {},
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> {
return _loadAndRenderDialog(mergeOptions(_options, optionOverrides));
},

Expand Down
1 change: 1 addition & 0 deletions packages/feedback/src/modal/components/Dialog.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import type { FeedbackFormData, FeedbackInternalOptions } from '@sentry/types';
import { Fragment, h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import type { VNode } from 'preact';
import { useCallback, useMemo, useState } from 'preact/hooks';

import { SUCCESS_MESSAGE_TIMEOUT } from '../../constants';
import { DialogHeader } from './DialogHeader';
import type { Props as HeaderProps } from './DialogHeader';
Expand Down
16 changes: 5 additions & 11 deletions packages/feedback/src/modal/integration.tsx
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
import { getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';
import type {
CreateDialogProps,
FeedbackDialog,
FeedbackFormData,
FeedbackModalIntegration,
IntegrationFn,
User,
} from '@sentry/types';
import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/types';
import { h, render } from 'preact';
import * as hooks from 'preact/hooks';
import { DOCUMENT } from '../constants';
import { Dialog } from './components/Dialog';
import { createDialogStyles } from './components/Dialog.css';
Expand All@@ -30,7 +24,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
name: 'FeedbackModal',
// eslint-disable-next-line @typescript-eslint/no-empty-function
setupOnce() {},
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }: CreateDialogProps) => {
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }) => {
const shadowRoot = shadow as unknown as ShadowRoot;
const userKey = options.useSentryUser;
const user = getUser();
Expand All@@ -39,7 +33,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
const style = createDialogStyles();

let originalOverflow = '';
const dialog: FeedbackDialog = {
const dialog: ReturnType<FeedbackModalIntegration['createDialog']> = {
get el() {
return el;
},
Expand All@@ -66,7 +60,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
},
};

const screenshotInput = screenshotIntegration && screenshotIntegration.createInput(h, dialog, options);
const screenshotInput = screenshotIntegration && screenshotIntegration.createInput({ h, hooks, dialog, options });

const renderContent = (open: boolean): void => {
render(
Expand Down
47 changes: 27 additions & 20 deletions packages/feedback/src/screenshot/components/ScreenshotEditor.tsx
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
import type { FeedbackDialog, FeedbackInternalOptions } from '@sentry/types';
/* eslint-disable max-lines */
import type { FeedbackInternalOptions, FeedbackModalIntegration } from '@sentry/types';
import type { ComponentType, VNode, h as hType } from 'preact';
// biome-ignore lint: needed for preact
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, WINDOW } from '../../constants';
import { createScreenshotInputStyles } from './ScreenshotInput.css';
import { useTakeScreenshot } from './useTakeScreenshot';
import { useTakeScreenshotFactory } from './useTakeScreenshot';

const CROP_BUTTON_SIZE = 30;
const CROP_BUTTON_BORDER = 3;
Expand All@@ -15,8 +13,9 @@ const DPI = WINDOW.devicePixelRatio;

interface FactoryParams {
h: typeof hType;
hooks: typeof Hooks;
imageBuffer: HTMLCanvasElement;
dialog: FeedbackDialog;
dialog: ReturnType<FeedbackModalIntegration['createDialog']>;
options: FeedbackInternalOptions;
}

Expand DownExpand Up@@ -62,17 +61,25 @@ const getContainedSize = (img: HTMLCanvasElement): Box => {
return { startX: x, startY: y, endX: width + x, endY: height + y };
};

export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }: FactoryParams): ComponentType<Props> {
export function ScreenshotEditorFactory({
h, // eslint-disable-line @typescript-eslint/no-unused-vars
hooks,
imageBuffer,
dialog,
options,
}: FactoryParams): ComponentType<Props> {
const useTakeScreenshot = useTakeScreenshotFactory({ hooks });

return function ScreenshotEditor({ onError }: Props): VNode {
const styles = useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);
const styles = hooks.useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);

const canvasContainerRef = useRef<HTMLDivElement>(null);
const cropContainerRef = useRef<HTMLDivElement>(null);
const croppingRef = useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = useState(false);
const canvasContainerRef = hooks.useRef<HTMLDivElement>(null);
const cropContainerRef = hooks.useRef<HTMLDivElement>(null);
const croppingRef = hooks.useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = hooks.useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = hooks.useState(false);

useEffect(() => {
hooks.useEffect(() => {
WINDOW.addEventListener('resize', resizeCropper, false);
}, []);

Expand All@@ -99,7 +106,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
setCroppingRect({ startX: 0, startY: 0, endX: imageDimensions.width, endY: imageDimensions.height });
}

useEffect(() => {
hooks.useEffect(() => {
const cropper = croppingRef.current;
if (!cropper) {
return;
Expand DownExpand Up@@ -141,7 +148,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
DOCUMENT.addEventListener('mousemove', handleMouseMove);
}

const makeHandleMouseMove = useCallback((corner: string) => {
const makeHandleMouseMove = hooks.useCallback((corner: string) => {
return function (e: MouseEvent) {
if (!croppingRef.current) {
return;
Expand DownExpand Up@@ -218,10 +225,10 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
}

useTakeScreenshot({
onBeforeScreenshot: useCallback(() => {
onBeforeScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'none';
}, []),
onScreenshot: useCallback(
onScreenshot: hooks.useCallback(
(imageSource: HTMLVideoElement) => {
const context = imageBuffer.getContext('2d');
if (!context) {
Expand All@@ -235,13 +242,13 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
},
[imageBuffer],
),
onAfterScreenshot: useCallback(() => {
onAfterScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'block';
const container = canvasContainerRef.current;
container && container.appendChild(imageBuffer);
resizeCropper();
}, []),
onError: useCallback(error => {
onError: hooks.useCallback(error => {
(dialog.el as HTMLElement).style.display = 'block';
onError(error);
}, []),
Expand Down
74 changes: 40 additions & 34 deletions packages/feedback/src/screenshot/components/useTakeScreenshot.tsx
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,51 @@
// biome-ignore lint/nursery/noUnusedImports: reason
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useEffect } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, NAVIGATOR, WINDOW } from '../../constants';

interface FactoryParams {
hooks: typeof Hooks;
}

interface Props {
onBeforeScreenshot: () => void;
onScreenshot: (imageSource: HTMLVideoElement) => void;
onAfterScreenshot: () => void;
onError: (error: Error) => void;
}

export const useTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props): void => {
useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});
type UseTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) => void;

const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};
export function useTakeScreenshotFactory({ hooks }: FactoryParams): UseTakeScreenshot {
return function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) {
hooks.useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});

takeScreenshot().catch(onError);
}, []);
};
const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};

takeScreenshot().catch(onError);
}, []);
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions docs/migration/feedback.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,15 +14,15 @@ Below you can find a list of relevant feedback changes and issues that have been
We have streamlined the interface for interacting with the Feedback widget. Below is a list of public functions that
existed in 7.x and a description of how they have changed in v8.

| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<FeedbackDialog>` so you can control showing and hiding of the feedback form directly. |
| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<ReturnType<FeedbackModalIntegration['createDialog']>>` so you can control showing and hiding of the feedback form directly. |

### API Examples

Expand Down
15 changes: 10 additions & 5 deletions packages/feedback/src/core/integration.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import { getClient } from '@sentry/core';
import type {
FeedbackDialog,
FeedbackInternalOptions,
FeedbackModalIntegration,
FeedbackScreenshotIntegration,
Expand DownExpand Up@@ -56,7 +55,9 @@ export const buildFeedbackIntegration = ({
}: BuilderOptions): IntegrationFn<
Integration & {
attachTo(el: Element | string, optionOverrides?: OverrideFeedbackConfiguration): Unsubscribe;
createForm(optionOverrides?: OverrideFeedbackConfiguration): Promise<FeedbackDialog>;
createForm(
optionOverrides?: OverrideFeedbackConfiguration,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>>;
createWidget(optionOverrides?: OverrideFeedbackConfiguration): ActorComponent;
remove(): void;
}
Expand DownExpand Up@@ -179,7 +180,9 @@ export const buildFeedbackIntegration = ({
return integration as I;
};

const _loadAndRenderDialog = async (options: FeedbackInternalOptions): Promise<FeedbackDialog> => {
const _loadAndRenderDialog = async (
options: FeedbackInternalOptions,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> => {
const screenshotRequired = options.enableScreenshot && isScreenshotSupported();
const [modalIntegration, screenshotIntegration] = await Promise.all([
_findIntegration<FeedbackModalIntegration>('FeedbackModal', getModalIntegration, 'feedbackModalIntegration'),
Expand DownExpand Up@@ -223,7 +226,7 @@ export const buildFeedbackIntegration = ({
throw new Error('Unable to attach to target element');
}

let dialog: FeedbackDialog | null = null;
let dialog: ReturnType<FeedbackModalIntegration['createDialog']> | null = null;
const handleClick = async (): Promise<void> => {
if (!dialog) {
dialog = await _loadAndRenderDialog({
Expand DownExpand Up@@ -306,7 +309,9 @@ export const buildFeedbackIntegration = ({
* Creates a new Form which you can
* Accepts partial options to override any options passed to constructor.
*/
async createForm(optionOverrides: OverrideFeedbackConfiguration = {}): Promise<FeedbackDialog> {
async createForm(
optionOverrides: OverrideFeedbackConfiguration = {},
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> {
return _loadAndRenderDialog(mergeOptions(_options, optionOverrides));
},

Expand Down
1 change: 1 addition & 0 deletions packages/feedback/src/modal/components/Dialog.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import type { FeedbackFormData, FeedbackInternalOptions } from '@sentry/types';
import { Fragment, h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import type { VNode } from 'preact';
import { useCallback, useMemo, useState } from 'preact/hooks';

import { SUCCESS_MESSAGE_TIMEOUT } from '../../constants';
import { DialogHeader } from './DialogHeader';
import type { Props as HeaderProps } from './DialogHeader';
Expand Down
16 changes: 5 additions & 11 deletions packages/feedback/src/modal/integration.tsx
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
import { getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';
import type {
CreateDialogProps,
FeedbackDialog,
FeedbackFormData,
FeedbackModalIntegration,
IntegrationFn,
User,
} from '@sentry/types';
import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/types';
import { h, render } from 'preact';
import * as hooks from 'preact/hooks';
import { DOCUMENT } from '../constants';
import { Dialog } from './components/Dialog';
import { createDialogStyles } from './components/Dialog.css';
Expand All@@ -30,7 +24,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
name: 'FeedbackModal',
// eslint-disable-next-line @typescript-eslint/no-empty-function
setupOnce() {},
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }: CreateDialogProps) => {
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }) => {
const shadowRoot = shadow as unknown as ShadowRoot;
const userKey = options.useSentryUser;
const user = getUser();
Expand All@@ -39,7 +33,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
const style = createDialogStyles();

let originalOverflow = '';
const dialog: FeedbackDialog = {
const dialog: ReturnType<FeedbackModalIntegration['createDialog']> = {
get el() {
return el;
},
Expand All@@ -66,7 +60,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
},
};

const screenshotInput = screenshotIntegration && screenshotIntegration.createInput(h, dialog, options);
const screenshotInput = screenshotIntegration && screenshotIntegration.createInput({ h, hooks, dialog, options });

const renderContent = (open: boolean): void => {
render(
Expand Down
47 changes: 27 additions & 20 deletions packages/feedback/src/screenshot/components/ScreenshotEditor.tsx
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
import type { FeedbackDialog, FeedbackInternalOptions } from '@sentry/types';
/* eslint-disable max-lines */
import type { FeedbackInternalOptions, FeedbackModalIntegration } from '@sentry/types';
import type { ComponentType, VNode, h as hType } from 'preact';
// biome-ignore lint: needed for preact
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, WINDOW } from '../../constants';
import { createScreenshotInputStyles } from './ScreenshotInput.css';
import { useTakeScreenshot } from './useTakeScreenshot';
import { useTakeScreenshotFactory } from './useTakeScreenshot';

const CROP_BUTTON_SIZE = 30;
const CROP_BUTTON_BORDER = 3;
Expand All@@ -15,8 +13,9 @@ const DPI = WINDOW.devicePixelRatio;

interface FactoryParams {
h: typeof hType;
hooks: typeof Hooks;
imageBuffer: HTMLCanvasElement;
dialog: FeedbackDialog;
dialog: ReturnType<FeedbackModalIntegration['createDialog']>;
options: FeedbackInternalOptions;
}

Expand DownExpand Up@@ -62,17 +61,25 @@ const getContainedSize = (img: HTMLCanvasElement): Box => {
return { startX: x, startY: y, endX: width + x, endY: height + y };
};

export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }: FactoryParams): ComponentType<Props> {
export function ScreenshotEditorFactory({
h, // eslint-disable-line @typescript-eslint/no-unused-vars
hooks,
imageBuffer,
dialog,
options,
}: FactoryParams): ComponentType<Props> {
const useTakeScreenshot = useTakeScreenshotFactory({ hooks });

return function ScreenshotEditor({ onError }: Props): VNode {
const styles = useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);
const styles = hooks.useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);

const canvasContainerRef = useRef<HTMLDivElement>(null);
const cropContainerRef = useRef<HTMLDivElement>(null);
const croppingRef = useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = useState(false);
const canvasContainerRef = hooks.useRef<HTMLDivElement>(null);
const cropContainerRef = hooks.useRef<HTMLDivElement>(null);
const croppingRef = hooks.useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = hooks.useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = hooks.useState(false);

useEffect(() => {
hooks.useEffect(() => {
WINDOW.addEventListener('resize', resizeCropper, false);
}, []);

Expand All@@ -99,7 +106,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
setCroppingRect({ startX: 0, startY: 0, endX: imageDimensions.width, endY: imageDimensions.height });
}

useEffect(() => {
hooks.useEffect(() => {
const cropper = croppingRef.current;
if (!cropper) {
return;
Expand DownExpand Up@@ -141,7 +148,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
DOCUMENT.addEventListener('mousemove', handleMouseMove);
}

const makeHandleMouseMove = useCallback((corner: string) => {
const makeHandleMouseMove = hooks.useCallback((corner: string) => {
return function (e: MouseEvent) {
if (!croppingRef.current) {
return;
Expand DownExpand Up@@ -218,10 +225,10 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
}

useTakeScreenshot({
onBeforeScreenshot: useCallback(() => {
onBeforeScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'none';
}, []),
onScreenshot: useCallback(
onScreenshot: hooks.useCallback(
(imageSource: HTMLVideoElement) => {
const context = imageBuffer.getContext('2d');
if (!context) {
Expand All@@ -235,13 +242,13 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
},
[imageBuffer],
),
onAfterScreenshot: useCallback(() => {
onAfterScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'block';
const container = canvasContainerRef.current;
container && container.appendChild(imageBuffer);
resizeCropper();
}, []),
onError: useCallback(error => {
onError: hooks.useCallback(error => {
(dialog.el as HTMLElement).style.display = 'block';
onError(error);
}, []),
Expand Down
74 changes: 40 additions & 34 deletions packages/feedback/src/screenshot/components/useTakeScreenshot.tsx
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,51 @@
// biome-ignore lint/nursery/noUnusedImports: reason
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useEffect } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, NAVIGATOR, WINDOW } from '../../constants';

interface FactoryParams {
hooks: typeof Hooks;
}

interface Props {
onBeforeScreenshot: () => void;
onScreenshot: (imageSource: HTMLVideoElement) => void;
onAfterScreenshot: () => void;
onError: (error: Error) => void;
}

export const useTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props): void => {
useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});
type UseTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) => void;

const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};
export function useTakeScreenshotFactory({ hooks }: FactoryParams): UseTakeScreenshot {
return function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) {
hooks.useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});

takeScreenshot().catch(onError);
}, []);
};
const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};

takeScreenshot().catch(onError);
}, []);
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions docs/migration/feedback.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,15 +14,15 @@ Below you can find a list of relevant feedback changes and issues that have been
We have streamlined the interface for interacting with the Feedback widget. Below is a list of public functions that
existed in 7.x and a description of how they have changed in v8.

| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<FeedbackDialog>` so you can control showing and hiding of the feedback form directly. |
| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<ReturnType<FeedbackModalIntegration['createDialog']>>` so you can control showing and hiding of the feedback form directly. |

### API Examples

Expand Down
15 changes: 10 additions & 5 deletions packages/feedback/src/core/integration.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import { getClient } from '@sentry/core';
import type {
FeedbackDialog,
FeedbackInternalOptions,
FeedbackModalIntegration,
FeedbackScreenshotIntegration,
Expand DownExpand Up@@ -56,7 +55,9 @@ export const buildFeedbackIntegration = ({
}: BuilderOptions): IntegrationFn<
Integration & {
attachTo(el: Element | string, optionOverrides?: OverrideFeedbackConfiguration): Unsubscribe;
createForm(optionOverrides?: OverrideFeedbackConfiguration): Promise<FeedbackDialog>;
createForm(
optionOverrides?: OverrideFeedbackConfiguration,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>>;
createWidget(optionOverrides?: OverrideFeedbackConfiguration): ActorComponent;
remove(): void;
}
Expand DownExpand Up@@ -179,7 +180,9 @@ export const buildFeedbackIntegration = ({
return integration as I;
};

const _loadAndRenderDialog = async (options: FeedbackInternalOptions): Promise<FeedbackDialog> => {
const _loadAndRenderDialog = async (
options: FeedbackInternalOptions,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> => {
const screenshotRequired = options.enableScreenshot && isScreenshotSupported();
const [modalIntegration, screenshotIntegration] = await Promise.all([
_findIntegration<FeedbackModalIntegration>('FeedbackModal', getModalIntegration, 'feedbackModalIntegration'),
Expand DownExpand Up@@ -223,7 +226,7 @@ export const buildFeedbackIntegration = ({
throw new Error('Unable to attach to target element');
}

let dialog: FeedbackDialog | null = null;
let dialog: ReturnType<FeedbackModalIntegration['createDialog']> | null = null;
const handleClick = async (): Promise<void> => {
if (!dialog) {
dialog = await _loadAndRenderDialog({
Expand DownExpand Up@@ -306,7 +309,9 @@ export const buildFeedbackIntegration = ({
* Creates a new Form which you can
* Accepts partial options to override any options passed to constructor.
*/
async createForm(optionOverrides: OverrideFeedbackConfiguration = {}): Promise<FeedbackDialog> {
async createForm(
optionOverrides: OverrideFeedbackConfiguration = {},
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> {
return _loadAndRenderDialog(mergeOptions(_options, optionOverrides));
},

Expand Down
1 change: 1 addition & 0 deletions packages/feedback/src/modal/components/Dialog.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import type { FeedbackFormData, FeedbackInternalOptions } from '@sentry/types';
import { Fragment, h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import type { VNode } from 'preact';
import { useCallback, useMemo, useState } from 'preact/hooks';

import { SUCCESS_MESSAGE_TIMEOUT } from '../../constants';
import { DialogHeader } from './DialogHeader';
import type { Props as HeaderProps } from './DialogHeader';
Expand Down
16 changes: 5 additions & 11 deletions packages/feedback/src/modal/integration.tsx
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
import { getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';
import type {
CreateDialogProps,
FeedbackDialog,
FeedbackFormData,
FeedbackModalIntegration,
IntegrationFn,
User,
} from '@sentry/types';
import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/types';
import { h, render } from 'preact';
import * as hooks from 'preact/hooks';
import { DOCUMENT } from '../constants';
import { Dialog } from './components/Dialog';
import { createDialogStyles } from './components/Dialog.css';
Expand All@@ -30,7 +24,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
name: 'FeedbackModal',
// eslint-disable-next-line @typescript-eslint/no-empty-function
setupOnce() {},
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }: CreateDialogProps) => {
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }) => {
const shadowRoot = shadow as unknown as ShadowRoot;
const userKey = options.useSentryUser;
const user = getUser();
Expand All@@ -39,7 +33,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
const style = createDialogStyles();

let originalOverflow = '';
const dialog: FeedbackDialog = {
const dialog: ReturnType<FeedbackModalIntegration['createDialog']> = {
get el() {
return el;
},
Expand All@@ -66,7 +60,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
},
};

const screenshotInput = screenshotIntegration && screenshotIntegration.createInput(h, dialog, options);
const screenshotInput = screenshotIntegration && screenshotIntegration.createInput({ h, hooks, dialog, options });

const renderContent = (open: boolean): void => {
render(
Expand Down
47 changes: 27 additions & 20 deletions packages/feedback/src/screenshot/components/ScreenshotEditor.tsx
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
import type { FeedbackDialog, FeedbackInternalOptions } from '@sentry/types';
/* eslint-disable max-lines */
import type { FeedbackInternalOptions, FeedbackModalIntegration } from '@sentry/types';
import type { ComponentType, VNode, h as hType } from 'preact';
// biome-ignore lint: needed for preact
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, WINDOW } from '../../constants';
import { createScreenshotInputStyles } from './ScreenshotInput.css';
import { useTakeScreenshot } from './useTakeScreenshot';
import { useTakeScreenshotFactory } from './useTakeScreenshot';

const CROP_BUTTON_SIZE = 30;
const CROP_BUTTON_BORDER = 3;
Expand All@@ -15,8 +13,9 @@ const DPI = WINDOW.devicePixelRatio;

interface FactoryParams {
h: typeof hType;
hooks: typeof Hooks;
imageBuffer: HTMLCanvasElement;
dialog: FeedbackDialog;
dialog: ReturnType<FeedbackModalIntegration['createDialog']>;
options: FeedbackInternalOptions;
}

Expand DownExpand Up@@ -62,17 +61,25 @@ const getContainedSize = (img: HTMLCanvasElement): Box => {
return { startX: x, startY: y, endX: width + x, endY: height + y };
};

export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }: FactoryParams): ComponentType<Props> {
export function ScreenshotEditorFactory({
h, // eslint-disable-line @typescript-eslint/no-unused-vars
hooks,
imageBuffer,
dialog,
options,
}: FactoryParams): ComponentType<Props> {
const useTakeScreenshot = useTakeScreenshotFactory({ hooks });

return function ScreenshotEditor({ onError }: Props): VNode {
const styles = useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);
const styles = hooks.useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);

const canvasContainerRef = useRef<HTMLDivElement>(null);
const cropContainerRef = useRef<HTMLDivElement>(null);
const croppingRef = useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = useState(false);
const canvasContainerRef = hooks.useRef<HTMLDivElement>(null);
const cropContainerRef = hooks.useRef<HTMLDivElement>(null);
const croppingRef = hooks.useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = hooks.useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = hooks.useState(false);

useEffect(() => {
hooks.useEffect(() => {
WINDOW.addEventListener('resize', resizeCropper, false);
}, []);

Expand All@@ -99,7 +106,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
setCroppingRect({ startX: 0, startY: 0, endX: imageDimensions.width, endY: imageDimensions.height });
}

useEffect(() => {
hooks.useEffect(() => {
const cropper = croppingRef.current;
if (!cropper) {
return;
Expand DownExpand Up@@ -141,7 +148,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
DOCUMENT.addEventListener('mousemove', handleMouseMove);
}

const makeHandleMouseMove = useCallback((corner: string) => {
const makeHandleMouseMove = hooks.useCallback((corner: string) => {
return function (e: MouseEvent) {
if (!croppingRef.current) {
return;
Expand DownExpand Up@@ -218,10 +225,10 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
}

useTakeScreenshot({
onBeforeScreenshot: useCallback(() => {
onBeforeScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'none';
}, []),
onScreenshot: useCallback(
onScreenshot: hooks.useCallback(
(imageSource: HTMLVideoElement) => {
const context = imageBuffer.getContext('2d');
if (!context) {
Expand All@@ -235,13 +242,13 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
},
[imageBuffer],
),
onAfterScreenshot: useCallback(() => {
onAfterScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'block';
const container = canvasContainerRef.current;
container && container.appendChild(imageBuffer);
resizeCropper();
}, []),
onError: useCallback(error => {
onError: hooks.useCallback(error => {
(dialog.el as HTMLElement).style.display = 'block';
onError(error);
}, []),
Expand Down
74 changes: 40 additions & 34 deletions packages/feedback/src/screenshot/components/useTakeScreenshot.tsx
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,51 @@
// biome-ignore lint/nursery/noUnusedImports: reason
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useEffect } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, NAVIGATOR, WINDOW } from '../../constants';

interface FactoryParams {
hooks: typeof Hooks;
}

interface Props {
onBeforeScreenshot: () => void;
onScreenshot: (imageSource: HTMLVideoElement) => void;
onAfterScreenshot: () => void;
onError: (error: Error) => void;
}

export const useTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props): void => {
useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});
type UseTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) => void;

const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};
export function useTakeScreenshotFactory({ hooks }: FactoryParams): UseTakeScreenshot {
return function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) {
hooks.useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});

takeScreenshot().catch(onError);
}, []);
};
const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};

takeScreenshot().catch(onError);
}, []);
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions docs/migration/feedback.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,15 +14,15 @@ Below you can find a list of relevant feedback changes and issues that have been
We have streamlined the interface for interacting with the Feedback widget. Below is a list of public functions that
existed in 7.x and a description of how they have changed in v8.

| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<FeedbackDialog>` so you can control showing and hiding of the feedback form directly. |
| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<ReturnType<FeedbackModalIntegration['createDialog']>>` so you can control showing and hiding of the feedback form directly. |

### API Examples

Expand Down
15 changes: 10 additions & 5 deletions packages/feedback/src/core/integration.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import { getClient } from '@sentry/core';
import type {
FeedbackDialog,
FeedbackInternalOptions,
FeedbackModalIntegration,
FeedbackScreenshotIntegration,
Expand DownExpand Up@@ -56,7 +55,9 @@ export const buildFeedbackIntegration = ({
}: BuilderOptions): IntegrationFn<
Integration & {
attachTo(el: Element | string, optionOverrides?: OverrideFeedbackConfiguration): Unsubscribe;
createForm(optionOverrides?: OverrideFeedbackConfiguration): Promise<FeedbackDialog>;
createForm(
optionOverrides?: OverrideFeedbackConfiguration,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>>;
createWidget(optionOverrides?: OverrideFeedbackConfiguration): ActorComponent;
remove(): void;
}
Expand DownExpand Up@@ -179,7 +180,9 @@ export const buildFeedbackIntegration = ({
return integration as I;
};

const _loadAndRenderDialog = async (options: FeedbackInternalOptions): Promise<FeedbackDialog> => {
const _loadAndRenderDialog = async (
options: FeedbackInternalOptions,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> => {
const screenshotRequired = options.enableScreenshot && isScreenshotSupported();
const [modalIntegration, screenshotIntegration] = await Promise.all([
_findIntegration<FeedbackModalIntegration>('FeedbackModal', getModalIntegration, 'feedbackModalIntegration'),
Expand DownExpand Up@@ -223,7 +226,7 @@ export const buildFeedbackIntegration = ({
throw new Error('Unable to attach to target element');
}

let dialog: FeedbackDialog | null = null;
let dialog: ReturnType<FeedbackModalIntegration['createDialog']> | null = null;
const handleClick = async (): Promise<void> => {
if (!dialog) {
dialog = await _loadAndRenderDialog({
Expand DownExpand Up@@ -306,7 +309,9 @@ export const buildFeedbackIntegration = ({
* Creates a new Form which you can
* Accepts partial options to override any options passed to constructor.
*/
async createForm(optionOverrides: OverrideFeedbackConfiguration = {}): Promise<FeedbackDialog> {
async createForm(
optionOverrides: OverrideFeedbackConfiguration = {},
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> {
return _loadAndRenderDialog(mergeOptions(_options, optionOverrides));
},

Expand Down
1 change: 1 addition & 0 deletions packages/feedback/src/modal/components/Dialog.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import type { FeedbackFormData, FeedbackInternalOptions } from '@sentry/types';
import { Fragment, h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import type { VNode } from 'preact';
import { useCallback, useMemo, useState } from 'preact/hooks';

import { SUCCESS_MESSAGE_TIMEOUT } from '../../constants';
import { DialogHeader } from './DialogHeader';
import type { Props as HeaderProps } from './DialogHeader';
Expand Down
16 changes: 5 additions & 11 deletions packages/feedback/src/modal/integration.tsx
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
import { getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';
import type {
CreateDialogProps,
FeedbackDialog,
FeedbackFormData,
FeedbackModalIntegration,
IntegrationFn,
User,
} from '@sentry/types';
import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/types';
import { h, render } from 'preact';
import * as hooks from 'preact/hooks';
import { DOCUMENT } from '../constants';
import { Dialog } from './components/Dialog';
import { createDialogStyles } from './components/Dialog.css';
Expand All@@ -30,7 +24,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
name: 'FeedbackModal',
// eslint-disable-next-line @typescript-eslint/no-empty-function
setupOnce() {},
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }: CreateDialogProps) => {
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }) => {
const shadowRoot = shadow as unknown as ShadowRoot;
const userKey = options.useSentryUser;
const user = getUser();
Expand All@@ -39,7 +33,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
const style = createDialogStyles();

let originalOverflow = '';
const dialog: FeedbackDialog = {
const dialog: ReturnType<FeedbackModalIntegration['createDialog']> = {
get el() {
return el;
},
Expand All@@ -66,7 +60,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
},
};

const screenshotInput = screenshotIntegration && screenshotIntegration.createInput(h, dialog, options);
const screenshotInput = screenshotIntegration && screenshotIntegration.createInput({ h, hooks, dialog, options });

const renderContent = (open: boolean): void => {
render(
Expand Down
47 changes: 27 additions & 20 deletions packages/feedback/src/screenshot/components/ScreenshotEditor.tsx
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
import type { FeedbackDialog, FeedbackInternalOptions } from '@sentry/types';
/* eslint-disable max-lines */
import type { FeedbackInternalOptions, FeedbackModalIntegration } from '@sentry/types';
import type { ComponentType, VNode, h as hType } from 'preact';
// biome-ignore lint: needed for preact
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, WINDOW } from '../../constants';
import { createScreenshotInputStyles } from './ScreenshotInput.css';
import { useTakeScreenshot } from './useTakeScreenshot';
import { useTakeScreenshotFactory } from './useTakeScreenshot';

const CROP_BUTTON_SIZE = 30;
const CROP_BUTTON_BORDER = 3;
Expand All@@ -15,8 +13,9 @@ const DPI = WINDOW.devicePixelRatio;

interface FactoryParams {
h: typeof hType;
hooks: typeof Hooks;
imageBuffer: HTMLCanvasElement;
dialog: FeedbackDialog;
dialog: ReturnType<FeedbackModalIntegration['createDialog']>;
options: FeedbackInternalOptions;
}

Expand DownExpand Up@@ -62,17 +61,25 @@ const getContainedSize = (img: HTMLCanvasElement): Box => {
return { startX: x, startY: y, endX: width + x, endY: height + y };
};

export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }: FactoryParams): ComponentType<Props> {
export function ScreenshotEditorFactory({
h, // eslint-disable-line @typescript-eslint/no-unused-vars
hooks,
imageBuffer,
dialog,
options,
}: FactoryParams): ComponentType<Props> {
const useTakeScreenshot = useTakeScreenshotFactory({ hooks });

return function ScreenshotEditor({ onError }: Props): VNode {
const styles = useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);
const styles = hooks.useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);

const canvasContainerRef = useRef<HTMLDivElement>(null);
const cropContainerRef = useRef<HTMLDivElement>(null);
const croppingRef = useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = useState(false);
const canvasContainerRef = hooks.useRef<HTMLDivElement>(null);
const cropContainerRef = hooks.useRef<HTMLDivElement>(null);
const croppingRef = hooks.useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = hooks.useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = hooks.useState(false);

useEffect(() => {
hooks.useEffect(() => {
WINDOW.addEventListener('resize', resizeCropper, false);
}, []);

Expand All@@ -99,7 +106,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
setCroppingRect({ startX: 0, startY: 0, endX: imageDimensions.width, endY: imageDimensions.height });
}

useEffect(() => {
hooks.useEffect(() => {
const cropper = croppingRef.current;
if (!cropper) {
return;
Expand DownExpand Up@@ -141,7 +148,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
DOCUMENT.addEventListener('mousemove', handleMouseMove);
}

const makeHandleMouseMove = useCallback((corner: string) => {
const makeHandleMouseMove = hooks.useCallback((corner: string) => {
return function (e: MouseEvent) {
if (!croppingRef.current) {
return;
Expand DownExpand Up@@ -218,10 +225,10 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
}

useTakeScreenshot({
onBeforeScreenshot: useCallback(() => {
onBeforeScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'none';
}, []),
onScreenshot: useCallback(
onScreenshot: hooks.useCallback(
(imageSource: HTMLVideoElement) => {
const context = imageBuffer.getContext('2d');
if (!context) {
Expand All@@ -235,13 +242,13 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
},
[imageBuffer],
),
onAfterScreenshot: useCallback(() => {
onAfterScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'block';
const container = canvasContainerRef.current;
container && container.appendChild(imageBuffer);
resizeCropper();
}, []),
onError: useCallback(error => {
onError: hooks.useCallback(error => {
(dialog.el as HTMLElement).style.display = 'block';
onError(error);
}, []),
Expand Down
74 changes: 40 additions & 34 deletions packages/feedback/src/screenshot/components/useTakeScreenshot.tsx
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,51 @@
// biome-ignore lint/nursery/noUnusedImports: reason
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useEffect } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, NAVIGATOR, WINDOW } from '../../constants';

interface FactoryParams {
hooks: typeof Hooks;
}

interface Props {
onBeforeScreenshot: () => void;
onScreenshot: (imageSource: HTMLVideoElement) => void;
onAfterScreenshot: () => void;
onError: (error: Error) => void;
}

export const useTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props): void => {
useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});
type UseTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) => void;

const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};
export function useTakeScreenshotFactory({ hooks }: FactoryParams): UseTakeScreenshot {
return function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) {
hooks.useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});

takeScreenshot().catch(onError);
}, []);
};
const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};

takeScreenshot().catch(onError);
}, []);
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions docs/migration/feedback.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,15 +14,15 @@ Below you can find a list of relevant feedback changes and issues that have been
We have streamlined the interface for interacting with the Feedback widget. Below is a list of public functions that
existed in 7.x and a description of how they have changed in v8.

| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<FeedbackDialog>` so you can control showing and hiding of the feedback form directly. |
| Method Name | Replacement | Notes |
| ------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Sentry.getClient<BrowserClient>()?.getIntegration(Feedback)` | `const feedback = Sentry.getFeedback()` | Get a type-safe reference to the configured feedbackIntegration instance. |
| `feedback.getWidget()` | `const widget = feedback.createWidget(); widget.appendToDom()` | The SDK no longer maintains a stack of form instances. If you call `createWidget()` a new widget will be inserted into the DOM and an `ActorComponent` returned allows you control over the lifecycle of the widget. |
| `feedback.openDialog()` | `widget.open()` | Make the form inside the widget visible. |
| `feedback.closeDialog()` | `widget.close()` | Make the form inside the widget hidden in the page. Success/Error messages will still be rendered and will hide themselves if the form was recently submitted. |
| `feedback.removeWidget()` | `widget.removeFromDom()` | Remove the form and widget instance from the page. After calling this `widget.el.parentNode` will be set to null. |
| `feedback.attachTo()` | `const unsubscribe = feedback.attachTo(myButtonElem)` | The `attachTo()` method will create an onClick event listener to your html element that calls `appendToDom()` and `open()`. It returns a callback to remove the event listener. |
| - | `const form = await feedback.createForm()` | A new method `createForm()`, used internally by `createWidget()` and `attachTo()`, returns a `Promise<ReturnType<FeedbackModalIntegration['createDialog']>>` so you can control showing and hiding of the feedback form directly. |

### API Examples

Expand Down
15 changes: 10 additions & 5 deletions packages/feedback/src/core/integration.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import { getClient } from '@sentry/core';
import type {
FeedbackDialog,
FeedbackInternalOptions,
FeedbackModalIntegration,
FeedbackScreenshotIntegration,
Expand DownExpand Up@@ -56,7 +55,9 @@ export const buildFeedbackIntegration = ({
}: BuilderOptions): IntegrationFn<
Integration & {
attachTo(el: Element | string, optionOverrides?: OverrideFeedbackConfiguration): Unsubscribe;
createForm(optionOverrides?: OverrideFeedbackConfiguration): Promise<FeedbackDialog>;
createForm(
optionOverrides?: OverrideFeedbackConfiguration,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>>;
createWidget(optionOverrides?: OverrideFeedbackConfiguration): ActorComponent;
remove(): void;
}
Expand DownExpand Up@@ -179,7 +180,9 @@ export const buildFeedbackIntegration = ({
return integration as I;
};

const _loadAndRenderDialog = async (options: FeedbackInternalOptions): Promise<FeedbackDialog> => {
const _loadAndRenderDialog = async (
options: FeedbackInternalOptions,
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> => {
const screenshotRequired = options.enableScreenshot && isScreenshotSupported();
const [modalIntegration, screenshotIntegration] = await Promise.all([
_findIntegration<FeedbackModalIntegration>('FeedbackModal', getModalIntegration, 'feedbackModalIntegration'),
Expand DownExpand Up@@ -223,7 +226,7 @@ export const buildFeedbackIntegration = ({
throw new Error('Unable to attach to target element');
}

let dialog: FeedbackDialog | null = null;
let dialog: ReturnType<FeedbackModalIntegration['createDialog']> | null = null;
const handleClick = async (): Promise<void> => {
if (!dialog) {
dialog = await _loadAndRenderDialog({
Expand DownExpand Up@@ -306,7 +309,9 @@ export const buildFeedbackIntegration = ({
* Creates a new Form which you can
* Accepts partial options to override any options passed to constructor.
*/
async createForm(optionOverrides: OverrideFeedbackConfiguration = {}): Promise<FeedbackDialog> {
async createForm(
optionOverrides: OverrideFeedbackConfiguration = {},
): Promise<ReturnType<FeedbackModalIntegration['createDialog']>> {
return _loadAndRenderDialog(mergeOptions(_options, optionOverrides));
},

Expand Down
1 change: 1 addition & 0 deletions packages/feedback/src/modal/components/Dialog.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ import type { FeedbackFormData, FeedbackInternalOptions } from '@sentry/types';
import { Fragment, h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import type { VNode } from 'preact';
import { useCallback, useMemo, useState } from 'preact/hooks';

import { SUCCESS_MESSAGE_TIMEOUT } from '../../constants';
import { DialogHeader } from './DialogHeader';
import type { Props as HeaderProps } from './DialogHeader';
Expand Down
16 changes: 5 additions & 11 deletions packages/feedback/src/modal/integration.tsx
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
import { getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';
import type {
CreateDialogProps,
FeedbackDialog,
FeedbackFormData,
FeedbackModalIntegration,
IntegrationFn,
User,
} from '@sentry/types';
import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/types';
import { h, render } from 'preact';
import * as hooks from 'preact/hooks';
import { DOCUMENT } from '../constants';
import { Dialog } from './components/Dialog';
import { createDialogStyles } from './components/Dialog.css';
Expand All@@ -30,7 +24,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
name: 'FeedbackModal',
// eslint-disable-next-line @typescript-eslint/no-empty-function
setupOnce() {},
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }: CreateDialogProps) => {
createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }) => {
const shadowRoot = shadow as unknown as ShadowRoot;
const userKey = options.useSentryUser;
const user = getUser();
Expand All@@ -39,7 +33,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
const style = createDialogStyles();

let originalOverflow = '';
const dialog: FeedbackDialog = {
const dialog: ReturnType<FeedbackModalIntegration['createDialog']> = {
get el() {
return el;
},
Expand All@@ -66,7 +60,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
},
};

const screenshotInput = screenshotIntegration && screenshotIntegration.createInput(h, dialog, options);
const screenshotInput = screenshotIntegration && screenshotIntegration.createInput({ h, hooks, dialog, options });

const renderContent = (open: boolean): void => {
render(
Expand Down
47 changes: 27 additions & 20 deletions packages/feedback/src/screenshot/components/ScreenshotEditor.tsx
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
import type { FeedbackDialog, FeedbackInternalOptions } from '@sentry/types';
/* eslint-disable max-lines */
import type { FeedbackInternalOptions, FeedbackModalIntegration } from '@sentry/types';
import type { ComponentType, VNode, h as hType } from 'preact';
// biome-ignore lint: needed for preact
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, WINDOW } from '../../constants';
import { createScreenshotInputStyles } from './ScreenshotInput.css';
import { useTakeScreenshot } from './useTakeScreenshot';
import { useTakeScreenshotFactory } from './useTakeScreenshot';

const CROP_BUTTON_SIZE = 30;
const CROP_BUTTON_BORDER = 3;
Expand All@@ -15,8 +13,9 @@ const DPI = WINDOW.devicePixelRatio;

interface FactoryParams {
h: typeof hType;
hooks: typeof Hooks;
imageBuffer: HTMLCanvasElement;
dialog: FeedbackDialog;
dialog: ReturnType<FeedbackModalIntegration['createDialog']>;
options: FeedbackInternalOptions;
}

Expand DownExpand Up@@ -62,17 +61,25 @@ const getContainedSize = (img: HTMLCanvasElement): Box => {
return { startX: x, startY: y, endX: width + x, endY: height + y };
};

export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }: FactoryParams): ComponentType<Props> {
export function ScreenshotEditorFactory({
h, // eslint-disable-line @typescript-eslint/no-unused-vars
hooks,
imageBuffer,
dialog,
options,
}: FactoryParams): ComponentType<Props> {
const useTakeScreenshot = useTakeScreenshotFactory({ hooks });

return function ScreenshotEditor({ onError }: Props): VNode {
const styles = useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);
const styles = hooks.useMemo(() => ({ __html: createScreenshotInputStyles().innerText }), []);

const canvasContainerRef = useRef<HTMLDivElement>(null);
const cropContainerRef = useRef<HTMLDivElement>(null);
const croppingRef = useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = useState(false);
const canvasContainerRef = hooks.useRef<HTMLDivElement>(null);
const cropContainerRef = hooks.useRef<HTMLDivElement>(null);
const croppingRef = hooks.useRef<HTMLCanvasElement>(null);
const [croppingRect, setCroppingRect] = hooks.useState<Box>({ startX: 0, startY: 0, endX: 0, endY: 0 });
const [confirmCrop, setConfirmCrop] = hooks.useState(false);

useEffect(() => {
hooks.useEffect(() => {
WINDOW.addEventListener('resize', resizeCropper, false);
}, []);

Expand All@@ -99,7 +106,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
setCroppingRect({ startX: 0, startY: 0, endX: imageDimensions.width, endY: imageDimensions.height });
}

useEffect(() => {
hooks.useEffect(() => {
const cropper = croppingRef.current;
if (!cropper) {
return;
Expand DownExpand Up@@ -141,7 +148,7 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
DOCUMENT.addEventListener('mousemove', handleMouseMove);
}

const makeHandleMouseMove = useCallback((corner: string) => {
const makeHandleMouseMove = hooks.useCallback((corner: string) => {
return function (e: MouseEvent) {
if (!croppingRef.current) {
return;
Expand DownExpand Up@@ -218,10 +225,10 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
}

useTakeScreenshot({
onBeforeScreenshot: useCallback(() => {
onBeforeScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'none';
}, []),
onScreenshot: useCallback(
onScreenshot: hooks.useCallback(
(imageSource: HTMLVideoElement) => {
const context = imageBuffer.getContext('2d');
if (!context) {
Expand All@@ -235,13 +242,13 @@ export function makeScreenshotEditorComponent({ imageBuffer, dialog, options }:
},
[imageBuffer],
),
onAfterScreenshot: useCallback(() => {
onAfterScreenshot: hooks.useCallback(() => {
(dialog.el as HTMLElement).style.display = 'block';
const container = canvasContainerRef.current;
container && container.appendChild(imageBuffer);
resizeCropper();
}, []),
onError: useCallback(error => {
onError: hooks.useCallback(error => {
(dialog.el as HTMLElement).style.display = 'block';
onError(error);
}, []),
Expand Down
74 changes: 40 additions & 34 deletions packages/feedback/src/screenshot/components/useTakeScreenshot.tsx
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,51 @@
// biome-ignore lint/nursery/noUnusedImports: reason
import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars
import { useEffect } from 'preact/hooks';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT, NAVIGATOR, WINDOW } from '../../constants';

interface FactoryParams {
hooks: typeof Hooks;
}

interface Props {
onBeforeScreenshot: () => void;
onScreenshot: (imageSource: HTMLVideoElement) => void;
onAfterScreenshot: () => void;
onError: (error: Error) => void;
}

export const useTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props): void => {
useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});
type UseTakeScreenshot = ({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) => void;

const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};
export function useTakeScreenshotFactory({ hooks }: FactoryParams): UseTakeScreenshot {
return function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }: Props) {
hooks.useEffect(() => {
const takeScreenshot = async (): Promise<void> => {
onBeforeScreenshot();
const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({
video: {
width: WINDOW.innerWidth * WINDOW.devicePixelRatio,
height: WINDOW.innerHeight * WINDOW.devicePixelRatio,
},
audio: false,
// @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab
monitorTypeSurfaces: 'exclude',
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
});

takeScreenshot().catch(onError);
}, []);
};
const video = DOCUMENT.createElement('video');
await new Promise<void>((resolve, reject) => {
video.srcObject = stream;
video.onloadedmetadata = () => {
onScreenshot(video);
stream.getTracks().forEach(track => track.stop());
resolve();
};
video.play().catch(reject);
});
onAfterScreenshot();
};

takeScreenshot().catch(onError);
}, []);
};
}
Loading