Skip to content

Commit

Permalink
send file object to state and read bianaries and hashes outside of re…
Browse files Browse the repository at this point in the history
…act #2766
  • Loading branch information
Josh Pollock committed Oct 25, 2018
1 parent fb9ca9c commit 200bfb7
Show file tree
Hide file tree
Showing 13 changed files with 6,984 additions and 72 deletions.
2 changes: 1 addition & 1 deletion clients/blocks/build/index.min.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion clients/privacy/build/index.min.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion clients/pro/build/index.min.js.map

Large diffs are not rendered by default.

6,878 changes: 6,849 additions & 29 deletions clients/render/build/index.min.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion clients/render/build/index.min.js.map

Large diffs are not rendered by default.

24 changes: 4 additions & 20 deletions clients/render/components/Fields/FileInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {CalderaFormsFieldGroup, Fragment} from "../CalderaFormsFieldGroup";
import {CalderaFormsFieldPropType} from "../CalderaFormsFieldRender";
import PropTypes from 'prop-types';
import Dropzone from 'react-dropzone';

const CryptoJS = require("crypto-js");

export const FileInput = (props) => {
const{shouldDisable,accept,field,describedById,onChange,style,className,multiple,multiUploadText,inputProps} = props;
Expand All @@ -21,21 +21,12 @@ export const FileInput = (props) => {

const onDrop = (acceptedFiles, rejectedFiles) => {
acceptedFiles.forEach(file => {
const reader = new FileReader();
reader.onload = () => {
onChange(reader.result);
};
reader.onabort = () => console.log('file reading was aborted');
reader.onerror = () => console.log('file reading has failed');
reader.readAsBinaryString(file);
onChange(file);

});
};

const createImageFromFieldValue = (fieldValue) =>{
const img = new Image();
img.src = fieldValue;
return img;
};


return(
<Dropzone
Expand All @@ -50,13 +41,6 @@ export const FileInput = (props) => {
multiple={multiple}
>
<p>{multiUploadText}</p>
{fieldValue &&
<ul>
<li>
<img src={fieldValue} />
</li>
</ul>
}
</Dropzone>
)
};
Expand Down
93 changes: 75 additions & 18 deletions clients/render/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,14 @@ import {CalderaFormsRender} from "./components/CalderaFormsRender";
import React from 'react';
import ReactDOM from "react-dom";
import domReady from '@wordpress/dom-ready';

Object.defineProperty( global.wp, 'element', {
const CryptoJS = require("crypto-js");
Object.defineProperty(global.wp, 'element', {
get: () => React
} );


});


domReady( function() {
jQuery( document ).on( 'cf.form.init', (e, obj ) => {
domReady(function () {
jQuery(document).on('cf.form.init', (e, obj) => {
const {
state,//CF state instance
formId, //Form's ID
Expand All @@ -22,7 +20,7 @@ domReady( function() {
const fieldsToControl = [];

//Build configurations
document.querySelectorAll('.cf2-field-wrapper' ).forEach(function(fieldElement) {
document.querySelectorAll('.cf2-field-wrapper').forEach(function (fieldElement) {
const fieldIdAttr = fieldElement.getAttribute('data-field-id');

const formConfig = window.cf2[idAttr];
Expand All @@ -31,19 +29,18 @@ domReady( function() {
formConfig.fields[fieldIdAttr]
: null;

if( 'string' === typeof fieldConfig ){
if ('string' === typeof fieldConfig) {
fieldConfig = JSON.parse(fieldConfig);
}
if( fieldConfig ){
if (fieldConfig) {
fieldsToControl.push(fieldConfig);
if(fieldConfig.hasOwnProperty('fieldDefault' ) ){
state.mutateState(fieldIdAttr,fieldConfig.fieldDefault);
if (fieldConfig.hasOwnProperty('fieldDefault')) {
state.mutateState(fieldIdAttr, fieldConfig.fieldDefault);

}
}
});


/**
* Flag to indicate if validation is happening or not
*
Expand All @@ -55,12 +52,69 @@ domReady( function() {
*/
let shouldBeValidating = false;


function createMediaFromFile(file, additionalData) {
// Create upload payload
const data = new window.FormData();
data.append('file', file, file.name || file.type.replace('/', '.'));
data.append('title', file.name ? file.name.replace(/\.[^.]+$/, '') : file.type.replace('/', '.'));
forEach(additionalData, ((value, key) => data.append(key, value)));
/**
return apiFetch( {
path: '/cf-api/v3/file',
body: data,
method: 'POST',
} );
**/
}


//When form submits, push values onto form object before it is serialized
jQuery(document).on( 'cf.form.submit', (event,obj) => {
jQuery(document).on('cf.form.submit', (event, obj) => {
const values = theComponent.getFieldValues();
if( Object.keys(values).length){
if (Object.keys(values).length) {
Object.keys(values).forEach(fieldId => {
obj.$form.data(fieldId, values[fieldId]);
const field = fieldsToControl.find(field => fieldId === field.fieldId);
if (field) {
if ('file' === field.type) {
const verify = jQuery(`#_cf_verify_${field.formId}`).val();
const hashes = [];
const bianaries = [];
const files = [values[fieldId]];

files.forEach(file => {
var readerForHashes = new FileReader();
readerForHashes.addEventListener(
'load',
function () {
hashes.push(CryptoJS.MD5(CryptoJS.lib.WordArray.create(this.result)).toString());
}
);
readerForHashes.readAsArrayBuffer(file);
var readerForBianary = new FileReader();
readerForBianary.onload = () => {
bianaries.push( readerForHashes.result );
};

readerForBianary.readAsBinaryString(file);

});

const data = {
files: bianaries,
hashes,
verify,
formId: field.formId,
fieldId: field.fieldId,
control: field.control
};
console.log(data);
}
} else {
obj.$form.data(fieldId, values[fieldId]);
}

});
}
});
Expand All @@ -81,10 +135,13 @@ domReady( function() {
formIdAttr={idAttr}
fieldsToControl={fieldsToControl}
shouldBeValidating={shouldBeValidating}
ref={(component) => {theComponent = component}} />,
ref={(component) => {
theComponent = component
}}
/>,
document.getElementById(`cf2-${idAttr}`)
);


});
} );
});
7 changes: 6 additions & 1 deletion clients/render/util.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
export const getFieldConfigBy = (fieldConfigs, findBy, findWhere ) =>{
return fieldConfigs.find( field => findWhere ===field[findBy] );

}
};
const CryptoJS = require("crypto-js");

export const hashFiles = (files) => {
return files.map( file => CryptoJS.MD5(contents).toString() );
};
5 changes: 5 additions & 0 deletions clients/tests/unit/render/md5_screenshot.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php
if( file_exists(__DIR__ . '/screenshot.jpeg') ){
echo md5_file(__DIR__ . '/screenshot.jpeg');
}
exit;
Binary file added clients/tests/unit/render/screenshot.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 23 additions & 0 deletions clients/tests/unit/render/util.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {hashFiles} from "../../../render/util";

const CryptoJS = require("crypto-js");

var fs = require('fs');
//979296365572B262DBDA9C5186C7D0BE
const expectHash = '979296365572b262dbda9c5186c7d0be';

describe( 'File hashing', () => {
it( 'Has php-compatible md5 file function', () => {
const contents = fs.readFileSync(__dirname + '/screenshot.jpeg');
const foundHash = CryptoJS.MD5(contents).toString();
expect(foundHash).toEqual(expectHash );

});

it( 'Function hashes array', () => {
const hashes = hashFiles( [
fs.readFileSync(__dirname + '/screenshot.jpeg')
]);
expect( hashes[0] ).toBe( expectHash );
})
})
15 changes: 15 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,14 @@
"dependencies": {
"@wordpress/dom-ready": "^1.2.0",
"@wordpress/url": "^2.1.0",
"crypto-js": "^3.1.9-1",
"cryptojslib": "^3.1.2",
"css-loader": "^0.28.11",
"dangerously-set-inner-html": "^2.0.1",
"exports-loader": "^0.7.0",
"inputmask": "^3.3.11",
"lodash.remove": "^4.7.0",
"md5-file": "^4.0.0",
"react-dropzone": "^6.2.4",
"react-emoji-render": "^0.4.6",
"validator": "^10.8.0"
Expand Down

0 comments on commit 200bfb7

Please sign in to comment.