Skip to content

Commit

Permalink
initial
Browse files Browse the repository at this point in the history
  • Loading branch information
aldeed committed Jul 31, 2014
0 parents commit 5245970
Show file tree
Hide file tree
Showing 9 changed files with 312 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.DS_Store
.build*
.npm*
.meteor*
smart.lock
/packages/
5 changes: 5 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
language: node_js
node_js:
- "0.10"
before_install:
- "curl -L http://git.io/ejPSng | /bin/sh"
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2014 Eric Dobbertin

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
80 changes: 80 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
cfs-autoform
=========================

WORK IN PROGRESS

A smart package for Meteor that provides a file UI component for use within an autoform. The UI component supports clicking to select files or dropping them. Once the full form is valid, the files are uploaded using CollectionFS. The form document is inserted only if the uploads are all successful. If the form document fails to insert on the server, the uploaded files are removed.

## Installation

Work in progress. For now, not on Atmosphere. Put this in the packages section of your smart.json:

```
"cfs-autoform": {
"git": "https://github.com/aldeed/meteor-cfs-autoform",
"branch": "master"
}
```

## Prerequisites

Add `autoform` and `collectionFS` packages to your app. Also add any other CFS packages you need, particularly a storage adapter package.

## Example

*Assumption: autopublish, insecure, and cfs-gridfs packages are in use*

*common.js*

```js
Docs = new Meteor.Collection("docs");
Docs.attachSchema(new SimpleSchema({
name: {
type: String
},
fileId: {
type: String,
label: "File"
}
}));

Files = new FS.Collection("files", {
stores: [new FS.Store.GridFS("filesStore")]
});

Files.allow({
download: function () {
return true;
},
fetch: null
});
```

*html:*

```html
<template name="insertForm">
{{#autoForm id="insertForm" type="insert" collection="Docs"}}
{{> afQuickField name="name"}}
{{> cfsFileField name="fileId" collection="files"}}
<button type="submit">Submit</button>
{{/autoForm}}
</template>
```

## Notes

* Only insert forms (`type="insert"`) are supported
* The `collection` attribute for `cfsFileField` must be the same as the first argument you passed to the FS.Collection constructor.
* Files are uploaded only after you click submit and the form is valid.
* If file upload fails, the form document is not inserted.
* If one file fails to upload, any other files from that form that did upload are deleted.
* If the form document insert fails on the server, the associated files are automatically deleted as part of the latency compensation rollback.

## TODO

* Insert FS.File itself when using cfs-ejson-file package.
* Display customizable progress bar template in place of each field while uploading.
* Better template/component structure so that it does not have to be a quickField.

