I want to get the width of the content, do some calculations on it, and present a badge.
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const tabWidth = tab.width;
But if I have devtools open anchored to the right, I get that as part of the width. How can I get the non-devtools size - the real size of the window.
chrome.action.onClicked.addListener(async () => {
function getWidth() {
var msg = {
a: document.body.clientWidth,
b: document.body.scrollWidth,
c: window.innerWidth,
d: window.pageXOffset,
e: document.body.getBoundingClientRect().width,
f: document.body.offsetWidth
};
chrome.runtime.sendMessage(msg);
}
var tab = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: {tabId: tab[0].id},
function: getWidth
}, () => {
console.log('script injected')
})
});
chrome.runtime.onMessage.addListener(msg => {
console.table(msg)
})
Related
I am using web viewer and want to rotate individual pages and update them in the database.
Right now I am able to rotate the whole pdf only.
I am following this doc https://www.pdftron.com/documentation/web/guides/manipulation/rotate/
but not able to understand much
export default function PdfTron(props: any): ReactElement {
const viewer = useRef<HTMLDivElement>(null);
const {DrawingLibDetailsState, DrawingLibDetailsDispatch}: any = useContext(DrawingLibDetailsContext);
const [newInstance, setNewInstance] = useState<any>(null);
const [currentPage, setCurrentPage] = useState<any>(null);
const {dispatch, state }:any = useContext(stateContext);
//console.log("currentPage in state",currentPage)
useEffect(() => {
WebViewer(
{
path: '/webviewer/lib',
licenseKey: process.env["REACT_APP_PDFTRON_LICENSE_KEY"],
initialDoc: '',
filename: 'drawings',
extension: "pdf",
isReadOnly: true,
fullAPI: true,
disabledElements: [
// 'leftPanelButton',
// // 'selectToolButton',
// 'stickyToolButton',
// 'toggleNotesButton',
]
},
viewer.current as HTMLDivElement,
).then((instance: any) => {
setNewInstance(instance)
// you can now call WebViewer APIs here...
});
}, []);
useEffect(() => {
if(DrawingLibDetailsState?.parsedFileUrl?.url && newInstance ){
const s3Key = DrawingLibDetailsState?.parsedFileUrl?.s3Key;
const pageNum = s3Key.split('/')[s3Key.split('/').length-1].split('.')[0];
const fileName = DrawingLibDetailsState?.drawingLibDetails[0]?.fileName?.replace(".pdf", "");
const downloadingFileName = `page${pageNum}_${fileName}`;
newInstance.loadDocument(DrawingLibDetailsState?.parsedFileUrl?.url, {extension: "pdf",
filename: downloadingFileName ? downloadingFileName : 'drawing',})
const { documentViewer } = newInstance.Core;
const pageRotation = newInstance.Core.PageRotation;
const clickDocument =newInstance.Core.DocumentViewer.Click;
const pageNumber = newInstance.Core.pageNum;
//get page rotation from the PDF
documentViewer.addEventListener('rotationUpdated', (rotation: number) => {
updateRotation(rotation)
})
// trigger an event after the document loaded
documentViewer.addEventListener('documentLoaded', async() => {
const doc = documentViewer.getDocument();
const rotation = DrawingLibDetailsState?.drawingLibDetails[0]?.sheetsReviewed?.pdfRotation ?
DrawingLibDetailsState?.drawingLibDetails[0]?.sheetsReviewed?.pdfRotation : 0
documentViewer.setRotation(rotation)
})
documentViewer.on('pageNumberUpdated', () => {
DrawingLibDetailsDispatch(setDrawingPageNumber(0));
})
}
}, [DrawingLibDetailsState?.parsedFileUrl?.url, newInstance]);
useEffect(() => {
if(DrawingLibDetailsState?.drawingPageNum && newInstance ){
const { documentViewer, PDFNet } = newInstance.Core;
PDFNet.initialize()
documentViewer.addEventListener('documentLoaded',async () => {
await PDFNet.initialize()
const pdfDoc = documentViewer.getDocument();
const doc = await pdfDoc.getPDFDoc();
newInstance.UI.pageManipulationOverlay.add([
{
type: 'customPageOperation',
header: 'Custom options',
dataElement: 'customPageOperations',
operations: [
{
title: 'Alert me',
img: '/path-to-image',
onClick: (selectedPageNumbers:any) => {
alert(`Selected thumbnail pages: ${selectedPageNumbers}`);
},
dataElement: 'customPageOperationButton',
},
],
},
{ type: 'divider' },
]);
documentViewer.setCurrentPage(DrawingLibDetailsState?.drawingPageNum, true);
});
documentViewer.setCurrentPage(DrawingLibDetailsState?.drawingPageNum, true);
}
}, [DrawingLibDetailsState?.drawingPageNum]);
useEffect(() => {
if(props?.drawingSheetsDetails?.fileSize){
fetchSheetUrl(props?.drawingSheetsDetails)
}
}, [props?.drawingSheetsDetails]);
const fetchSheetUrl = (file: any) => {
const payload = [{
fileName: file.fileName,
key: file.sourceKey,
expiresIn: 100000000,
// processed: true
}];
getSheetUrl(payload);
}
const getSheetUrl = async (payload: any) => {
try {
dispatch(setIsLoading(true));
const fileUploadResponse = await postApi('V1/S3/downloadLink', payload);
if(fileUploadResponse.success){
const fileData = {
s3Key: payload[0].key,
url: fileUploadResponse.success[0].url
}
DrawingLibDetailsDispatch(setParsedFileUrl(fileData));
}
dispatch(setIsLoading(false));
} catch (error) {
Notification.sendNotification(error, AlertTypes.warn);
dispatch(setIsLoading(false));
}
}
const updateRotation = (rotation: number) => {
props.updateRotation(rotation)
}
return (
<>
<div className="webviewer" ref={viewer}></div>
</>
)
}
In WebViewer 8.0 you would need to enable the left panel by default when the document is loaded, and then use event delegation on left panel to watch for button clicks on the single page rotation buttons.
const { documentViewer } = instance.Core
documentViewer.addEventListener('documentLoaded',()=>{
let panelElement = instance.docViewer.getScrollViewElement().closest('#app').querySelector('[data-element="thumbnailsPanel"]');
if (!parentElement) {
instance.UI.toggleElementVisibility('leftPanel');
panelElement = instance.docViewer.getScrollViewElement().closest('#app').querySelector('[data-element="thumbnailsPanel"]');
}
panelElement.addEventListener('click', (e) => {
if (e.target.dataset?.element === 'thumbRotateClockwise' || e.target.dataset?.element === 'thumbRotateCounterClockwise') {
// The single page rotations are performed asychronously and there are no events firings in 8.0, so we have to manually add a delay before the page finishes rotating itself.
setTimeout(() => {
const pageNumber = parseInt(e.target.parentElement.previousSibling.textContent);
const rotation = instance.docViewer.getDocument().getPageRotation(pageNumber);
console.log('page ', pageNumber, ' self rotation is ', rotation);
}, 500);
}
});
})
If you have the option to upgrade to the latest WebViewer, you can listen to the ‘pagesUpdated’ event on documentViewer and the code becomes shorter & cleaner:
const { documentViewer } = instance.Core
documentViewer.addEventListener('pagesUpdated',(changes)=>{
changes.contentChanged.forEach(pageNumber=>{
const rotation = documentViewer.getDocument().getPageRotation(pageNumber)
console.log('page ', pageNumber, ' self rotation is ', rotation);
})
})
For both situations, when you load the document back, you can use documentViewer.getDocument().rotatePages to rotate to your saved rotations.
assuming we have the saved page rotations data structured like this
const rotationData = [
{pageNumber: 1, rotation: 180},
{pageNumber: 3, rotation: 90},
{pageNumber: 4, rotation: 270},
]
We can use the following code to rotate our individual pages back:
const { documentViewer } = instance.Core
documentViewer.addEventListener('documentLoaded',()=>{
rotationData.forEach(page=>{
const originalRotation = documentViewer.getDocument().getPageRotation(page.pageNumber)
if (originalRotation !== page.rotation) {
documentViewer.getDocument().rotatePages([page.pageNumber], (page.rotation-originalRotation)/90);
}
})
})
I have tried many things including adding the headers to the request. Still does not work. I have looked everywhere and came here as a last resort.
My main.js (routes)
app.post("/timeclock/punchout", async (req, res) => {
let time = moment().unix();
let employeeid = req.body.empid2;
let date = moment().format();
let comments = req.body.comments;
return res.send({ error: false, message: "complete punch" });
});
my liquid file using jQuery and axios
<script>
toast = siiimpleToast.setOptions({
container: 'body',
class: 'siiimpleToast',
position: 'top|right',
margin: 15,
delay: 2,
duration: 3000,
style: {},
})
$("#form").submit(function(event) {
event.preventDefault()
let empid1 = $("#empid").val()
let comments1 = $("#comments").val()
axios.post('/timeclock/punchin', {comments: comments1, empid: empid1}).then(response => {
if(response.data.error == false) {
$("#form").trigger('reset')
toast.success('Punch Successful!')
} else if(response.data.error == true) {
toast.alert(response.data.message)
$("#form").trigger('reset')
}
}, (error) => {
console.log(error)
})
})
$("#form").submit(function(event) {
event.preventDefault()
let empid1 = $("#empid").val()
let commentsout1 = $("#commentsout").val()
axios.post('/timeclock/punchout', {commentsout: commentsout1, empid: empid1}).then(response => {
if(response.data.error == false) {
$("#form").trigger('reset')
toast.success('Punch Successful!')
} else if(response.data.error == true) {
toast.alert(response.data.message)
$("#form").trigger('reset')
}
}, (error) => {
console.log(error)
})
})
any ideas? I read that it automatically detects the content type. But I cant seem to override it.
in order to cover all statements/branch/lines, I need to write two or more fn.spec.ts to test fn.ts, how can I merge fn.spec.ts and fn2.spec.ts to be one file ?
// fn.ts
export const getEnv = () => {
if (location.href.indexOf('localhost') !== -1 || /\d+\.\d+\.\d+\.\d+/.test(location.href)) {
return 'Test'
}
return 'Product'
}
// fn.spec.ts
describe('fn getEnv',()=>{
Object.defineProperty(window, 'location', {
value: {
href: 'http://192.168.2.3:9001'
},
})
const { getEnv } = require('./fn')
test('getEnv',()=>{
expect(getEnv()).toBe('Test')
})
})
// fn2.spec.ts
describe('fn getEnv',()=>{
Object.defineProperty(window, 'location', {
value: {
href: 'https://xx.com'
},
})
const { getEnv } = require('./fn')
test('getEnv',()=>{
expect(getEnv()).toBe('Product')
})
})
// jest.config.js
module.exports = {
testEnvironment: 'jest-environment-jsdom', // browser environment
}
Just merge it into one file with a clear expectation message.
import { getEnv } from './fn';
describe('fn', () => {
describe('getEnv', () => {
test('should return "Test" when window location is an IP address', () => {
Object.defineProperty(window, 'location', {
value: {
href: 'http://192.168.2.3:9001'
},
});
const actual = getEnv();
expect(actual).toBe('Test');
});
test('should return "Product" when window location is a domain', () => {
Object.defineProperty(window, 'location', {
value: {
href: 'https://xx.com'
},
});
const actual = getEnv();
expect(actual).toBe('Product');
})
});
});
I want to maky my presence show the numbers of orders from a json file into the bot's presence but it doesn't show anything and doesn't tell any errors in the console
const fsn = require("fs-nextra");
module.exports = {
name: 'ready',
once: true,
execute(client) {
fsn.readJSON("./orders.json").then((orderDB) => {
let amount = 0;
for (let x in orderDB) {
amount++;
client.user.setPresence({
status: 'online',
activity: {
name: `${amount} orders | .help`,
type: "WATCHING"
}
})
}
});
console.log(`Ready! Logged in as ${client.user.tag}`);
},
};
You forgot to set a "}" after the loop. I changed you the mistake in the following code:
const fsn = require("fs-nextra");
module.exports = {
name: 'ready',
once: true,
execute(client) {
fsn.readJSON("./orders.json").then((orderDB) => {
let amount = 0;
for (let x in orderDB) {
amount++;
}
client.user.setPresence({
status: 'online',
activity: {
name: `${amount} orders | .help`,
type: "WATCHING"
}
})
});
console.log(`Ready! Logged in as ${client.user.tag}`);
},
};
I am currently trying to do a test on media queries but I can't figure out. How possibly I can change width of the window so it reflects to media query.
I have tried all commented code to mock the width but no use. I know it has something to do with jsdom but cant figure out.
it('when image is WIDE and media match with medium', () => {
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 900})
// window.resizeBy = jest.fn();
// window.resizeBy(900,300);
//const mediaQuery = '(min-width: 790px)';
// Object.defineProperty(window, "matchMedia", {
// value: jest.fn(() => { return { matches: true,media: mediaQuery } })
// });
// Object.defineProperty(window,'innerWidth', {
// configurable: true,
// writable: true,
// value: 790
// });
// Object.defineProperty(window,'innerHeight', {
// configurable: true,
// writable: true,
// value: 900
// });
window.matchMedia = jest.fn().mockImplementation(query => {
//query always display (min-width: 240px) and (max-width: 767px)
return {
matches: true,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn(),
};
});
const result = imageStretcher(aWideImage);
expect(result).toEqual({ imgWidth: '90%', imgHeight: '40%' });
});
This is the code I want to test.
const screenResolution = {
smallSize: '(min-width: 240px) and (max-width: 767px)',
mediumSize: '(min-width: 768px) and (max-width: 1200px)',
};
const sizeTypes = {
smallSize: 'smallSize',
mediumSize: 'mediumSize',
normalSize: 'normalSize',
};
const sizeSettings = {
[PORTRAIT]: {
smallSize: { imgWidth: '62%', imgHeight: '50%' },
mediumSize: { imgWidth: '95%', imgHeight: '75%' },
normalSize: { imgWidth: '70%', imgHeight: '90%' },
},
[WIDE]: {
smallSize: { imgWidth: '90%', imgHeight: '30%' },
mediumSize: { imgWidth: '90%', imgHeight: '40%' },
normalSize: { imgWidth: '65%', imgHeight: '80%' },
},
};
const screenResolutionMatcher = (imageType: number) => {
if (window.matchMedia(screenResolution.smallSize).matches) {
return setNewImageSize(imageType, sizeTypes.smallSize);
} else if (window.matchMedia(screenResolution.mediumSize).matches) {
return setNewImageSize(imageType, sizeTypes.mediumSize);
} else {
return setNewImageSize(imageType, sizeTypes.normalSize);
}
};
export const imageStretcher = (source: string) => {
//....
return screenResolutionMatcher(imageType);
}
};
OK finally after having crazy rough time with this I have figured it out this way it test medium screen.
it('when image is WIDE and media match with medium', () => {
window.matchMedia = jest.fn().mockImplementation(query => ({
matches: query !== '(min-width: 240px) and (max-width: 767px)',
media: '',
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn()
}));
const result = imageStretcher(aWideImage);
expect(result).toEqual({ imgWidth: '90%', imgHeight: '40%' });
});