initial commit

This commit is contained in:
Chen Asraf
2019-04-10 01:16:36 +03:00
commit 67d2b2f2a0
14 changed files with 4574 additions and 0 deletions

3
.babelrc Normal file
View File

@@ -0,0 +1,3 @@
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

87
.gitignore vendored Normal file
View File

@@ -0,0 +1,87 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
### CUSTOM ###
dist/

13
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,13 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "yarn: start",
"command": "yarn start",
"problemMatcher": []
}
]
}

36
UploadResized.d.ts vendored Normal file
View File

@@ -0,0 +1,36 @@
/** Declaration file generated by dts-gen */
/*~ If this module is a UMD module that exposes a global variable 'myLib' when
*~ loaded outside a module loader environment, declare that global here.
*~ Otherwise, delete this declaration.
*/
export as namespace myLib;
/*~ If this module has methods, declare them as functions like so.
*/
export function myMethod(a: string): string;
export function myOtherMethod(a: number): number;
/*~ You can declare types that are available via importing the module */
export interface someType {
name: string;
length: number;
extras?: string[];
}
/*~ You can declare properties of the module using const, let, or var */
export const myField: number;
/*~ If there are types, properties, or methods inside dotted names
*~ of the module, declare them inside a 'namespace'.
*/
export namespace subProp {
/*~ For example, given this definition, someone could write:
*~ import { subProp } from 'yourModule';
*~ subProp.foo();
*~ or
*~ import * as yourMod from 'yourModule';
*~ yourMod.subProp.foo();
*/
export function foo(): void;
}

30
package.json Normal file
View File

@@ -0,0 +1,30 @@
{
"name": "upload_resized",
"version": "1.0.0",
"main": "index.js",
"repository": "git@github.com:chenasraf/upload_resized.git",
"author": "Chen Asraf <chenasraf@users.noreply.github.com>",
"license": "MIT",
"dependencies": {
"@babel/polyfill": "^7.4.3",
"chrome": "^0.1.0",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"styled-components": "^4.2.0"
},
"devDependencies": {
"@babel/core": "^7.4.3",
"@babel/preset-env": "^7.4.3",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"chrome-url-loader": "^1.1.1",
"copy-webpack-plugin": "^5.0.2",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0"
},
"scripts": {
"start": "webpack --mode development --watch",
"build": "webpack --mode production"
}
}

16
public/manifest.json Normal file
View File

@@ -0,0 +1,16 @@
{
"manifest_version": 2,
"name": "Upload Resizer",
"version": "{{VERSION}}",
"background": {
"persistent": true,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["frontend.js"]
}],
"permissions": [
"contextMenus"
]
}

13
src/background.js Normal file
View File

@@ -0,0 +1,13 @@
import 'chrome'
import '@babel/polyfill'
import { createImageElement, getImageSize } from './lib/resizer'
import { assert, Message } from './lib/utils'
chrome.contextMenus.create({
contexts: ['image'],
title: 'Resize to 50%',
onclick: async (info, tab) => {
assert(info.mediaType === 'image', 'expected image')
chrome.tabs.sendMessage(tab.id, new Message('select_image', { src: info.srcUrl }))
}
})

View File

@@ -0,0 +1,92 @@
import * as React from 'react'
import propTypes from 'prop-types'
import styled from 'styled-components'
import { spacing, MAX_Z_INDEX } from '../lib/cssvars'
import { Size, createImageElement, getImageSize } from '../lib/resizer'
const Overlay = styled.div`
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0 , 0, 0.4);
z-index: ${MAX_Z_INDEX};
&, & * {
box-sizing: border-box;
}
`
const Container = styled.div`
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
`
const boxPadding = spacing * 2;
const boxMargin = spacing * 2;
const Box = styled.div`
min-width: 500px;
max-width: calc(100vw - ${boxMargin * 2}px);
margin: ${boxMargin}px;
background: white;
border-radius: 3px;
padding: ${boxPadding}px;
`
const BoxContent = styled.div`
max-height: calc(100vh - ${boxMargin * 2}px - ${boxPadding * 2}px);
overflow-y: auto;
`
const ImageContainer = styled.div`
max-width: 100%;
overflow: auto;
`
export default class UploadResizer extends React.Component {
constructor(props) {
super(props)
this.state = {
size: new Size(),
}
}
async componentWillMount() {
const img = await createImageElement(this.props.image)
this.setState({ size: getImageSize(img) })
}
render() {
const { size } = this.state
return (
<Overlay>
<Container>
<Box>
<BoxContent>
Image Preview:
<ImageContainer>
<img src={this.props.image} />
</ImageContainer>
<div>
Original Size: {size.width}x{size.height}
</div>
</BoxContent>
</Box>
</Container>
</Overlay>
)
}
}
UploadResizer.propTypes = {
image: propTypes.string.isRequired,
}