[![Support via Gittip](https://rawgithub.com/twolfson/gittip-badge/0.2.0/dist/gittip.png)](https://www.gittip.com/aldeed/)
8 changes: 8 additions & 0 deletions cfs-autoform.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/* CSS declarations go here */
.cfsaf_hidden {
display: none !important;
}

.cfsaf_field {
cursor: pointer !important;
}
4 changes: 4 additions & 0 deletions cfs-autoform.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<template name="cfsFileField">
<input type="file" class="cfsaf_hidden" {{inputAtts}}>
{{> afQuickField qfAtts}}
</template>
166 changes: 166 additions & 0 deletions cfs-autoform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
if (Meteor.isClient) {
Template.cfsFileField.helpers({
qfAtts: function () {
var atts = _.clone(this);
atts.type = "text";
atts.readonly = true;
var defaultPlaceholder = atts.multiple ? "Click to upload files or drop them here" : "Click to upload a file or drop it here";
atts.placeholder = atts.placeholder || defaultPlaceholder;
atts["class"] = atts["class"] || "";
atts["class"] = atts["class"] + " cfsaf_field";
delete atts.collection;
delete atts.multiple;
return atts;
},
inputAtts: function () {
var self = this;
return {
type: "file",
"data-cfs-schema-key": self.name,
"data-cfs-collection": self.collection,
multiple: self.multiple
};
}
});

function findAFData() {
var i = 1, af;
do {
af = UI._parentData(i);
i++;
} while (af && !af._af);
return af ? af._af : null;
}

var hookTracking = {};
Template.cfsFileField.rendered = function () {
var d = findAFData();
if (!d) {
throw new Error("cfsFileField must be used within an autoForm block");
}
// By adding hooks dynamically on render, hopefully any user hooks will have
// been added before so we won't disrupt expected behavior.
var formId = d.formId;
if (!hookTracking[formId]) {
hookTracking[formId] = true;
addAFHook(formId);
}
};

var handler = function (event, template) {
var fileList = [];
FS.Utility.eachFile(event, function (f) {
fileList.push(f.name);
});
template.$('[data-schema-key]').val(fileList.join(", "));
var fileList = event.originalEvent.dataTransfer ? event.originalEvent.dataTransfer.files : event.currentTarget.files;
// Store the FileList on the file input for later
$('[data-cfs-schema-key]').data("cfsaf_files", fileList);
};

Template.cfsFileField.events({
'click [data-schema-key]': function (event, template) {
template.$('[data-cfs-schema-key]').click();
},
'change [data-cfs-schema-key]': handler,
'dropped [data-schema-key]': handler
});

function deleteUploadedFiles(template) {
template.$('[data-cfs-schema-key]').each(function () {
var uploadedFiles = $(this).data("cfsaf_uploaded-files") || [];
_.each(uploadedFiles, function (f) {
f.remove();
});
});
}

function addAFHook(formId) {
AutoForm.addHooks(formId, {
before: {
// We add a before.insert hook to upload all the files in the form.
// This hook doesn't allow the form to continue submitting until
// all the files are successfully uploaded.
insert: function (doc, template) {
var self = this;
if (!AutoForm.validateForm(formId)) {
return false;
}

var totalFiles = 0;
template.$('[data-cfs-schema-key]').each(function () {
var elem = $(this);
var files = elem.data("cfsaf_files");
if (files) {
totalFiles += files.length;
}
var key = elem.attr("data-cfs-schema-key");
delete doc[key];
});

if (totalFiles === 0) {
return doc;
}

var doneFiles = 0;
var failedFiles = 0;
function cb(error, fileObj, key) {
doneFiles++;
if (error) {
failedFiles++;
} else {
doc[key] = fileObj._id;
}
if (doneFiles === totalFiles) {
if (failedFiles > 0) {
deleteUploadedFiles(template);
self.result(false);
} else {
self.result(doc);
}
}
}

template.$('[data-cfs-schema-key]').each(function () {
var elem = $(this);
var key = elem.attr("data-cfs-schema-key");
var fsCollectionName = elem.attr("data-cfs-collection");
var files = elem.data("cfsaf_files");
_.each(files, function (file) {
var fileObj = new FS.File(file);
fileObj.once("uploaded", function () {
// track successful uploads so we can delete them if any
// of the other files fail to upload
var uploadedFiles = elem.data("cfsaf_uploaded-files") || [];
uploadedFiles.push(fileObj);
elem.data("cfsaf_uploaded-files", uploadedFiles);
// call callback after uploaded, not just inserted
cb(null, fileObj, key);
});
FS._collections[fsCollectionName].insert(fileObj, function (error, fileObj) {
if (error) {
cb(error, fileObj, key);
}
// TODO progress bar during uploads
});
});
});
}
},
after: {
// We add an after.insert hook to delete uploaded files if the doc insert fails.
insert: function (error, result, template) {
var elems = template.$('[data-cfs-schema-key]');
if (error) {
deleteUploadedFiles(template);
} else {
// cleanup files data
elems.removeData("cfsaf_files");
}
// cleanup uploaded files data
elems.removeData("cfsaf_uploaded-files");
}
}
});
}
}
10 changes: 10 additions & 0 deletions package.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Package.describe({
name: "cfs-autoform",
summary: "Upload files as part of autoform submission"
});

Package.on_use(function(api) {
api.use(['autoform', 'underscore', 'collectionFS', 'templating', 'ui-dropped-event']);

api.add_files(['cfs-autoform.html', 'cfs-autoform.js', 'cfs-autoform.css'], 'client');
});
13 changes: 13 additions & 0 deletions smart.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "cfs-autoform",
"description": "Upload files as part of autoform submission",
"homepage": "https://github.com/aldeed/meteor-cfs-autoform",
"author": "Eric Dobbertin (http://dairystatedesigns.com)",
"version": "0.1.0",
"git": "https://github.com/aldeed/meteor-cfs-autoform.git",
"packages": {
"autoform": {},
"collectionFS": {},
"ui-dropped-event": {}
}
}

0 comments on commit 5245970

Please sign in to comment.