From 29a83d7008877b01b7a3d9fbfa8f341affdb20a6 Mon Sep 17 00:00:00 2001 From: dinedine Date: Wed, 2 Jun 2010 16:31:01 +0200 Subject: [PATCH] theme asset picker done (+ flash upload feature) + some refactoring about uploader --- .../admin/theme_assets_controller.rb | 43 +- app/helpers/admin/assets_helper.rb | 27 +- app/models/asset.rb | 3 + app/models/extensions/asset/vignette.rb | 46 ++ app/models/theme_asset.rb | 3 + app/uploaders/asset_uploader.rb | 6 +- app/uploaders/theme_asset_uploader.rb | 66 +-- app/views/admin/theme_assets/_asset.html.haml | 11 +- app/views/admin/theme_assets/_form.html.haml | 2 +- app/views/admin/theme_assets/images.html.haml | 3 + doc/TODO | 29 +- lib/locomotive/mongoid/model_extensions.rb | 1 + public/javascripts/admin/plugins/json2.js | 478 ++++++++++++++++++ public/javascripts/admin/plugins/scrollTo.js | 11 + public/javascripts/admin/theme_assets.js | 63 ++- public/stylesheets/admin/box.css | 3 +- 16 files changed, 647 insertions(+), 148 deletions(-) create mode 100644 app/models/extensions/asset/vignette.rb create mode 100644 lib/locomotive/mongoid/model_extensions.rb create mode 100644 public/javascripts/admin/plugins/json2.js create mode 100644 public/javascripts/admin/plugins/scrollTo.js diff --git a/app/controllers/admin/theme_assets_controller.rb b/app/controllers/admin/theme_assets_controller.rb index 80e00e61..037949c1 100644 --- a/app/controllers/admin/theme_assets_controller.rb +++ b/app/controllers/admin/theme_assets_controller.rb @@ -1,6 +1,8 @@ module Admin class ThemeAssetsController < BaseController + include ActionView::Helpers::TextHelper + sections 'settings', 'theme_assets' def index @@ -22,24 +24,33 @@ module Admin end def create - # logger.debug "request = #{request.inspect}" - # logger.debug "file size = #{request.env['rack.input'].inspect}" + params[:theme_asset] = { :source => params[:file] } if params[:file] - # File.cp(request.env['rack.input'], '/Users/didier/Desktop/FOO') + @asset = current_site.theme_assets.build(params[:theme_asset]) - if params[:file] - # params[:theme_asset][:source] = request.env['rack.input'] - @asset = current_site.theme_assets.build(:source => params[:file]) - else - @asset = current_site.theme_assets.build(params[:theme_asset]) - end - - if @asset.save - flash_success! - redirect_to edit_admin_theme_asset_url(@asset) - else - flash_error! - render :action => 'new' + respond_to do |format| + if @asset.save + format.html do + flash_success! + redirect_to edit_admin_theme_asset_url(@asset) + end + format.json do + render :json => { + :status => 'success', + :name => truncate(@asset.slug, :length => 22), + :url => @asset.source.url, + :vignette_url => @asset.vignette_url + } + end + else + format.html do + flash_error! + render :action => 'new' + end + format.json do + render :json => { :status => 'error' } + end + end end end diff --git a/app/helpers/admin/assets_helper.rb b/app/helpers/admin/assets_helper.rb index 4d167bc3..7510e439 100644 --- a/app/helpers/admin/assets_helper.rb +++ b/app/helpers/admin/assets_helper.rb @@ -1,34 +1,9 @@ module Admin::AssetsHelper def vignette_tag(asset) - if asset.image? - if asset.width < 80 && asset.height < 80 - image_tag(asset.source.url) - else - image_tag(asset.source.url(:medium)) - end - # elsif asset.pdf? - # image_tag(asset.source.url(:medium)) - else - mime_type_to_image(asset, :medium) - end + image_tag(asset.vignette_url) end - - def mime_type_to_image(asset, size = :thumb) - mime_type = File.mime_type?(asset.source_filename) - filename = "unknown" - if !(mime_type =~ /pdf/).nil? - filename = "PDF" - elsif !(mime_type =~ /css/).nil? - filename = "CSS" - elsif !(mime_type =~ /javascript/).nil? - filename = "JAVA" - end - - image_tag(File.join("admin", "icons", "filetype", size.to_s, filename + ".png")) - end - def image_dimensions_and_size(asset) content_tag(:small, "#{asset.width}px x #{@asset.height}px | #{number_to_human_size(asset.size)}") end diff --git a/app/models/asset.rb b/app/models/asset.rb index 98219ebf..8396dadc 100644 --- a/app/models/asset.rb +++ b/app/models/asset.rb @@ -3,6 +3,9 @@ class Asset include Mongoid::Document include Mongoid::Timestamps + ## Extensions ## + include Models::Extensions::Asset::Vignette + ## fields ## field :name, :type => String field :content_type, :type => String diff --git a/app/models/extensions/asset/vignette.rb b/app/models/extensions/asset/vignette.rb new file mode 100644 index 00000000..2c445668 --- /dev/null +++ b/app/models/extensions/asset/vignette.rb @@ -0,0 +1,46 @@ +module Models + + module Extensions + + module Asset + + module Vignette + + def vignette_url + if self.image? + if self.width < 80 && self.height < 80 + self.source.url + else + self.source.url(:medium) + end + # elsif asset.pdf? + # image_tag(asset.source.url(:medium)) + else + mime_type_to_url(:medium) + end + end + + protected + + def mime_type_to_url(size) + mime_type = File.mime_type?(self.source_filename) + filename = "unknown" + + if !(mime_type =~ /pdf/).nil? + filename = "PDF" + elsif !(mime_type =~ /css/).nil? + filename = "CSS" + elsif !(mime_type =~ /javascript/).nil? + filename = "JAVA" + end + + File.join("admin", "icons", "filetype", size.to_s, filename + ".png") + end + + end + + end + + end + +end \ No newline at end of file diff --git a/app/models/theme_asset.rb b/app/models/theme_asset.rb index c488cc0a..8e4a4b91 100644 --- a/app/models/theme_asset.rb +++ b/app/models/theme_asset.rb @@ -2,6 +2,9 @@ class ThemeAsset include Locomotive::Mongoid::Document + ## Extensions ## + include Models::Extensions::Asset::Vignette + ## fields ## field :slug field :content_type diff --git a/app/uploaders/asset_uploader.rb b/app/uploaders/asset_uploader.rb index 1adf706f..f6ca8f4c 100644 --- a/app/uploaders/asset_uploader.rb +++ b/app/uploaders/asset_uploader.rb @@ -30,7 +30,7 @@ class AssetUploader < CarrierWave::Uploader::Base def set_content_type value = :other - content_type = File.mime_type?(original_filename) if file.content_type == 'application/octet-stream' + content_type = file.content_type == 'application/octet-stream' ? File.mime_type?(original_filename) : file.content_type self.class.content_types.each_pair do |type, rules| rules.each do |rule| @@ -59,7 +59,9 @@ class AssetUploader < CarrierWave::Uploader::Base :image => ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg'], :movie => [/^video/, 'application/x-shockwave-flash', 'application/x-swf'], :audio => [/^audio/, 'application/ogg', 'application/x-mp3'], - :pdf => ['application/pdf', 'application/x-pdf'] + :pdf => ['application/pdf', 'application/x-pdf'], + :stylesheet => ['text/css'], + :javascript => ['text/javascript', 'text/js', 'application/x-javascript'] } end diff --git a/app/uploaders/theme_asset_uploader.rb b/app/uploaders/theme_asset_uploader.rb index 437a4723..b02202ea 100644 --- a/app/uploaders/theme_asset_uploader.rb +++ b/app/uploaders/theme_asset_uploader.rb @@ -1,71 +1,13 @@ # encoding: utf-8 -class ThemeAssetUploader < CarrierWave::Uploader::Base - - include CarrierWave::RMagick - - # Choose what kind of storage to use for this uploader - # storage :file - # storage :s3 - - # Override the directory where uploaded files will be stored - # This is a sensible default for uploaders that are meant to be mounted: - def store_dir - "sites/#{model.site_id}/themes/#{model.id}" - end - - version :thumb do - process :resize_to_fill => [50, 50] - process :convert => 'png' - end - - version :medium do - process :resize_to_fill => [80, 80] - process :convert => 'png' - end - - version :preview do - process :resize_to_fit => [880, 1100] - process :convert => 'png' - end +class ThemeAssetUploader < AssetUploader process :set_content_type process :set_size process :set_width_and_height - - def set_content_type - value = :other - - content_type = File.mime_type?(original_filename) if file.content_type == 'application/octet-stream' - - self.class.content_types.each_pair do |type, rules| - rules.each do |rule| - case rule - when String then value = type if content_type == rule - when Regexp then value = type if (content_type =~ rule) == 0 - end - end - end - - model.content_type = value - end - def set_size - model.size = file.size - end - - def set_width_and_height - if model.image? - model.width, model.height = `identify -format "%wx%h" #{file.path}`.split(/x/).collect(&:to_i) - end - end - - def self.content_types - { - :image => ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg'], - :stylesheet => ['text/css'], - :javascript => ['text/javascript', 'text/js', 'application/x-javascript'] - } + def store_dir + "sites/#{model.site_id}/themes/#{model.id}" end def extension_white_list @@ -82,4 +24,4 @@ class ThemeAssetUploader < CarrierWave::Uploader::Base end end -end +end \ No newline at end of file diff --git a/app/views/admin/theme_assets/_asset.html.haml b/app/views/admin/theme_assets/_asset.html.haml index 95f5047c..4fb4cc28 100644 --- a/app/views/admin/theme_assets/_asset.html.haml +++ b/app/views/admin/theme_assets/_asset.html.haml @@ -1,11 +1,12 @@ -- per_row ||= 6 -- edit_mode = defined?(edit).nil? ? true: edit +- per_row = local_assigns[:per_row] || 6 +- asset_counter = local_assigns[:asset_counter] || 0 +- edit = local_assigns.key?(:edit) ? edit : true -%li{ :class => "asset #{'last' if (asset_counter + 1) % per_row == 0}"} - %h4= link_to truncate(asset.slug, :length => 22), edit_mode ? edit_admin_theme_asset_path(asset) : asset.source.url +%li{ :class => "#{asset.new_record? ? 'new-asset' : 'asset'} #{'last' if (asset_counter + 1) % per_row == 0}"} + %h4= link_to truncate(asset.slug, :length => 18), edit ? edit_admin_theme_asset_path(asset) : asset.source.url .image .inside = vignette_tag(asset) - - if edit_mode + - if edit .actions = link_to image_tag('admin/list/icons/cross.png'), admin_theme_asset_path(asset), :class => 'remove', :confirm => t('admin.messages.confirm'), :method => :delete \ No newline at end of file diff --git a/app/views/admin/theme_assets/_form.html.haml b/app/views/admin/theme_assets/_form.html.haml index b289d20a..e4acf486 100644 --- a/app/views/admin/theme_assets/_form.html.haml +++ b/app/views/admin/theme_assets/_form.html.haml @@ -1,5 +1,5 @@ - content_for :head do - = javascript_include_tag 'admin/plugins/codemirror/codemirror', 'admin/plugins/fancybox', 'admin/plugins/plupload/plupload.full.js', 'admin/theme_assets.js' + = javascript_include_tag 'admin/plugins/json2', 'admin/plugins/scrollTo', 'admin/plugins/codemirror/codemirror', 'admin/plugins/fancybox', 'admin/plugins/plupload/plupload.full.js', 'admin/theme_assets.js' = stylesheet_link_tag 'admin/plugins/fancybox', 'admin/box' = f.hidden_field :performing_plain_text diff --git a/app/views/admin/theme_assets/images.html.haml b/app/views/admin/theme_assets/images.html.haml index 2371c1af..3d4db34c 100644 --- a/app/views/admin/theme_assets/images.html.haml +++ b/app/views/admin/theme_assets/images.html.haml @@ -8,5 +8,8 @@ %p.no-items= t('.no_items') - else %ul.assets + = render 'asset', :asset => current_site.theme_assets.build, :edit => false + = render :partial => 'asset', :collection => @image_assets, :locals => { :per_row => 3, :edit => false } + %li.clear \ No newline at end of file diff --git a/doc/TODO b/doc/TODO index b2fcf22e..b4398a37 100644 --- a/doc/TODO +++ b/doc/TODO @@ -1,10 +1,12 @@ BOARD: -- theme assets picker (???) - x lightbox (http://fancybox.net/api) - x select it - - flash upload (http://www.plupload.com/example_custom.php) - theme assets: disable version if not image -- refactor theme assets / assets uploaders +- refactoring: CustomFields::CustomField => CustomFields::Field +- new types for custom field + - file + - boolean + - date +- optimization custom_fields: use dynamic class for a collection instead of modifying the metaclass each time we build an item + BACKLOG: @@ -14,15 +16,6 @@ BACKLOG: - cucumber features for admin pages - refactoring admin crud (pages + layouts + snippets) -- icons for mime type - -- new types for custom field - - file - - boolean - - date -- refactoring: CustomFields::CustomField => CustomFields::Field -- optimization custom_fields: use dynamic class for a collection instead of modifying the metaclass each time we build an item - - deploy on Heroku BUGS: @@ -31,6 +24,7 @@ BUGS: NICE TO HAVE: - asset collections: custom resizing if image - super_finder +- better icons for mime type DONE: x admin layout @@ -101,4 +95,9 @@ x how to disable a page part in layout ? (BUG) x non published page (redirect to 404 ?) x refactoring page.rb => create module pagetree ! assets uploader: remove old files if new one (BUG non ) -x CodeMirror: switch js -> css -> js .... (http://marijn.haverbeke.nl/codemirror/manual.html) \ No newline at end of file +x CodeMirror: switch js -> css -> js .... (http://marijn.haverbeke.nl/codemirror/manual.html) +x theme assets picker (???) + x lightbox (http://fancybox.net/api) + x select it + x flash upload (http://www.plupload.com/example_custom.php) +x refactor theme assets / assets uploaders \ No newline at end of file diff --git a/lib/locomotive/mongoid/model_extensions.rb b/lib/locomotive/mongoid/model_extensions.rb new file mode 100644 index 00000000..dfec19c6 --- /dev/null +++ b/lib/locomotive/mongoid/model_extensions.rb @@ -0,0 +1 @@ +Dir[File.join(Rails.root, 'app', 'models', 'extensions', '**', '*.rb')].each { |lib| require lib } \ No newline at end of file diff --git a/public/javascripts/admin/plugins/json2.js b/public/javascripts/admin/plugins/json2.js new file mode 100644 index 00000000..e0c9df84 --- /dev/null +++ b/public/javascripts/admin/plugins/json2.js @@ -0,0 +1,478 @@ +/* + http://www.JSON.org/json2.js + 2009-04-16 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + See http://www.JSON.org/js.html + + This file creates a global JSON object containing two methods: stringify + and parse. + + JSON.stringify(value, replacer, space) + value any JavaScript value, usually an object or array. + + replacer an optional parameter that determines how object + values are stringified for objects. It can be a + function or an array of strings. + + space an optional parameter that specifies the indentation + of nested structures. If it is omitted, the text will + be packed without extra whitespace. If it is a number, + it will specify the number of spaces to indent at each + level. If it is a string (such as '\t' or ' '), + it contains the characters used to indent at each level. + + This method produces a JSON text from a JavaScript value. + + When an object value is found, if the object contains a toJSON + method, its toJSON method will be called and the result will be + stringified. A toJSON method does not serialize: it returns the + value represented by the name/value pair that should be serialized, + or undefined if nothing should be serialized. The toJSON method + will be passed the key associated with the value, and this will be + bound to the object holding the key. + + For example, this would serialize Dates as ISO strings. + + Date.prototype.toJSON = function (key) { + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; + + You can provide an optional replacer method. It will be passed the + key and value of each member, with this bound to the containing + object. The value that is returned from your method will be + serialized. If your method returns undefined, then the member will + be excluded from the serialization. + + If the replacer parameter is an array of strings, then it will be + used to select the members to be serialized. It filters the results + such that only members with keys listed in the replacer array are + stringified. + + Values that do not have JSON representations, such as undefined or + functions, will not be serialized. Such values in objects will be + dropped; in arrays they will be replaced with null. You can use + a replacer function to replace those with JSON values. + JSON.stringify(undefined) returns undefined. + + The optional space parameter produces a stringification of the + value that is filled with line breaks and indentation to make it + easier to read. + + If the space parameter is a non-empty string, then that string will + be used for indentation. If the space parameter is a number, then + the indentation will be that many spaces. + + Example: + + text = JSON.stringify(['e', {pluribus: 'unum'}]); + // text is '["e",{"pluribus":"unum"}]' + + + text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); + // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' + + text = JSON.stringify([new Date()], function (key, value) { + return this[key] instanceof Date ? + 'Date(' + this[key] + ')' : value; + }); + // text is '["Date(---current time---)"]' + + + JSON.parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = JSON.parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { + var d; + if (typeof value === 'string' && + value.slice(0, 5) === 'Date(' && + value.slice(-1) === ')') { + d = new Date(value.slice(5, -1)); + if (d) { + return d; + } + } + return value; + }); + + + This is a reference implementation. You are free to copy, modify, or + redistribute. + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. +*/ + +/*jslint evil: true */ + +/*global JSON */ + +/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, + call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, + lastIndex, length, parse, prototype, push, replace, slice, stringify, + test, toJSON, toString, valueOf +*/ + +// Create a JSON object only if one does not already exist. We create the +// methods in a closure to avoid creating global variables. + +if (!this.JSON) { + JSON = {}; +} +(function () { + + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + if (typeof Date.prototype.toJSON !== 'function') { + + Date.prototype.toJSON = function (key) { + + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; + + String.prototype.toJSON = + Number.prototype.toJSON = + Boolean.prototype.toJSON = function (key) { + return this.valueOf(); + }; + } + + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + rep; + + + function quote(string) { + +// If the string contains no control characters, no quote characters, and no +// backslash characters, then we can safely slap some quotes around it. +// Otherwise we must also replace the offending characters with safe escape +// sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? + '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' ? c : + '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : + '"' + string + '"'; + } + + + function str(key, holder) { + +// Produce a string from holder[key]. + + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key]; + +// If the value has a toJSON method, call it to obtain a replacement value. + + if (value && typeof value === 'object' && + typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + +// If we were called with a replacer function, then call the replacer to +// obtain a replacement value. + + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + +// What happens next depends on the value's type. + + switch (typeof value) { + case 'string': + return quote(value); + + case 'number': + +// JSON numbers must be finite. Encode non-finite numbers as null. + + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + +// If the value is a boolean or null, convert it to a string. Note: +// typeof null does not produce 'null'. The case is included here in +// the remote chance that this gets fixed someday. + + return String(value); + +// If the type is 'object', we might be dealing with an object or an array or +// null. + + case 'object': + +// Due to a specification blunder in ECMAScript, typeof null is 'object', +// so watch out for that case. + + if (!value) { + return 'null'; + } + +// Make an array to hold the partial results of stringifying this object value. + + gap += indent; + partial = []; + +// Is the value an array? + + if (Object.prototype.toString.apply(value) === '[object Array]') { + +// The value is an array. Stringify every element. Use null as a placeholder +// for non-JSON values. + + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + +// Join all of the elements together, separated with commas, and wrap them in +// brackets. + + v = partial.length === 0 ? '[]' : + gap ? '[\n' + gap + + partial.join(',\n' + gap) + '\n' + + mind + ']' : + '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + +// If the replacer is an array, use it to select the members to be stringified. + + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + k = rep[i]; + if (typeof k === 'string') { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + +// Otherwise, iterate through all of the keys in the object. + + for (k in value) { + if (Object.hasOwnProperty.call(value, k)) { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + +// Join all of the member texts together, separated with commas, +// and wrap them in braces. + + v = partial.length === 0 ? '{}' : + gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + + mind + '}' : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + +// If the JSON object does not yet have a stringify method, give it one. + + if (typeof JSON.stringify !== 'function') { + JSON.stringify = function (value, replacer, space) { + +// The stringify method takes a value and an optional replacer, and an optional +// space parameter, and returns a JSON text. The replacer can be a function +// that can replace values, or an array of strings that will select the keys. +// A default replacer method can be provided. Use of the space parameter can +// produce text that is more easily readable. + + var i; + gap = ''; + indent = ''; + +// If the space parameter is a number, make an indent string containing that +// many spaces. + + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + +// If the space parameter is a string, it will be used as the indent string. + + } else if (typeof space === 'string') { + indent = space; + } + +// If there is a replacer, it must be a function or an array. +// Otherwise, throw an error. + + rep = replacer; + if (replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + +// Make a fake root object containing our value under the key of ''. +// Return the result of stringifying the value. + + return str('', {'': value}); + }; + } + + +// If the JSON object does not yet have a parse method, give it one. + + if (typeof JSON.parse !== 'function') { + JSON.parse = function (text, reviver) { + +// The parse method takes a text and an optional reviver function, and returns +// a JavaScript value if the text is a valid JSON text. + + var j; + + function walk(holder, key) { + +// The walk method is used to recursively walk the resulting structure so +// that modifications can be made. + + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + for (k in value) { + if (Object.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + } + + +// Parsing happens in four stages. In the first stage, we replace certain +// Unicode characters with escape sequences. JavaScript handles many characters +// incorrectly, either silently deleting them, or treating them as line endings. + + cx.lastIndex = 0; + if (cx.test(text)) { + text = text.replace(cx, function (a) { + return '\\u' + + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }); + } + +// In the second stage, we run the text against regular expressions that look +// for non-JSON patterns. We are especially concerned with '()' and 'new' +// because they can cause invocation, and '=' because it can cause mutation. +// But just to be safe, we want to reject all unexpected forms. + +// We split the second stage into 4 regexp operations in order to work around +// crippling inefficiencies in IE's and Safari's regexp engines. First we +// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we +// replace all simple value tokens with ']' characters. Third, we delete all +// open brackets that follow a colon or comma or that begin the text. Finally, +// we look to see that the remaining characters are only whitespace or ']' or +// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. + + if (/^[\],:{}\s]*$/. +test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). +replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). +replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + +// In the third stage we use the eval function to compile the text into a +// JavaScript structure. The '{' operator is subject to a syntactic ambiguity +// in JavaScript: it can begin a block or an object literal. We wrap the text +// in parens to eliminate the ambiguity. + + j = eval('(' + text + ')'); + +// In the optional fourth stage, we recursively walk the new structure, passing +// each name/value pair to a reviver function for possible transformation. + + return typeof reviver === 'function' ? + walk({'': j}, '') : j; + } + +// If the text is not JSON parseable, then a SyntaxError is thrown. + + throw new SyntaxError('JSON.parse'); + }; + } +}()); \ No newline at end of file diff --git a/public/javascripts/admin/plugins/scrollTo.js b/public/javascripts/admin/plugins/scrollTo.js new file mode 100644 index 00000000..5e787781 --- /dev/null +++ b/public/javascripts/admin/plugins/scrollTo.js @@ -0,0 +1,11 @@ +/** + * jQuery.ScrollTo - Easy element scrolling using jQuery. + * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com + * Dual licensed under MIT and GPL. + * Date: 5/25/2009 + * @author Ariel Flesler + * @version 1.4.2 + * + * http://flesler.blogspot.com/2007/10/jqueryscrollto.html + */ +;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery); \ No newline at end of file diff --git a/public/javascripts/admin/theme_assets.js b/public/javascripts/admin/theme_assets.js index 5a42190a..efb37e70 100644 --- a/public/javascripts/admin/theme_assets.js +++ b/public/javascripts/admin/theme_assets.js @@ -20,6 +20,19 @@ var enableFileOrTextToggling = function() { }); } +var copyLinkToEditor = function(link, event) { + var editor = CodeMirrorEditors[0].editor; + var handle = editor.cursorLine(), position = editor.cursorPosition(handle).character; + var text = 'url("' + link.attr('href') + '")'; + + editor.insertIntoLine(handle, position, text); + + event.stopPropagation(); + event.preventDefault(); + + $.fancybox.close(); +} + var setupUploader = function() { var multipartParams = {}; multipartParams[$('meta[name=csrf-param]').attr('content')] = $('meta[name=csrf-token]').attr('content'); @@ -39,18 +52,41 @@ var setupUploader = function() { uploader.start(); }); + uploader.bind('FileUploaded', function(up, file, response) { + var json = JSON.parse(response.response); + + if (json.status == 'success') { + var asset = $('.asset-picker ul li.new-asset') + .clone() + .insertBefore($('.asset-picker ul li.clear')) + .addClass('asset'); + + asset.find('h4 a').attr('href', json.url).html(json.name).bind('click', function(e) { + copyLinkToEditor($(this), e); + }); + asset.find('.image .inside img').attr('src', json.vignette_url); + + if ($('.asset-picker ul li.asset').length % 3 == 0) + asset.addClass('last'); + + asset.removeClass('new-asset'); + + $('.asset-picker ul').scrollTo($('li.asset:last'), 400); + } + }); + uploader.init(); } $(document).ready(function() { enableFileOrTextToggling(); - // $('code.stylesheet textarea').each(function() { - // addCodeMirrorEditor(null, $(this), ["tokenizejavascript.js", "parsejavascript.js", "parsecss.js"]); - // }); - // $('code.javascript textarea').each(function() { - // addCodeMirrorEditor(null, $(this), ["parsecss.js", "tokenizejavascript.js", "parsejavascript.js"]); - // }); + $('code.stylesheet textarea').each(function() { + addCodeMirrorEditor(null, $(this), ["tokenizejavascript.js", "parsejavascript.js", "parsecss.js"]); + }); + $('code.javascript textarea').each(function() { + addCodeMirrorEditor(null, $(this), ["parsecss.js", "tokenizejavascript.js", "parsejavascript.js"]); + }); $('select#theme_asset_content_type').bind('change', function() { var editor = CodeMirrorEditors[0].editor; @@ -61,20 +97,7 @@ $(document).ready(function() { 'onComplete': function() { setupUploader(); - $('ul.assets h4 a').bind('click', function(e) { - var editor = CodeMirrorEditors[0].editor; - var handle = editor.cursorLine(), position = editor.cursorPosition(handle).character; - var text = 'url("' + $(this).attr('href') + '")'; - - editor.insertIntoLine(handle, position, text); - - e.stopPropagation(); - e.preventDefault(); - - $.fancybox.close(); - }); + $('ul.assets h4 a').bind('click', function(e) { copyLinkToEditor($(this), e); }); } }); - - $('a#asset-picker-link').click(); }); \ No newline at end of file diff --git a/public/stylesheets/admin/box.css b/public/stylesheets/admin/box.css index 9f2257c9..b694e54a 100644 --- a/public/stylesheets/admin/box.css +++ b/public/stylesheets/admin/box.css @@ -10,4 +10,5 @@ div.asset-picker h2 { padding-bottom:10px; } -div.asset-picker ul { overflow: auto; height: 471px; } \ No newline at end of file +div.asset-picker ul { overflow: auto; height: 471px; } +div.asset-picker ul li.new-asset { display: none; } \ No newline at end of file