30
src/frontend.jsx Normal file
View File

@@ -0,0 +1,30 @@
import '@babel/polyfill'
import 'chrome'
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import UploadResizer from './components/upload_resizer'
const __EL_ID = '__upload_resizer_box'
function bootstrap(imgSrc) {
removeExistingBootstrap()
const el = document.createElement('div')
el.id = __EL_ID
document.body.appendChild(el)
ReactDOM.render(<UploadResizer image={imgSrc} />, el)
}
function removeExistingBootstrap() {
const el = document.querySelector(`#${__EL_ID}`)
if (el) {
el.remove()
}
}
chrome.runtime.onMessage.addListener((message, sender, respond) => {
console.log('got msg', message, sender)
if (message && message.action === 'select_image') {
bootstrap(message.payload.src)
}
return true
})

2
src/lib/cssvars.js Normal file
View File

@@ -0,0 +1,2 @@
export const spacing = 8;
export const MAX_Z_INDEX = 2147483638;

35
src/lib/resizer.js Normal file
View File

@@ -0,0 +1,35 @@
import { assert } from './utils'
export function createImageElement(src) {
assert(src, 'src must not be empty')
const img = new Image()
img.src = src
return new Promise((resolve, reject) => {
img.onload = () => resolve(img)
img.onerror = (e) => reject(e)
})
}
export function
getImageSize(img) {
assert(img instanceof Image, 'expected Image object')
return new Size(img.width, img.height)
}
export class Size {
constructor(width, height) {
assert(
['undefined', 'number'].includes(typeof width) ||
(typeof width === 'object' && typeof height === 'undefined'), 'width must be number or undefined')
assert(['undefined', 'number'].includes(typeof height), 'height must be number or undefined')
if (typeof width === 'object') {
this.width = width.width
this.height = width.height
} else {
this.width = width
this.height = height
}
}
}

13
src/lib/utils.js Normal file
View File

@@ -0,0 +1,13 @@
export function assert(cond, msg) {
if (!Boolean(cond)) {
throw new Error(msg)
}
}
export class Message {
constructor(action, payload) {
assert(typeof action === 'string', 'action must be a string')
this.action = action
this.payload = payload
}
}

55
webpack.config.js Normal file
View File

@@ -0,0 +1,55 @@
const webpack = require('webpack')
const path = require('path')
const CopyPlugin = require('copy-webpack-plugin')
const package = require('./package.json')
const paths = {
nodeModules: path.join(process.cwd(), 'node_modules'),
dist: path.join(process.cwd(), 'dist'),
src: path.join(process.cwd(), 'src'),
public: path.join(process.cwd(), 'public'),
}
module.exports = {
devtool: 'inline-cheap-module-source-map',
entry: {
'background': path.join(paths.src, 'background.js'),
'frontend': path.join(paths.src, 'frontend.jsx'),
},
output: {
path: paths.dist,
filename: '[name].js',
},
module: {
rules: [
{
test: [/\.jsx?/],
exclude: paths.nodeModules,
loader: 'babel-loader',
},
{
test: /\.(png|svg|jpe?g|bmp|gif)/i,
loader: require.resolve('chrome-url-loader'),
options: {
publicDir: path.join(paths.dist, 'images'),
baseDir: paths.public,
}
}
]
},
plugins: [
new CopyPlugin([{
from: paths.public,
to: paths.build,
transform(content, _path) {
return content.toString().replace('{{VERSION}}', package.version)
}
}])
],
externals: {
chrome: 'chrome'
},
resolve: {
extensions: ['.js', '.jsx'],
}
}

4149
yarn.lock Normal file

File diff suppressed because it is too large Load Diff