diff --git a/.env.development b/.env.development index 846bc9cf8..a11d6864c 100644 --- a/.env.development +++ b/.env.development @@ -6,7 +6,7 @@ DATABASE_PASSWORD=password DATABASE_NAME=r_solutions_development DATABASE_PORT=5432 REDIS_URL=redis://solutions_redis:6379/12 -APP_HOST=localhost +APP_HOST=localhost:5250 RECAPTCHA_SITE_KEY=foocvi0PSRc_AyhjP7jcN RECAPTCHA_SECRET_KEY=bar8saabKym-6u5KGh VIOLET_SERVICE_TIMEOUT=500 diff --git a/app/controllers/comfy/admin/sales_collateral_controller.rb b/app/controllers/comfy/admin/sales_collateral_controller.rb index 3f92711f2..d13fef443 100644 --- a/app/controllers/comfy/admin/sales_collateral_controller.rb +++ b/app/controllers/comfy/admin/sales_collateral_controller.rb @@ -10,4 +10,10 @@ def dashboard @website = host @email = email_resolved_for_apex end + + def generate + subdomain = Subdomain.current + subdomain.generate_default_sales_assets + redirect_to sales_collateral_path + end end \ No newline at end of file diff --git a/app/models/comfy/cms/page.rb b/app/models/comfy/cms/page.rb new file mode 100644 index 000000000..ef9896344 --- /dev/null +++ b/app/models/comfy/cms/page.rb @@ -0,0 +1,175 @@ +# frozen_string_literal: true + +class Comfy::Cms::Page < ActiveRecord::Base + + self.table_name = "comfy_cms_pages" + + include Comfy::Cms::WithFragments + include Comfy::Cms::WithCategories + + cms_acts_as_tree counter_cache: :children_count, order: :position + cms_has_revisions_for :fragments_attributes + + attr_accessor :content + + # -- Relationships ----------------------------------------------------------- + belongs_to :site + belongs_to :target_page, + class_name: "Comfy::Cms::Page", + optional: true + + has_many :translations, + dependent: :destroy + + # -- Callbacks --------------------------------------------------------------- + before_validation :assigns_label, + :assign_parent, + :escape_slug, + :assign_full_path + before_create :assign_position + after_save :sync_child_full_paths! + after_find :unescape_slug_and_path + + # -- Validations ------------------------------------------------------------- + validates :label, + presence: true + validates :slug, + presence: true, + uniqueness: { scope: :parent_id }, + unless: ->(p) { + p.site && (p.site.pages.count.zero? || p.site.pages.root == self) + } + validate :validate_target_page + validate :validate_format_of_unescaped_slug + + # -- Scopes ------------------------------------------------------------------ + scope :published, -> { where(is_published: true) } + + # -- Violet customizations ------ + has_one_attached :og_image + has_one_attached :story_post + has_one_attached :landscape_post + + # -- Class Methods ----------------------------------------------------------- + # Tree-like structure for pages + def self.options_for_select(site:, current_page: nil, exclude_self: false) + options = [] + + options_for_page = ->(page, depth = 0) do + return if page.nil? + return if exclude_self && page == current_page + + options << ["#{'. . ' * depth}#{page.label}", page.id] + + page.children.order(:position).each do |child_page| + options_for_page.call(child_page, depth + 1) + end + end + + options_for_page.call(site.pages.root) + + options + end + + # -- Instance Methods -------------------------------------------------------- + # For previewing purposes sometimes we need to have full_path set. This + # full path take care of the pages and its childs but not of the site path + def full_path + read_attribute(:full_path) || assign_full_path + end + + # Somewhat unique method of identifying a page that is not a full_path + def identifier + parent_id.blank? ? "index" : full_path[1..-1].parameterize + end + + # Full url for a page + def url(relative: false) + [site.url(relative: relative), full_path].compact.join + end + + # This method will mutate page object by transfering attributes from translation + # for a given locale. + def translate! + # If site locale same as page's or there's no translastions, we do nothing + if site.locale == I18n.locale.to_s || translations.blank? + return + end + + translation = translations.published.find_by!(locale: I18n.locale) + self.layout = translation.layout + self.label = translation.label + self.content_cache = translation.content_cache + + # We can't just assign fragments as it's a relation and will write to DB + # This has odd side-effect of preserving page's fragments and just replacing + # them from the translation. Not an issue if all fragments match. + self.fragments_attributes = translation.fragments_attributes + readonly! + + self + end + +protected + + def assigns_label + self.label = label.blank? ? slug.try(:titleize) : label + end + + def assign_parent + return unless site + self.parent ||= site.pages.root unless self == site.pages.root || site.pages.count.zero? + end + + def assign_full_path + self.full_path = + if self.parent + [CGI.escape(self.parent.full_path).gsub("%2F", "/"), slug].join("/").squeeze("/") + else + "/" + end + end + + def assign_position + return unless self.parent + return if position.to_i.positive? + max = self.parent.children.maximum(:position) + self.position = max ? max + 1 : 0 + end + + def validate_target_page + return unless target_page + p = self + while p.target_page + if (p = p.target_page) == self + return errors.add(:target_page_id, "Invalid Redirect") + end + end + end + + def validate_format_of_unescaped_slug + return unless slug.present? + unescaped_slug = CGI.unescape(slug) + errors.add(:slug, :invalid) unless unescaped_slug =~ %r{^\p{Alnum}[\.\p{Alnum}\p{Mark}_-]*$}i + end + + # Forcing re-saves for child pages so they can update full_paths + def sync_child_full_paths! + return unless full_path_previously_changed? + children.each do |p| + p.update_attribute(:full_path, p.send(:assign_full_path)) + end + end + + # Escape slug unless it's nonexistent (root) + def escape_slug + self.slug = CGI.escape(slug) unless slug.nil? + end + + # Unescape the slug and full path back into their original forms unless they're nonexistent + def unescape_slug_and_path + self.slug = CGI.unescape(slug) unless slug.nil? + self.full_path = CGI.unescape(full_path) unless full_path.nil? + end + +end \ No newline at end of file diff --git a/app/models/subdomain.rb b/app/models/subdomain.rb index 74690fe8e..0371a1bee 100755 --- a/app/models/subdomain.rb +++ b/app/models/subdomain.rb @@ -14,6 +14,11 @@ class Subdomain < ApplicationRecord has_one_attached :favicon has_one_attached :og_image has_one_attached :qr_code + has_one_attached :story_post + has_one_attached :landscape_post + has_one_attached :square_post + + has_rich_text :email_signature @@ -219,6 +224,73 @@ def puppeteer_capture end end + def generate_default_sales_assets + # Get the host + subdomain = Apartment::Tenant.current + subdomain_resolved_for_apex = subdomain == 'public' || subdomain == 'root' ? "http://#{ENV['APP_HOST']}" : "http://#{subdomain}.#{ENV['APP_HOST']}" + url = subdomain_resolved_for_apex + Puppeteer.launch(headless: true, args: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-dev-shm-usage']) do |browser| + page = browser.new_page + page.goto(url) + page.viewport = Puppeteer::Viewport.new(width: 1080, height: 1920) + screenshot_settings = { + type: 'jpeg', + quality: ENV["PUPPETEER_SCREENSHOT_QUALITY"] ? ENV["PUPPETEER_SCREENSHOT_QUALITY"].to_i : 50 + } + # optioanlly remove Violet Cookie banner + dimensions = page.evaluate(<<~JAVASCRIPT) + () => { + + // Source - https://stackoverflow.com/a + // Posted by Johan Dettmar, modified by community. See post 'Timeline' for change history + // Retrieved 2025-11-12, License - CC BY-SA 4.0 + + Element.prototype.remove = function() { + this.parentElement.removeChild(this); + } + NodeList.prototype.remove = HTMLCollection.prototype.remove = function() { + for(var i = this.length - 1; i >= 0; i--) { + if(this[i] && this[i].parentElement) { + this[i].parentElement.removeChild(this[i]); + } + } + } + document.getElementById("cookie-consent-wrapper").remove(); + } + JAVASCRIPT + + screenshot = page.screenshot(**screenshot_settings) + binary_output = screenshot + self.story_post.attach( + io: StringIO.new(binary_output), + filename: "story.jpeg", + content_type: "image/jpeg", + identify: false + ) + + page.viewport = Puppeteer::Viewport.new(width: 1920, height: 1080) + screenshot = page.screenshot(**screenshot_settings) + binary_output = screenshot + self.landscape_post.attach( + io: StringIO.new(binary_output), + filename: "landscape.jpeg", + content_type: "image/jpeg", + identify: false + ) + + page.viewport = Puppeteer::Viewport.new(width: 1080, height: 1080) + screenshot = page.screenshot(**screenshot_settings) + binary_output = screenshot + self.square_post.attach( + io: StringIO.new(binary_output), + filename: "square.jpeg", + content_type: "image/jpeg", + identify: false + ) + browser.close + end + end + private def change_2fa_setting diff --git a/app/views/comfy/admin/sales_collateral/dashboard.html.haml b/app/views/comfy/admin/sales_collateral/dashboard.html.haml index 90a3382bf..130e9b07d 100644 --- a/app/views/comfy/admin/sales_collateral/dashboard.html.haml +++ b/app/views/comfy/admin/sales_collateral/dashboard.html.haml @@ -2,7 +2,9 @@ .d-flex.my-2.justify-content-between.align-items-center .h2.mb-0 Sales Collateral - = link_to 'Sales Collateral Builder - coming soon', sales_collateral_path, role: 'button', class: 'btn btn-primary' + .d-flex + = link_to 'Sales Collateral Builder - coming soon', sales_collateral_path, role: 'button', class: 'btn btn-primary m-2' + = link_to 'Refresh', sales_collateral_generate_path, role: 'button', class: 'btn btn-secondary m-2' .card .card-header @@ -72,6 +74,51 @@ .m-2 = image_tag(Subdomain.current.qr_code) + + +.card.my-5 + .card-header + %strong + Outbound + .card-body + %p.m-2 + Apex + #accordion + .card + #headingOne.card-header + %h5.mb-0 + %button.btn.btn-link{"aria-controls" => "collapseOne", "aria-expanded" => "false", "data-target" => "#collapseOne", "data-toggle" => "collapse"} + Square Post: + #collapseOne.collapse.show{"aria-labelledby" => "headingOne", "data-parent" => "#accordion"} + .card-body + .container + .img-fluid + = image_tag(Subdomain.current.square_post) if Subdomain.current.square_post.attached? + .card + #headingTwo.card-header + %h5.mb-0 + %button.btn.btn-link.collapsed{"aria-controls" => "collapseTwo", "aria-expanded" => "false", "data-target" => "#collapseTwo", "data-toggle" => "collapse"} + Story Post: + #collapseTwo.collapse{"aria-labelledby" => "headingTwo", "data-parent" => "#accordion"} + .card-body + .container + .img-fluid + = image_tag(Subdomain.current.story_post) if Subdomain.current.story_post.attached? + .card + #headingThree.card-header + %h5.mb-0 + %button.btn.btn-link.collapsed{"aria-controls" => "collapseThree", "aria-expanded" => "false", "data-target" => "#collapseThree", "data-toggle" => "collapse"} + Landscape Post: + #collapseThree.collapse{"aria-labelledby" => "headingThree", "data-parent" => "#accordion"} + .card-body + .container + .img-fluid + = image_tag(Subdomain.current.landscape_post) if Subdomain.current.landscape_post.attached? + %p.m-2 + CMS Pages + - Comfy::Cms::Page.all.each do |page| + = page.full_path + .card.my-5 .card-header %strong diff --git a/config/routes.rb b/config/routes.rb index ec83d3406..b972bb6e5 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -23,6 +23,8 @@ def self.matches?(request) get 'v2/dashboard', to: 'comfy/admin/v2/dashboard#dashboard' get 'sales_collateral', to: 'comfy/admin/sales_collateral#dashboard' + get 'sales_collateral/generate', to: 'comfy/admin/sales_collateral#generate' + get "/sales_collateral_builder", to: redirect("/motionity/src/index.html") # video calling, lock down new/create actions-- and allow public show action get 'rooms', to: 'comfy/admin/rooms#new' diff --git a/public/motionity/.gitattributes b/public/motionity/.gitattributes new file mode 100644 index 000000000..dfe077042 --- /dev/null +++ b/public/motionity/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/public/motionity/LICENSE b/public/motionity/LICENSE new file mode 100644 index 000000000..c7db196a0 --- /dev/null +++ b/public/motionity/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Alyssa X + +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. diff --git a/public/motionity/README.md b/public/motionity/README.md new file mode 100644 index 000000000..3669bd38b --- /dev/null +++ b/public/motionity/README.md @@ -0,0 +1,32 @@ +# Motionity + +![Preview](preview.gif)

+The web-based motion graphics editor for everyone 📽 + +Motionity is a free and open source animation editor in the web. It's a mix of After Effects and Canva, with powerful features like keyframing, masking, filters, and more, and integrations to browse for assets to easily drag and drop into your video. + +👉 [Try it now](https://motionity.app) for free, or [read the guide in Notion](https://motionity.notion.site/Get-started-with-Motionity-bc2a2017670d4ec6a44d5ff760ca4656) + +Motionity - The web-based motion graphics editor for everyone | Product Hunt + +> You can support this project (and many others) through [GitHub Sponsors](https://github.com/sponsors/alyssaxuu)! ❤️ + +Made by [Alyssa X](https://twitter.com/alyssaxuu) + +## Features + +⚡️ Keyframing with custom easing
+🎚 Image and video filters (adjustments, blur, chroma key...)
+✂️ Trim and cut videos
+👀 Layer masking
+🔊 Audio support
+🔍 Search for images, videos, shapes and more
+✨ Text animation (typewriter, scale, fade...)
+💥 Lottie support
+🧩 Pixabay integration
+...and much more - all for free & no sign in needed! + +# + +Feel free to reach out to me through email at hi@alyssax.com or [on Twitter](https://twitter.com/alyssaxuu) if you have any questions or feedback! Hope you find this useful 💜 + diff --git a/public/motionity/preview.gif b/public/motionity/preview.gif new file mode 100644 index 000000000..127376f5d Binary files /dev/null and b/public/motionity/preview.gif differ diff --git a/public/motionity/src/assets/align-bottom.svg b/public/motionity/src/assets/align-bottom.svg new file mode 100644 index 000000000..4acc58258 --- /dev/null +++ b/public/motionity/src/assets/align-bottom.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/align-center-h.svg b/public/motionity/src/assets/align-center-h.svg new file mode 100644 index 000000000..1a523bf40 --- /dev/null +++ b/public/motionity/src/assets/align-center-h.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/align-center-v.svg b/public/motionity/src/assets/align-center-v.svg new file mode 100644 index 000000000..4a471cdc4 --- /dev/null +++ b/public/motionity/src/assets/align-center-v.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/align-left.svg b/public/motionity/src/assets/align-left.svg new file mode 100644 index 000000000..897ebc31a --- /dev/null +++ b/public/motionity/src/assets/align-left.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/align-right.svg b/public/motionity/src/assets/align-right.svg new file mode 100644 index 000000000..91475b300 --- /dev/null +++ b/public/motionity/src/assets/align-right.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/align-text-center-active.svg b/public/motionity/src/assets/align-text-center-active.svg new file mode 100644 index 000000000..e175a8c8a --- /dev/null +++ b/public/motionity/src/assets/align-text-center-active.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/align-text-center.svg b/public/motionity/src/assets/align-text-center.svg new file mode 100644 index 000000000..b22d67e4b --- /dev/null +++ b/public/motionity/src/assets/align-text-center.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/align-text-justify-active.svg b/public/motionity/src/assets/align-text-justify-active.svg new file mode 100644 index 000000000..7b8c0a1de --- /dev/null +++ b/public/motionity/src/assets/align-text-justify-active.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/align-text-justify.svg b/public/motionity/src/assets/align-text-justify.svg new file mode 100644 index 000000000..0554712c6 --- /dev/null +++ b/public/motionity/src/assets/align-text-justify.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/align-text-left-active.svg b/public/motionity/src/assets/align-text-left-active.svg new file mode 100644 index 000000000..1d5fe48e6 --- /dev/null +++ b/public/motionity/src/assets/align-text-left-active.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/align-text-left.svg b/public/motionity/src/assets/align-text-left.svg new file mode 100644 index 000000000..2a8a606e6 --- /dev/null +++ b/public/motionity/src/assets/align-text-left.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/align-text-right-active.svg b/public/motionity/src/assets/align-text-right-active.svg new file mode 100644 index 000000000..c499763af --- /dev/null +++ b/public/motionity/src/assets/align-text-right-active.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/align-text-right.svg b/public/motionity/src/assets/align-text-right.svg new file mode 100644 index 000000000..d59c59f96 --- /dev/null +++ b/public/motionity/src/assets/align-text-right.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/align-top.svg b/public/motionity/src/assets/align-top.svg new file mode 100644 index 000000000..bdc45b64a --- /dev/null +++ b/public/motionity/src/assets/align-top.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/alyssaimg.jpeg b/public/motionity/src/assets/alyssaimg.jpeg new file mode 100644 index 000000000..4f934ad01 Binary files /dev/null and b/public/motionity/src/assets/alyssaimg.jpeg differ diff --git a/public/motionity/src/assets/animals.png b/public/motionity/src/assets/animals.png new file mode 100644 index 000000000..fca5ff3e3 Binary files /dev/null and b/public/motionity/src/assets/animals.png differ diff --git a/public/motionity/src/assets/arrow.svg b/public/motionity/src/assets/arrow.svg new file mode 100644 index 000000000..a1614cea7 --- /dev/null +++ b/public/motionity/src/assets/arrow.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/audio-active.svg b/public/motionity/src/assets/audio-active.svg new file mode 100644 index 000000000..932c42afd --- /dev/null +++ b/public/motionity/src/assets/audio-active.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/audio.svg b/public/motionity/src/assets/audio.svg new file mode 100644 index 000000000..a79b33d3c --- /dev/null +++ b/public/motionity/src/assets/audio.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/audio.wav b/public/motionity/src/assets/audio.wav new file mode 100644 index 000000000..7fdc561be Binary files /dev/null and b/public/motionity/src/assets/audio.wav differ diff --git a/public/motionity/src/assets/audio/both-of-us-thumb.png b/public/motionity/src/assets/audio/both-of-us-thumb.png new file mode 100644 index 000000000..997a4b75f Binary files /dev/null and b/public/motionity/src/assets/audio/both-of-us-thumb.png differ diff --git a/public/motionity/src/assets/audio/both-of-us.mp3 b/public/motionity/src/assets/audio/both-of-us.mp3 new file mode 100644 index 000000000..0112f8479 Binary files /dev/null and b/public/motionity/src/assets/audio/both-of-us.mp3 differ diff --git a/public/motionity/src/assets/audio/epic-cinematic-trailer-thumb.png b/public/motionity/src/assets/audio/epic-cinematic-trailer-thumb.png new file mode 100644 index 000000000..57173b020 Binary files /dev/null and b/public/motionity/src/assets/audio/epic-cinematic-trailer-thumb.png differ diff --git a/public/motionity/src/assets/audio/epic-cinematic-trailer.mp3 b/public/motionity/src/assets/audio/epic-cinematic-trailer.mp3 new file mode 100644 index 000000000..2b016044d Binary files /dev/null and b/public/motionity/src/assets/audio/epic-cinematic-trailer.mp3 differ diff --git a/public/motionity/src/assets/audio/everything-feels-new-thumb.png b/public/motionity/src/assets/audio/everything-feels-new-thumb.png new file mode 100644 index 000000000..107a2d71e Binary files /dev/null and b/public/motionity/src/assets/audio/everything-feels-new-thumb.png differ diff --git a/public/motionity/src/assets/audio/everything-feels-new.mp3 b/public/motionity/src/assets/audio/everything-feels-new.mp3 new file mode 100644 index 000000000..f85667bb6 Binary files /dev/null and b/public/motionity/src/assets/audio/everything-feels-new.mp3 differ diff --git a/public/motionity/src/assets/audio/inspirational-background-thumb.png b/public/motionity/src/assets/audio/inspirational-background-thumb.png new file mode 100644 index 000000000..d73852de1 Binary files /dev/null and b/public/motionity/src/assets/audio/inspirational-background-thumb.png differ diff --git a/public/motionity/src/assets/audio/inspirational-background.mp3 b/public/motionity/src/assets/audio/inspirational-background.mp3 new file mode 100644 index 000000000..a19a53d6f Binary files /dev/null and b/public/motionity/src/assets/audio/inspirational-background.mp3 differ diff --git a/public/motionity/src/assets/audio/lofi-thumb.png b/public/motionity/src/assets/audio/lofi-thumb.png new file mode 100644 index 000000000..dc3389d47 Binary files /dev/null and b/public/motionity/src/assets/audio/lofi-thumb.png differ diff --git a/public/motionity/src/assets/audio/lofi.mp3 b/public/motionity/src/assets/audio/lofi.mp3 new file mode 100644 index 000000000..e7d40ff75 Binary files /dev/null and b/public/motionity/src/assets/audio/lofi.mp3 differ diff --git a/public/motionity/src/assets/audio/stomping-rock-thumb.png b/public/motionity/src/assets/audio/stomping-rock-thumb.png new file mode 100644 index 000000000..ee568c8fc Binary files /dev/null and b/public/motionity/src/assets/audio/stomping-rock-thumb.png differ diff --git a/public/motionity/src/assets/audio/stomping-rock.mp3 b/public/motionity/src/assets/audio/stomping-rock.mp3 new file mode 100644 index 000000000..a1b5e693e Binary files /dev/null and b/public/motionity/src/assets/audio/stomping-rock.mp3 differ diff --git a/public/motionity/src/assets/audio/the-podcast-intro-thumb.png b/public/motionity/src/assets/audio/the-podcast-intro-thumb.png new file mode 100644 index 000000000..8ff73b8fb Binary files /dev/null and b/public/motionity/src/assets/audio/the-podcast-intro-thumb.png differ diff --git a/public/motionity/src/assets/audio/the-podcast-intro.mp3 b/public/motionity/src/assets/audio/the-podcast-intro.mp3 new file mode 100644 index 000000000..0ac9518dc Binary files /dev/null and b/public/motionity/src/assets/audio/the-podcast-intro.mp3 differ diff --git a/public/motionity/src/assets/audio/tropical-summer-music-thumb.png b/public/motionity/src/assets/audio/tropical-summer-music-thumb.png new file mode 100644 index 000000000..28ec82bd8 Binary files /dev/null and b/public/motionity/src/assets/audio/tropical-summer-music-thumb.png differ diff --git a/public/motionity/src/assets/audio/tropical-summer-music.mp3 b/public/motionity/src/assets/audio/tropical-summer-music.mp3 new file mode 100644 index 000000000..baecab89e Binary files /dev/null and b/public/motionity/src/assets/audio/tropical-summer-music.mp3 differ diff --git a/public/motionity/src/assets/avatar-temp.png b/public/motionity/src/assets/avatar-temp.png new file mode 100644 index 000000000..5775891f8 Binary files /dev/null and b/public/motionity/src/assets/avatar-temp.png differ diff --git a/public/motionity/src/assets/background.png b/public/motionity/src/assets/background.png new file mode 100644 index 000000000..11b4ab206 Binary files /dev/null and b/public/motionity/src/assets/background.png differ diff --git a/public/motionity/src/assets/beach.png b/public/motionity/src/assets/beach.png new file mode 100644 index 000000000..150b02d29 Binary files /dev/null and b/public/motionity/src/assets/beach.png differ diff --git a/public/motionity/src/assets/bevel-active.svg b/public/motionity/src/assets/bevel-active.svg new file mode 100644 index 000000000..f7ef5e6cf --- /dev/null +++ b/public/motionity/src/assets/bevel-active.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/bevel.svg b/public/motionity/src/assets/bevel.svg new file mode 100644 index 000000000..08681621a --- /dev/null +++ b/public/motionity/src/assets/bevel.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/blcrop.svg b/public/motionity/src/assets/blcrop.svg new file mode 100644 index 000000000..056f8fbda --- /dev/null +++ b/public/motionity/src/assets/blcrop.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/bold-active.svg b/public/motionity/src/assets/bold-active.svg new file mode 100644 index 000000000..9bb237980 --- /dev/null +++ b/public/motionity/src/assets/bold-active.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/bold.svg b/public/motionity/src/assets/bold.svg new file mode 100644 index 000000000..3fe1a3960 --- /dev/null +++ b/public/motionity/src/assets/bold.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/brcrop.svg b/public/motionity/src/assets/brcrop.svg new file mode 100644 index 000000000..dad75fcc8 --- /dev/null +++ b/public/motionity/src/assets/brcrop.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/cars.png b/public/motionity/src/assets/cars.png new file mode 100644 index 000000000..0563a1c16 Binary files /dev/null and b/public/motionity/src/assets/cars.png differ diff --git a/public/motionity/src/assets/clear.svg b/public/motionity/src/assets/clear.svg new file mode 100644 index 000000000..bdcdbd015 --- /dev/null +++ b/public/motionity/src/assets/clear.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/close.svg b/public/motionity/src/assets/close.svg new file mode 100644 index 000000000..4da15f5ff --- /dev/null +++ b/public/motionity/src/assets/close.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/collapse.svg b/public/motionity/src/assets/collapse.svg new file mode 100644 index 000000000..2a9f9d1d1 --- /dev/null +++ b/public/motionity/src/assets/collapse.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/crop-icon.svg b/public/motionity/src/assets/crop-icon.svg new file mode 100644 index 000000000..f160bcaf0 --- /dev/null +++ b/public/motionity/src/assets/crop-icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/dash2-active.svg b/public/motionity/src/assets/dash2-active.svg new file mode 100644 index 000000000..5ae238c76 --- /dev/null +++ b/public/motionity/src/assets/dash2-active.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/dash2.svg b/public/motionity/src/assets/dash2.svg new file mode 100644 index 000000000..33fb0714e --- /dev/null +++ b/public/motionity/src/assets/dash2.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/data.json b/public/motionity/src/assets/data.json new file mode 100644 index 000000000..9e31bde60 --- /dev/null +++ b/public/motionity/src/assets/data.json @@ -0,0 +1 @@ +{"v":"5.7.1","fr":29.6104125976562,"ip":0,"op":148.002062291561,"w":1000,"h":1000,"nm":"textanim","ddd":0,"assets":[],"fonts":{"list":[{"fName":"SFProDisplay-Bold","fFamily":"SF Pro Display","fStyle":"Bold","ascent":70.458984375}]},"layers":[{"ddd":0,"ind":1,"ty":5,"nm":"thetext","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[482,449.123,0],"ix":2,"x":"var $bm_rt;\nvar H, W;\nH = thisComp.height;\nW = thisComp.width;\n$bm_rt = [\n H / 2,\n W / 2\n];"},"a":{"a":0,"k":[0,-36.377,0],"ix":1,"x":"var $bm_rt;\nvar sourceSize, T, L, W, H;\nsourceSize = thisLayer.sourceRectAtTime(time, false);\nT = sourceSize.top;\nL = sourceSize.left;\nW = sourceSize.width;\nH = sourceSize.height;\n$bm_rt = [\n L + W / 2,\n T + H / 2\n];"},"s":{"a":0,"k":[100,100,100],"ix":6,"x":"var $bm_rt;\nvar maxW, maxH, r, w, h, s;\nmaxW = $bm_mul(thisComp.width, 0.9);\nmaxH = $bm_mul(thisComp.height, 0.9);\nr = sourceRectAtTime(time);\nw = r.width;\nh = r.height;\ns = $bm_div(w, h) > $bm_div(maxW, maxH) ? $bm_div(maxW, w) : $bm_div(maxH, h);\n$bm_rt = $bm_mul([\n 100,\n 100\n], s);"}},"ao":0,"t":{"d":{"k":[{"s":{"sz":[2328.63940429688,46],"ps":[-187,-57.5],"s":60,"f":"SFProDisplay-Bold","t":"some text to test","j":2,"tr":0,"lh":72,"ls":0,"fc":[0,0,0]},"t":0}]},"p":{},"m":{"g":1,"a":{"a":0,"k":[0,0],"ix":2}},"a":[{"nm":"Animator 1","s":{"t":0,"xe":{"a":0,"k":0,"ix":7},"ne":{"a":0,"k":0,"ix":8},"a":{"a":0,"k":100,"ix":4},"b":1,"rn":0,"sh":1,"s":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"t":59.000822129744,"s":[100]}],"ix":1},"r":1},"a":{"o":{"a":0,"k":0,"ix":9}}}]},"ip":0,"op":257.003581141427,"st":0,"bm":0}],"markers":[],"chars":[{"ch":"s","size":60,"style":"Bold","w":51.46,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,-9.961],[-10.107,-2.148],[0,0],[0,-2.783],[5.371,0],[0.879,4.59],[0,0],[-14.453,0],[0,10.303],[10.938,2.295],[0,0],[0,2.686],[-4.932,0],[-0.439,-4.248],[0,0],[13.428,0]],"o":[[0,7.861],[0,0],[5.127,1.172],[0,3.418],[-5.664,0],[0,0],[0.928,10.303],[13.477,0],[0,-7.666],[0,0],[-5.273,-1.123],[0,-3.467],[5.273,0],[0,0],[-0.293,-10.254],[-13.33,0]],"v":[[3.76,-36.963],[18.994,-21.875],[27.93,-20.02],[34.863,-14.502],[26.172,-8.887],[16.357,-15.918],[2.441,-15.918],[26.172,1.123],[49.072,-15.967],[33.643,-30.225],[24.707,-32.129],[17.48,-37.744],[25.684,-43.457],[34.57,-36.328],[47.705,-36.328],[25.684,-53.467]],"c":true},"ix":2},"nm":"s","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"s","np":3,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"},{"ch":"o","size":60,"style":"Bold","w":57.28,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-15.82,0],[0,17.236],[15.674,0],[0,-16.943]],"o":[[15.82,0],[0,-16.992],[-15.674,0],[0,17.188]],"v":[[28.662,1.123],[54.59,-26.221],[28.662,-53.467],[2.734,-26.221]],"c":true},"ix":2},"nm":"o","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[6.982,0],[0,10.498],[-6.934,0],[0,-10.4]],"o":[[-7.031,0],[0,-10.4],[6.934,0],[0,10.498]],"v":[[28.662,-9.766],[17.188,-26.172],[28.662,-42.578],[40.088,-26.172]],"c":true},"ix":2},"nm":"o","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"o","np":5,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"},{"ch":"m","size":60,"style":"Bold","w":86.33,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[-5.42,0],[0,-5.615],[0,0],[0,0],[0,0],[-5.42,0],[0,-6.055],[0,0],[0,0],[0,0],[10.254,0],[2.344,-6.592],[0,0],[7.568,0],[2.197,-6.299],[0,0],[0,0],[0,0]],"o":[[0,0],[0,0],[0,-5.859],[5.273,0],[0,0],[0,0],[0,0],[0,-5.811],[5.518,0],[0,0],[0,0],[0,0],[0,-10.547],[-7.666,0],[0,0],[-1.758,-6.836],[-7.129,0],[0,0],[0,0],[0,0],[0,0]],"v":[[4.639,0],[18.896,0],[18.896,-31.592],[27.979,-41.553],[36.426,-32.617],[36.426,0],[50.146,0],[50.146,-31.787],[59.131,-41.553],[67.676,-32.178],[67.676,0],[81.934,0],[81.934,-35.742],[64.795,-53.32],[48.535,-42.578],[48.242,-42.578],[33.643,-53.32],[18.701,-42.871],[18.408,-42.871],[18.408,-52.344],[4.639,-52.344]],"c":true},"ix":2},"nm":"m","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"m","np":3,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"},{"ch":"e","size":60,"style":"Bold","w":55.52,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[5.225,0],[0,7.471],[0,0],[0,0],[0,0],[15.234,0],[0,-16.699],[-16.113,0],[-1.562,10.254]],"o":[[-1.318,4.004],[-7.275,0],[0,0],[0,0],[0,0],[0,-15.918],[-15.479,0],[0,16.748],[12.939,0],[0,0]],"v":[[39.307,-16.016],[28.76,-9.424],[16.748,-22.021],[16.748,-22.9],[52.832,-22.9],[52.832,-27.246],[27.979,-53.467],[2.734,-25.928],[28.516,1.123],[52.393,-16.016]],"c":true},"ix":2},"nm":"e","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[-6.25,0],[-0.293,-6.689],[0,0]],"o":[[6.348,0],[0,0],[0.488,-6.543]],"v":[[28.125,-42.92],[39.111,-31.641],[16.895,-31.641]],"c":true},"ix":2},"nm":"e","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"e","np":5,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"},{"ch":" ","size":60,"style":"Bold","w":19.78,"data":{},"fFamily":"SF Pro Display"},{"ch":"t","size":60,"style":"Bold","w":35.55,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[-12.305,0],[-1.465,0.342],[0,0],[1.27,0],[0,4.004],[0,0],[0,0],[0,0],[0,0],[0,0]],"o":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,10.205],[2.881,0],[0,0],[-0.879,0.146],[-4.199,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],"v":[[8.447,-64.404],[8.447,-52.344],[1.074,-52.344],[1.074,-41.602],[8.447,-41.602],[8.447,-14.111],[25.537,0.195],[32.324,-0.391],[32.324,-10.889],[28.857,-10.645],[22.705,-16.553],[22.705,-41.602],[32.373,-41.602],[32.373,-52.344],[22.705,-52.344],[22.705,-64.404]],"c":true},"ix":2},"nm":"t","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"t","np":3,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"},{"ch":"x","size":60,"style":"Bold","w":52.78,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],"o":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],"v":[[26.172,-18.164],[36.133,0],[51.611,0],[35.4,-26.465],[51.758,-52.344],[36.23,-52.344],[26.953,-34.668],[26.66,-34.668],[17.236,-52.344],[1.172,-52.344],[17.48,-26.074],[1.074,0],[16.064,0],[25.879,-18.164]],"c":true},"ix":2},"nm":"x","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"x","np":3,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"}]} \ No newline at end of file diff --git a/public/motionity/src/assets/delete.svg b/public/motionity/src/assets/delete.svg new file mode 100644 index 000000000..9a53c544d --- /dev/null +++ b/public/motionity/src/assets/delete.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/download-icon.svg b/public/motionity/src/assets/download-icon.svg new file mode 100644 index 000000000..f312a0920 --- /dev/null +++ b/public/motionity/src/assets/download-icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/drop-arrow.svg b/public/motionity/src/assets/drop-arrow.svg new file mode 100644 index 000000000..cb27d9129 --- /dev/null +++ b/public/motionity/src/assets/drop-arrow.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/edgecontrol.svg b/public/motionity/src/assets/edgecontrol.svg new file mode 100644 index 000000000..8fe63b68d --- /dev/null +++ b/public/motionity/src/assets/edgecontrol.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/eyedropper.svg b/public/motionity/src/assets/eyedropper.svg new file mode 100644 index 000000000..d2eb09352 --- /dev/null +++ b/public/motionity/src/assets/eyedropper.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/fade-in.svg b/public/motionity/src/assets/fade-in.svg new file mode 100644 index 000000000..32258808f --- /dev/null +++ b/public/motionity/src/assets/fade-in.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/filters.svg b/public/motionity/src/assets/filters.svg new file mode 100644 index 000000000..5f870503d --- /dev/null +++ b/public/motionity/src/assets/filters.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/food.png b/public/motionity/src/assets/food.png new file mode 100644 index 000000000..1af279fe5 Binary files /dev/null and b/public/motionity/src/assets/food.png differ diff --git a/public/motionity/src/assets/forest.png b/public/motionity/src/assets/forest.png new file mode 100644 index 000000000..8b10fada4 Binary files /dev/null and b/public/motionity/src/assets/forest.png differ diff --git a/public/motionity/src/assets/freeze.svg b/public/motionity/src/assets/freeze.svg new file mode 100644 index 000000000..b65d3a59a --- /dev/null +++ b/public/motionity/src/assets/freeze.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/frozen.svg b/public/motionity/src/assets/frozen.svg new file mode 100644 index 000000000..e14fbf7eb --- /dev/null +++ b/public/motionity/src/assets/frozen.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/hand-tool-active.svg b/public/motionity/src/assets/hand-tool-active.svg new file mode 100644 index 000000000..5aa53c3b8 --- /dev/null +++ b/public/motionity/src/assets/hand-tool-active.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/hand-tool.svg b/public/motionity/src/assets/hand-tool.svg new file mode 100644 index 000000000..0e8edb4e4 --- /dev/null +++ b/public/motionity/src/assets/hand-tool.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/image-active.svg b/public/motionity/src/assets/image-active.svg new file mode 100644 index 000000000..b4ddde496 --- /dev/null +++ b/public/motionity/src/assets/image-active.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/image.svg b/public/motionity/src/assets/image.svg new file mode 100644 index 000000000..c90fa480e --- /dev/null +++ b/public/motionity/src/assets/image.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/import.svg b/public/motionity/src/assets/import.svg new file mode 100644 index 000000000..eb5cc1ef2 --- /dev/null +++ b/public/motionity/src/assets/import.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/importexport.svg b/public/motionity/src/assets/importexport.svg new file mode 100644 index 000000000..c102b6d22 --- /dev/null +++ b/public/motionity/src/assets/importexport.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/italic-active.svg b/public/motionity/src/assets/italic-active.svg new file mode 100644 index 000000000..ad11f0190 --- /dev/null +++ b/public/motionity/src/assets/italic-active.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/italic.svg b/public/motionity/src/assets/italic.svg new file mode 100644 index 000000000..83955a1d5 --- /dev/null +++ b/public/motionity/src/assets/italic.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/loading-image.svg b/public/motionity/src/assets/loading-image.svg new file mode 100644 index 000000000..a167f0b08 --- /dev/null +++ b/public/motionity/src/assets/loading-image.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/public/motionity/src/assets/loading-video.svg b/public/motionity/src/assets/loading-video.svg new file mode 100644 index 000000000..c4df5b8aa --- /dev/null +++ b/public/motionity/src/assets/loading-video.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/public/motionity/src/assets/loading.gif b/public/motionity/src/assets/loading.gif new file mode 100644 index 000000000..54038677d Binary files /dev/null and b/public/motionity/src/assets/loading.gif differ diff --git a/public/motionity/src/assets/lock.svg b/public/motionity/src/assets/lock.svg new file mode 100644 index 000000000..0eb9f2267 --- /dev/null +++ b/public/motionity/src/assets/lock.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/locked.svg b/public/motionity/src/assets/locked.svg new file mode 100644 index 000000000..84257b0ab --- /dev/null +++ b/public/motionity/src/assets/locked.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/logo.svg b/public/motionity/src/assets/logo.svg new file mode 100644 index 000000000..c22b359bf --- /dev/null +++ b/public/motionity/src/assets/logo.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/lottie.json b/public/motionity/src/assets/lottie.json new file mode 100644 index 000000000..9e31bde60 --- /dev/null +++ b/public/motionity/src/assets/lottie.json @@ -0,0 +1 @@ +{"v":"5.7.1","fr":29.6104125976562,"ip":0,"op":148.002062291561,"w":1000,"h":1000,"nm":"textanim","ddd":0,"assets":[],"fonts":{"list":[{"fName":"SFProDisplay-Bold","fFamily":"SF Pro Display","fStyle":"Bold","ascent":70.458984375}]},"layers":[{"ddd":0,"ind":1,"ty":5,"nm":"thetext","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[482,449.123,0],"ix":2,"x":"var $bm_rt;\nvar H, W;\nH = thisComp.height;\nW = thisComp.width;\n$bm_rt = [\n H / 2,\n W / 2\n];"},"a":{"a":0,"k":[0,-36.377,0],"ix":1,"x":"var $bm_rt;\nvar sourceSize, T, L, W, H;\nsourceSize = thisLayer.sourceRectAtTime(time, false);\nT = sourceSize.top;\nL = sourceSize.left;\nW = sourceSize.width;\nH = sourceSize.height;\n$bm_rt = [\n L + W / 2,\n T + H / 2\n];"},"s":{"a":0,"k":[100,100,100],"ix":6,"x":"var $bm_rt;\nvar maxW, maxH, r, w, h, s;\nmaxW = $bm_mul(thisComp.width, 0.9);\nmaxH = $bm_mul(thisComp.height, 0.9);\nr = sourceRectAtTime(time);\nw = r.width;\nh = r.height;\ns = $bm_div(w, h) > $bm_div(maxW, maxH) ? $bm_div(maxW, w) : $bm_div(maxH, h);\n$bm_rt = $bm_mul([\n 100,\n 100\n], s);"}},"ao":0,"t":{"d":{"k":[{"s":{"sz":[2328.63940429688,46],"ps":[-187,-57.5],"s":60,"f":"SFProDisplay-Bold","t":"some text to test","j":2,"tr":0,"lh":72,"ls":0,"fc":[0,0,0]},"t":0}]},"p":{},"m":{"g":1,"a":{"a":0,"k":[0,0],"ix":2}},"a":[{"nm":"Animator 1","s":{"t":0,"xe":{"a":0,"k":0,"ix":7},"ne":{"a":0,"k":0,"ix":8},"a":{"a":0,"k":100,"ix":4},"b":1,"rn":0,"sh":1,"s":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"t":59.000822129744,"s":[100]}],"ix":1},"r":1},"a":{"o":{"a":0,"k":0,"ix":9}}}]},"ip":0,"op":257.003581141427,"st":0,"bm":0}],"markers":[],"chars":[{"ch":"s","size":60,"style":"Bold","w":51.46,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,-9.961],[-10.107,-2.148],[0,0],[0,-2.783],[5.371,0],[0.879,4.59],[0,0],[-14.453,0],[0,10.303],[10.938,2.295],[0,0],[0,2.686],[-4.932,0],[-0.439,-4.248],[0,0],[13.428,0]],"o":[[0,7.861],[0,0],[5.127,1.172],[0,3.418],[-5.664,0],[0,0],[0.928,10.303],[13.477,0],[0,-7.666],[0,0],[-5.273,-1.123],[0,-3.467],[5.273,0],[0,0],[-0.293,-10.254],[-13.33,0]],"v":[[3.76,-36.963],[18.994,-21.875],[27.93,-20.02],[34.863,-14.502],[26.172,-8.887],[16.357,-15.918],[2.441,-15.918],[26.172,1.123],[49.072,-15.967],[33.643,-30.225],[24.707,-32.129],[17.48,-37.744],[25.684,-43.457],[34.57,-36.328],[47.705,-36.328],[25.684,-53.467]],"c":true},"ix":2},"nm":"s","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"s","np":3,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"},{"ch":"o","size":60,"style":"Bold","w":57.28,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-15.82,0],[0,17.236],[15.674,0],[0,-16.943]],"o":[[15.82,0],[0,-16.992],[-15.674,0],[0,17.188]],"v":[[28.662,1.123],[54.59,-26.221],[28.662,-53.467],[2.734,-26.221]],"c":true},"ix":2},"nm":"o","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[6.982,0],[0,10.498],[-6.934,0],[0,-10.4]],"o":[[-7.031,0],[0,-10.4],[6.934,0],[0,10.498]],"v":[[28.662,-9.766],[17.188,-26.172],[28.662,-42.578],[40.088,-26.172]],"c":true},"ix":2},"nm":"o","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"o","np":5,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"},{"ch":"m","size":60,"style":"Bold","w":86.33,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[-5.42,0],[0,-5.615],[0,0],[0,0],[0,0],[-5.42,0],[0,-6.055],[0,0],[0,0],[0,0],[10.254,0],[2.344,-6.592],[0,0],[7.568,0],[2.197,-6.299],[0,0],[0,0],[0,0]],"o":[[0,0],[0,0],[0,-5.859],[5.273,0],[0,0],[0,0],[0,0],[0,-5.811],[5.518,0],[0,0],[0,0],[0,0],[0,-10.547],[-7.666,0],[0,0],[-1.758,-6.836],[-7.129,0],[0,0],[0,0],[0,0],[0,0]],"v":[[4.639,0],[18.896,0],[18.896,-31.592],[27.979,-41.553],[36.426,-32.617],[36.426,0],[50.146,0],[50.146,-31.787],[59.131,-41.553],[67.676,-32.178],[67.676,0],[81.934,0],[81.934,-35.742],[64.795,-53.32],[48.535,-42.578],[48.242,-42.578],[33.643,-53.32],[18.701,-42.871],[18.408,-42.871],[18.408,-52.344],[4.639,-52.344]],"c":true},"ix":2},"nm":"m","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"m","np":3,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"},{"ch":"e","size":60,"style":"Bold","w":55.52,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[5.225,0],[0,7.471],[0,0],[0,0],[0,0],[15.234,0],[0,-16.699],[-16.113,0],[-1.562,10.254]],"o":[[-1.318,4.004],[-7.275,0],[0,0],[0,0],[0,0],[0,-15.918],[-15.479,0],[0,16.748],[12.939,0],[0,0]],"v":[[39.307,-16.016],[28.76,-9.424],[16.748,-22.021],[16.748,-22.9],[52.832,-22.9],[52.832,-27.246],[27.979,-53.467],[2.734,-25.928],[28.516,1.123],[52.393,-16.016]],"c":true},"ix":2},"nm":"e","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[-6.25,0],[-0.293,-6.689],[0,0]],"o":[[6.348,0],[0,0],[0.488,-6.543]],"v":[[28.125,-42.92],[39.111,-31.641],[16.895,-31.641]],"c":true},"ix":2},"nm":"e","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"e","np":5,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"},{"ch":" ","size":60,"style":"Bold","w":19.78,"data":{},"fFamily":"SF Pro Display"},{"ch":"t","size":60,"style":"Bold","w":35.55,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[-12.305,0],[-1.465,0.342],[0,0],[1.27,0],[0,4.004],[0,0],[0,0],[0,0],[0,0],[0,0]],"o":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,10.205],[2.881,0],[0,0],[-0.879,0.146],[-4.199,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],"v":[[8.447,-64.404],[8.447,-52.344],[1.074,-52.344],[1.074,-41.602],[8.447,-41.602],[8.447,-14.111],[25.537,0.195],[32.324,-0.391],[32.324,-10.889],[28.857,-10.645],[22.705,-16.553],[22.705,-41.602],[32.373,-41.602],[32.373,-52.344],[22.705,-52.344],[22.705,-64.404]],"c":true},"ix":2},"nm":"t","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"t","np":3,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"},{"ch":"x","size":60,"style":"Bold","w":52.78,"data":{"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],"o":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],"v":[[26.172,-18.164],[36.133,0],[51.611,0],[35.4,-26.465],[51.758,-52.344],[36.23,-52.344],[26.953,-34.668],[26.66,-34.668],[17.236,-52.344],[1.172,-52.344],[17.48,-26.074],[1.074,0],[16.064,0],[25.879,-18.164]],"c":true},"ix":2},"nm":"x","mn":"ADBE Vector Shape - Group","hd":false}],"nm":"x","np":3,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}]},"fFamily":"SF Pro Display"}]} \ No newline at end of file diff --git a/public/motionity/src/assets/meditation.png b/public/motionity/src/assets/meditation.png new file mode 100644 index 000000000..6630cbbe5 Binary files /dev/null and b/public/motionity/src/assets/meditation.png differ diff --git a/public/motionity/src/assets/middlecontrol.svg b/public/motionity/src/assets/middlecontrol.svg new file mode 100644 index 000000000..53fb5b55b --- /dev/null +++ b/public/motionity/src/assets/middlecontrol.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/middlecontrolhoz.svg b/public/motionity/src/assets/middlecontrolhoz.svg new file mode 100644 index 000000000..ba05d9aaa --- /dev/null +++ b/public/motionity/src/assets/middlecontrolhoz.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/miter-active.svg b/public/motionity/src/assets/miter-active.svg new file mode 100644 index 000000000..537975c32 --- /dev/null +++ b/public/motionity/src/assets/miter-active.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/miter.svg b/public/motionity/src/assets/miter.svg new file mode 100644 index 000000000..938136c9d --- /dev/null +++ b/public/motionity/src/assets/miter.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/mockup-active.svg b/public/motionity/src/assets/mockup-active.svg new file mode 100644 index 000000000..e78b241b1 --- /dev/null +++ b/public/motionity/src/assets/mockup-active.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/mockup.svg b/public/motionity/src/assets/mockup.svg new file mode 100644 index 000000000..9cc9746aa --- /dev/null +++ b/public/motionity/src/assets/mockup.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/more-hoz.svg b/public/motionity/src/assets/more-hoz.svg new file mode 100644 index 000000000..426f3df2c --- /dev/null +++ b/public/motionity/src/assets/more-hoz.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/more-options.svg b/public/motionity/src/assets/more-options.svg new file mode 100644 index 000000000..792695886 --- /dev/null +++ b/public/motionity/src/assets/more-options.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/public/motionity/src/assets/nature.png b/public/motionity/src/assets/nature.png new file mode 100644 index 000000000..b0d0dda7c Binary files /dev/null and b/public/motionity/src/assets/nature.png differ diff --git a/public/motionity/src/assets/nolayers.svg b/public/motionity/src/assets/nolayers.svg new file mode 100644 index 000000000..a73f5b3c3 --- /dev/null +++ b/public/motionity/src/assets/nolayers.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/public/motionity/src/assets/office.png b/public/motionity/src/assets/office.png new file mode 100644 index 000000000..3397b9573 Binary files /dev/null and b/public/motionity/src/assets/office.png differ diff --git a/public/motionity/src/assets/pause-button.svg b/public/motionity/src/assets/pause-button.svg new file mode 100644 index 000000000..5fc1920af --- /dev/null +++ b/public/motionity/src/assets/pause-button.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/pixabay.svg b/public/motionity/src/assets/pixabay.svg new file mode 100644 index 000000000..efe0a7ba4 --- /dev/null +++ b/public/motionity/src/assets/pixabay.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/public/motionity/src/assets/play-button.svg b/public/motionity/src/assets/play-button.svg new file mode 100644 index 000000000..dfb901d28 --- /dev/null +++ b/public/motionity/src/assets/play-button.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/rain.png b/public/motionity/src/assets/rain.png new file mode 100644 index 000000000..bca20bfd2 Binary files /dev/null and b/public/motionity/src/assets/rain.png differ diff --git a/public/motionity/src/assets/repeat.svg b/public/motionity/src/assets/repeat.svg new file mode 100644 index 000000000..e4097b7e5 --- /dev/null +++ b/public/motionity/src/assets/repeat.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/replace-image.svg b/public/motionity/src/assets/replace-image.svg new file mode 100644 index 000000000..380dd368c --- /dev/null +++ b/public/motionity/src/assets/replace-image.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/right-arrow.svg b/public/motionity/src/assets/right-arrow.svg new file mode 100644 index 000000000..b692e9488 --- /dev/null +++ b/public/motionity/src/assets/right-arrow.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/rotateicon.svg b/public/motionity/src/assets/rotateicon.svg new file mode 100644 index 000000000..7b1d4db53 --- /dev/null +++ b/public/motionity/src/assets/rotateicon.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/round-active.svg b/public/motionity/src/assets/round-active.svg new file mode 100644 index 000000000..a99b7966a --- /dev/null +++ b/public/motionity/src/assets/round-active.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/round.svg b/public/motionity/src/assets/round.svg new file mode 100644 index 000000000..d0a9a3ee5 --- /dev/null +++ b/public/motionity/src/assets/round.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/scale.svg b/public/motionity/src/assets/scale.svg new file mode 100644 index 000000000..d8047cab1 --- /dev/null +++ b/public/motionity/src/assets/scale.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/search.svg b/public/motionity/src/assets/search.svg new file mode 100644 index 000000000..4935ec5b7 --- /dev/null +++ b/public/motionity/src/assets/search.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/seeker.svg b/public/motionity/src/assets/seeker.svg new file mode 100644 index 000000000..428571649 --- /dev/null +++ b/public/motionity/src/assets/seeker.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/shape-active.svg b/public/motionity/src/assets/shape-active.svg new file mode 100644 index 000000000..8f30f5bbc --- /dev/null +++ b/public/motionity/src/assets/shape-active.svg @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/shape.svg b/public/motionity/src/assets/shape.svg new file mode 100644 index 000000000..b7117e490 --- /dev/null +++ b/public/motionity/src/assets/shape.svg @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/shapes/arrow.svg b/public/motionity/src/assets/shapes/arrow.svg new file mode 100644 index 000000000..4d6afb297 --- /dev/null +++ b/public/motionity/src/assets/shapes/arrow.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/shapes/circle.svg b/public/motionity/src/assets/shapes/circle.svg new file mode 100644 index 000000000..93a21fc78 --- /dev/null +++ b/public/motionity/src/assets/shapes/circle.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/shapes/heart.svg b/public/motionity/src/assets/shapes/heart.svg new file mode 100644 index 000000000..5be9163ae --- /dev/null +++ b/public/motionity/src/assets/shapes/heart.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/shapes/hexagon.svg b/public/motionity/src/assets/shapes/hexagon.svg new file mode 100644 index 000000000..7efee63dc --- /dev/null +++ b/public/motionity/src/assets/shapes/hexagon.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/shapes/polygon.svg b/public/motionity/src/assets/shapes/polygon.svg new file mode 100644 index 000000000..dea3a2919 --- /dev/null +++ b/public/motionity/src/assets/shapes/polygon.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/shapes/rectangle.svg b/public/motionity/src/assets/shapes/rectangle.svg new file mode 100644 index 000000000..593b1df09 --- /dev/null +++ b/public/motionity/src/assets/shapes/rectangle.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/shapes/star.svg b/public/motionity/src/assets/shapes/star.svg new file mode 100644 index 000000000..f080d7b50 --- /dev/null +++ b/public/motionity/src/assets/shapes/star.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/shapes/triangle.svg b/public/motionity/src/assets/shapes/triangle.svg new file mode 100644 index 000000000..0bf978b44 --- /dev/null +++ b/public/motionity/src/assets/shapes/triangle.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/shrink.svg b/public/motionity/src/assets/shrink.svg new file mode 100644 index 000000000..aece229c9 --- /dev/null +++ b/public/motionity/src/assets/shrink.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/skip.svg b/public/motionity/src/assets/skip.svg new file mode 100644 index 000000000..a2ff37a1a --- /dev/null +++ b/public/motionity/src/assets/skip.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/slide-bottom.svg b/public/motionity/src/assets/slide-bottom.svg new file mode 100644 index 000000000..a5225dbc8 --- /dev/null +++ b/public/motionity/src/assets/slide-bottom.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/slide-left.svg b/public/motionity/src/assets/slide-left.svg new file mode 100644 index 000000000..9e2d08402 --- /dev/null +++ b/public/motionity/src/assets/slide-left.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/slide-right.svg b/public/motionity/src/assets/slide-right.svg new file mode 100644 index 000000000..33d63b6a8 --- /dev/null +++ b/public/motionity/src/assets/slide-right.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/slide-top.svg b/public/motionity/src/assets/slide-top.svg new file mode 100644 index 000000000..c966d3cea --- /dev/null +++ b/public/motionity/src/assets/slide-top.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/space.png b/public/motionity/src/assets/space.png new file mode 100644 index 000000000..2a897c92a Binary files /dev/null and b/public/motionity/src/assets/space.png differ diff --git a/public/motionity/src/assets/sponsor.svg b/public/motionity/src/assets/sponsor.svg new file mode 100644 index 000000000..10ba2c2cb --- /dev/null +++ b/public/motionity/src/assets/sponsor.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/star.svg b/public/motionity/src/assets/star.svg new file mode 100644 index 000000000..080a2d531 --- /dev/null +++ b/public/motionity/src/assets/star.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/street.png b/public/motionity/src/assets/street.png new file mode 100644 index 000000000..1cd7890b9 Binary files /dev/null and b/public/motionity/src/assets/street.png differ diff --git a/public/motionity/src/assets/strike-active.svg b/public/motionity/src/assets/strike-active.svg new file mode 100644 index 000000000..7c4a2c1dc --- /dev/null +++ b/public/motionity/src/assets/strike-active.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/strike.svg b/public/motionity/src/assets/strike.svg new file mode 100644 index 000000000..7d5a0fd64 --- /dev/null +++ b/public/motionity/src/assets/strike.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/summer.png b/public/motionity/src/assets/summer.png new file mode 100644 index 000000000..d1fb84749 Binary files /dev/null and b/public/motionity/src/assets/summer.png differ diff --git a/public/motionity/src/assets/tempload.svg b/public/motionity/src/assets/tempload.svg new file mode 100644 index 000000000..b477648f7 --- /dev/null +++ b/public/motionity/src/assets/tempload.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/text-active.svg b/public/motionity/src/assets/text-active.svg new file mode 100644 index 000000000..3be093d85 --- /dev/null +++ b/public/motionity/src/assets/text-active.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/text.svg b/public/motionity/src/assets/text.svg new file mode 100644 index 000000000..526232565 --- /dev/null +++ b/public/motionity/src/assets/text.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/thingy.svg b/public/motionity/src/assets/thingy.svg new file mode 100644 index 000000000..3e345ea9b --- /dev/null +++ b/public/motionity/src/assets/thingy.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/timeline-big.svg b/public/motionity/src/assets/timeline-big.svg new file mode 100644 index 000000000..d10cb3fbe --- /dev/null +++ b/public/motionity/src/assets/timeline-big.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/timeline-small.svg b/public/motionity/src/assets/timeline-small.svg new file mode 100644 index 000000000..31ba8575c --- /dev/null +++ b/public/motionity/src/assets/timeline-small.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/tlcrop.svg b/public/motionity/src/assets/tlcrop.svg new file mode 100644 index 000000000..423d60094 --- /dev/null +++ b/public/motionity/src/assets/tlcrop.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/transparent.png b/public/motionity/src/assets/transparent.png new file mode 100644 index 000000000..bd72208a1 Binary files /dev/null and b/public/motionity/src/assets/transparent.png differ diff --git a/public/motionity/src/assets/travel.png b/public/motionity/src/assets/travel.png new file mode 100644 index 000000000..c5c34bc81 Binary files /dev/null and b/public/motionity/src/assets/travel.png differ diff --git a/public/motionity/src/assets/trcrop.svg b/public/motionity/src/assets/trcrop.svg new file mode 100644 index 000000000..d6ff30d3f --- /dev/null +++ b/public/motionity/src/assets/trcrop.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/twemojis/bomb-emoji.png b/public/motionity/src/assets/twemojis/bomb-emoji.png new file mode 100644 index 000000000..b0be2778e Binary files /dev/null and b/public/motionity/src/assets/twemojis/bomb-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/cat-face-emoji.png b/public/motionity/src/assets/twemojis/cat-face-emoji.png new file mode 100644 index 000000000..ca4bc9036 Binary files /dev/null and b/public/motionity/src/assets/twemojis/cat-face-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/clap-emoji.png b/public/motionity/src/assets/twemojis/clap-emoji.png new file mode 100644 index 000000000..a1cc7e0b4 Binary files /dev/null and b/public/motionity/src/assets/twemojis/clap-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/clock-emoji.png b/public/motionity/src/assets/twemojis/clock-emoji.png new file mode 100644 index 000000000..c9e164313 Binary files /dev/null and b/public/motionity/src/assets/twemojis/clock-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/construction-emoji.png b/public/motionity/src/assets/twemojis/construction-emoji.png new file mode 100644 index 000000000..431a46f4e Binary files /dev/null and b/public/motionity/src/assets/twemojis/construction-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/crying-emoji.png b/public/motionity/src/assets/twemojis/crying-emoji.png new file mode 100644 index 000000000..cbc4c72a4 Binary files /dev/null and b/public/motionity/src/assets/twemojis/crying-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/dog-face-emoji.png b/public/motionity/src/assets/twemojis/dog-face-emoji.png new file mode 100644 index 000000000..1c784e7d6 Binary files /dev/null and b/public/motionity/src/assets/twemojis/dog-face-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/eyes-emoji.png b/public/motionity/src/assets/twemojis/eyes-emoji.png new file mode 100644 index 000000000..ccf9feedb Binary files /dev/null and b/public/motionity/src/assets/twemojis/eyes-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/fire-emoji.png b/public/motionity/src/assets/twemojis/fire-emoji.png new file mode 100644 index 000000000..e65793d3f Binary files /dev/null and b/public/motionity/src/assets/twemojis/fire-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/gem-emoji.png b/public/motionity/src/assets/twemojis/gem-emoji.png new file mode 100644 index 000000000..96ef12965 Binary files /dev/null and b/public/motionity/src/assets/twemojis/gem-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/ghost-emoji.png b/public/motionity/src/assets/twemojis/ghost-emoji.png new file mode 100644 index 000000000..595d5e375 Binary files /dev/null and b/public/motionity/src/assets/twemojis/ghost-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/gift-emoji.png b/public/motionity/src/assets/twemojis/gift-emoji.png new file mode 100644 index 000000000..ef45d9b30 Binary files /dev/null and b/public/motionity/src/assets/twemojis/gift-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/graph-emoji.png b/public/motionity/src/assets/twemojis/graph-emoji.png new file mode 100644 index 000000000..fc1f669d4 Binary files /dev/null and b/public/motionity/src/assets/twemojis/graph-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/heart-eyes-emoji.png b/public/motionity/src/assets/twemojis/heart-eyes-emoji.png new file mode 100644 index 000000000..95c0bb625 Binary files /dev/null and b/public/motionity/src/assets/twemojis/heart-eyes-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/heart-kiss-emoji.png b/public/motionity/src/assets/twemojis/heart-kiss-emoji.png new file mode 100644 index 000000000..d58605a82 Binary files /dev/null and b/public/motionity/src/assets/twemojis/heart-kiss-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/hundred-100-points-emoji.png b/public/motionity/src/assets/twemojis/hundred-100-points-emoji.png new file mode 100644 index 000000000..f348802ab Binary files /dev/null and b/public/motionity/src/assets/twemojis/hundred-100-points-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/laughing-emoji.png b/public/motionity/src/assets/twemojis/laughing-emoji.png new file mode 100644 index 000000000..9b2e006c8 Binary files /dev/null and b/public/motionity/src/assets/twemojis/laughing-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/mindblown-emoji.png b/public/motionity/src/assets/twemojis/mindblown-emoji.png new file mode 100644 index 000000000..ef3d65265 Binary files /dev/null and b/public/motionity/src/assets/twemojis/mindblown-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/money-emoji.png b/public/motionity/src/assets/twemojis/money-emoji.png new file mode 100644 index 000000000..f9fc3da38 Binary files /dev/null and b/public/motionity/src/assets/twemojis/money-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/moon-emoji.png b/public/motionity/src/assets/twemojis/moon-emoji.png new file mode 100644 index 000000000..5f8da25ee Binary files /dev/null and b/public/motionity/src/assets/twemojis/moon-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/nail-polish-emoji.png b/public/motionity/src/assets/twemojis/nail-polish-emoji.png new file mode 100644 index 000000000..89c223951 Binary files /dev/null and b/public/motionity/src/assets/twemojis/nail-polish-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/party-popper-emoji.png b/public/motionity/src/assets/twemojis/party-popper-emoji.png new file mode 100644 index 000000000..803f92801 Binary files /dev/null and b/public/motionity/src/assets/twemojis/party-popper-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/pencil-emoji.png b/public/motionity/src/assets/twemojis/pencil-emoji.png new file mode 100644 index 000000000..fec1b9992 Binary files /dev/null and b/public/motionity/src/assets/twemojis/pencil-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/pizza-emoji.png b/public/motionity/src/assets/twemojis/pizza-emoji.png new file mode 100644 index 000000000..431e21e0d Binary files /dev/null and b/public/motionity/src/assets/twemojis/pizza-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/plane-emoji.png b/public/motionity/src/assets/twemojis/plane-emoji.png new file mode 100644 index 000000000..9e1eaf997 Binary files /dev/null and b/public/motionity/src/assets/twemojis/plane-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/pleading-face-emoji.png b/public/motionity/src/assets/twemojis/pleading-face-emoji.png new file mode 100644 index 000000000..0160f423b Binary files /dev/null and b/public/motionity/src/assets/twemojis/pleading-face-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/point-emoji.png b/public/motionity/src/assets/twemojis/point-emoji.png new file mode 100644 index 000000000..68e04124e Binary files /dev/null and b/public/motionity/src/assets/twemojis/point-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/praying-hands-emoji.png b/public/motionity/src/assets/twemojis/praying-hands-emoji.png new file mode 100644 index 000000000..0c7195b6c Binary files /dev/null and b/public/motionity/src/assets/twemojis/praying-hands-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/raising-hands-emoji.png b/public/motionity/src/assets/twemojis/raising-hands-emoji.png new file mode 100644 index 000000000..f26f151dc Binary files /dev/null and b/public/motionity/src/assets/twemojis/raising-hands-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/rocket-emoji.png b/public/motionity/src/assets/twemojis/rocket-emoji.png new file mode 100644 index 000000000..9365bceb3 Binary files /dev/null and b/public/motionity/src/assets/twemojis/rocket-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/rose-emoji.png b/public/motionity/src/assets/twemojis/rose-emoji.png new file mode 100644 index 000000000..260abf31d Binary files /dev/null and b/public/motionity/src/assets/twemojis/rose-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/skull-emoji.png b/public/motionity/src/assets/twemojis/skull-emoji.png new file mode 100644 index 000000000..e80e2ae19 Binary files /dev/null and b/public/motionity/src/assets/twemojis/skull-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/smiling-emoji.png b/public/motionity/src/assets/twemojis/smiling-emoji.png new file mode 100644 index 000000000..d68993c9a Binary files /dev/null and b/public/motionity/src/assets/twemojis/smiling-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/sparkles-emoji.png b/public/motionity/src/assets/twemojis/sparkles-emoji.png new file mode 100644 index 000000000..9f4d33073 Binary files /dev/null and b/public/motionity/src/assets/twemojis/sparkles-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/star-emoji.png b/public/motionity/src/assets/twemojis/star-emoji.png new file mode 100644 index 000000000..0e01f3f79 Binary files /dev/null and b/public/motionity/src/assets/twemojis/star-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/sun-emoji.png b/public/motionity/src/assets/twemojis/sun-emoji.png new file mode 100644 index 000000000..74458f8bf Binary files /dev/null and b/public/motionity/src/assets/twemojis/sun-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/sunglasses-cool-emoji.png b/public/motionity/src/assets/twemojis/sunglasses-cool-emoji.png new file mode 100644 index 000000000..8ddeaafb1 Binary files /dev/null and b/public/motionity/src/assets/twemojis/sunglasses-cool-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/surprised-emoji.png b/public/motionity/src/assets/twemojis/surprised-emoji.png new file mode 100644 index 000000000..75056e1b6 Binary files /dev/null and b/public/motionity/src/assets/twemojis/surprised-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/target-emoji.png b/public/motionity/src/assets/twemojis/target-emoji.png new file mode 100644 index 000000000..fe967b6da Binary files /dev/null and b/public/motionity/src/assets/twemojis/target-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/thinking-face-emoji.png b/public/motionity/src/assets/twemojis/thinking-face-emoji.png new file mode 100644 index 000000000..0aa0b75d7 Binary files /dev/null and b/public/motionity/src/assets/twemojis/thinking-face-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/thought-balloon-emoji.png b/public/motionity/src/assets/twemojis/thought-balloon-emoji.png new file mode 100644 index 000000000..cc518b006 Binary files /dev/null and b/public/motionity/src/assets/twemojis/thought-balloon-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/thumbs-up-emoji.png b/public/motionity/src/assets/twemojis/thumbs-up-emoji.png new file mode 100644 index 000000000..92d330245 Binary files /dev/null and b/public/motionity/src/assets/twemojis/thumbs-up-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/tongue-emoji.png b/public/motionity/src/assets/twemojis/tongue-emoji.png new file mode 100644 index 000000000..7ba35fcf5 Binary files /dev/null and b/public/motionity/src/assets/twemojis/tongue-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/trophy-emoji.png b/public/motionity/src/assets/twemojis/trophy-emoji.png new file mode 100644 index 000000000..55aac19a6 Binary files /dev/null and b/public/motionity/src/assets/twemojis/trophy-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/tulip-emoji.png b/public/motionity/src/assets/twemojis/tulip-emoji.png new file mode 100644 index 000000000..2f36b692b Binary files /dev/null and b/public/motionity/src/assets/twemojis/tulip-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/wave-emoji.png b/public/motionity/src/assets/twemojis/wave-emoji.png new file mode 100644 index 000000000..6c02c7261 Binary files /dev/null and b/public/motionity/src/assets/twemojis/wave-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/winking-face-emoji.png b/public/motionity/src/assets/twemojis/winking-face-emoji.png new file mode 100644 index 000000000..24b04c3db Binary files /dev/null and b/public/motionity/src/assets/twemojis/winking-face-emoji.png differ diff --git a/public/motionity/src/assets/twemojis/wip-emoji.png b/public/motionity/src/assets/twemojis/wip-emoji.png new file mode 100644 index 000000000..250e6fccf Binary files /dev/null and b/public/motionity/src/assets/twemojis/wip-emoji.png differ diff --git a/public/motionity/src/assets/typewriter.svg b/public/motionity/src/assets/typewriter.svg new file mode 100644 index 000000000..49082b37d --- /dev/null +++ b/public/motionity/src/assets/typewriter.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/motionity/src/assets/underline-active.svg b/public/motionity/src/assets/underline-active.svg new file mode 100644 index 000000000..7cf8bc855 --- /dev/null +++ b/public/motionity/src/assets/underline-active.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/underline.svg b/public/motionity/src/assets/underline.svg new file mode 100644 index 000000000..fc7078b14 --- /dev/null +++ b/public/motionity/src/assets/underline.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/motionity/src/assets/undo.svg b/public/motionity/src/assets/undo.svg new file mode 100644 index 000000000..ffb1d85b7 --- /dev/null +++ b/public/motionity/src/assets/undo.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/public/motionity/src/assets/upload-grey.svg b/public/motionity/src/assets/upload-grey.svg new file mode 100644 index 000000000..db3e5c37a --- /dev/null +++ b/public/motionity/src/assets/upload-grey.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/upload.svg b/public/motionity/src/assets/upload.svg new file mode 100644 index 000000000..eb5cc1ef2 --- /dev/null +++ b/public/motionity/src/assets/upload.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/motionity/src/assets/uploads-active.svg b/public/motionity/src/assets/uploads-active.svg new file mode 100644 index 000000000..2c049aefd --- /dev/null +++ b/public/motionity/src/assets/uploads-active.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/uploads.svg b/public/motionity/src/assets/uploads.svg new file mode 100644 index 000000000..53dfc2a60 --- /dev/null +++ b/public/motionity/src/assets/uploads.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/video-active.svg b/public/motionity/src/assets/video-active.svg new file mode 100644 index 000000000..cf0312c8f --- /dev/null +++ b/public/motionity/src/assets/video-active.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/video.svg b/public/motionity/src/assets/video.svg new file mode 100644 index 000000000..ab13b922f --- /dev/null +++ b/public/motionity/src/assets/video.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/assets/wallpaper.png b/public/motionity/src/assets/wallpaper.png new file mode 100644 index 000000000..0d477bdf4 Binary files /dev/null and b/public/motionity/src/assets/wallpaper.png differ diff --git a/public/motionity/src/assets/work.png b/public/motionity/src/assets/work.png new file mode 100644 index 000000000..83fb0a194 Binary files /dev/null and b/public/motionity/src/assets/work.png differ diff --git a/public/motionity/src/assets/zap.svg b/public/motionity/src/assets/zap.svg new file mode 100644 index 000000000..3f30b5090 --- /dev/null +++ b/public/motionity/src/assets/zap.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/motionity/src/assets/zappy.svg b/public/motionity/src/assets/zappy.svg new file mode 100644 index 000000000..e2b5059fa --- /dev/null +++ b/public/motionity/src/assets/zappy.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/motionity/src/favicon.ico b/public/motionity/src/favicon.ico new file mode 100644 index 000000000..55c1f4211 Binary files /dev/null and b/public/motionity/src/favicon.ico differ diff --git a/public/motionity/src/index.html b/public/motionity/src/index.html new file mode 100644 index 000000000..7c28ffa7f --- /dev/null +++ b/public/motionity/src/index.html @@ -0,0 +1,390 @@ + + + + + + + + + + + + + +Motionity - The web-based motion graphics editor for everyone + + + + + + + + + + + + + + + + + + +
+
+
🤔
+
Motionity isn't optimized for mobile
+
You need to use a computer to be able to create animations with Motionity.
+ Other products by the maker +
+
+
+ + + + + +
+
+
+
Upload media
+ +
+
+
+ +
Click to upload
+
Or drag and drop a file
+
+
+ +
+
+
+
+

Download settings

+

Formats

+
+ + + + + + + + +
+
Download
+
+
+

Import & export

+

Save this project locally, or load an existing one.

+

Import a project

+
Import
+

Export this project

+
Export
+
+
+
+
+
+ +
+

Uploads

+

Objects

+

Images

+

Text

+

Videos

+

Audio

+

More

+
+
+
+
+ Upload Lottie +
+
+ Clear project +
+
+
+
+
+

Objects

Shapes

Emojis

+
+
+
+
+
+
+ + + +
+
+ + + +
+
+
+
+
+

Canvas settings

+ + + + + + + + + + + + + + + + + +
Preset
Size
Color +
+
+ +
+
+
Duration
+
+
+
+
+
+
+
+
+
Filters
+ +
+ +
+
Adjustments
+
Reset
+
+ Brightness + +
+ +
+
+ Contrast + +
+ +
+
+ Saturation + +
+ +
+
+ Vibrance + +
+ +
+
+ Hue + +
+ +
+
+
Chroma key
+
+ Status + +
+
On
+
Off
+
+ +
+
+ Color + +
+
+ +
+ +
+
+ Distance + +
+ +
+
+
Stylize
+
+ Noise + +
+ +
+
+ Blur + +
+ +
+
+
+
+
+
Undo
+
Redo
+
+
+ +
+
100%
+
+
Zoom in
+
Zoom out
+
Zoom to 50%
+
Zoom to 100%
+
Zoom to 200%
+
+
+
+
+ + Made by Alyssa X +
+ + + + +
+
+
+
+
+

Keyframe easing

+ +
+
+
+
+
LAYERS
+
+ +
+
+
+
+
+
+
+
+
+
+
+ +
+
+ +
+ +
+
+
4.0x
+
3.0x
+
2.0x
+
1.5x
+
1.0x
+
0.5x
+
+ 1.0x +
+
+
+ +
+ + + +
+ +
+
+
+
Import & export
+
Download
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/motionity/src/js/align.js b/public/motionity/src/js/align.js new file mode 100644 index 000000000..c59eaa6f2 --- /dev/null +++ b/public/motionity/src/js/align.js @@ -0,0 +1,371 @@ +// Center line reference +function initLines() { + if (canvas.getItemById('center_h')) { + canvas.remove(canvas.getItemById('center_h')); + canvas.remove(canvas.getItemById('center_v')); + } + if (canvas.getItemById('line_h')) { + canvas.remove(canvas.getItemById('line_h')); + canvas.remove(canvas.getItemById('line_v')); + } + + // Canvas center reference + canvas.add( + new fabric.Line( + [ + canvas.get('width') / 2, + 0, + canvas.get('width') / 2, + canvas.get('height'), + ], + { + opacity: 0, + selectable: false, + evented: false, + id: 'center_h', + } + ) + ); + canvas.add( + new fabric.Line( + [ + 0, + canvas.get('height') / 2, + canvas.get('width'), + canvas.get('height') / 2, + ], + { + opacity: 0, + selectable: false, + evented: false, + id: 'center_v', + } + ) + ); + + // Canvas alignemnt guides + line_h = new fabric.Line( + [ + canvas.get('width') / 2, + artboard.get('top'), + canvas.get('width') / 2, + artboard.get('height') + artboard.get('top'), + ], + { + stroke: 'red', + opacity: 0, + selectable: false, + evented: false, + id: 'line_h', + } + ); + line_v = new fabric.Line( + [ + artboard.get('left'), + canvas.get('height') / 2, + artboard.get('width') + artboard.get('left'), + canvas.get('height') / 2, + ], + { + stroke: 'red', + opacity: 0, + selectable: false, + evented: false, + id: 'line_v', + } + ); + canvas.add(line_h); + canvas.add(line_v); +} + +function alignControls(object, type) { + if (type == 'align-top') { + object.set( + 'top', + artboard.get('top') + + (object.get('height') * object.get('scaleY')) / 2 + ); + } else if (type == 'align-center-v') { + object.set( + 'top', + artboard.get('top') + artboard.get('height') / 2 + ); + } else if (type == 'align-bottom') { + object.set( + 'top', + artboard.get('top') + + artboard.get('height') - + (object.get('height') * object.get('scaleY')) / 2 + ); + } else if (type == 'align-left') { + object.set( + 'left', + artboard.get('left') + + (object.get('width') * object.get('scaleX')) / 2 + ); + } else if (type == 'align-center-h') { + object.set( + 'left', + artboard.get('left') + artboard.get('width') / 2 + ); + } else { + object.set( + 'left', + artboard.get('left') + + artboard.get('width') - + (object.get('width') * object.get('scaleX')) / 2 + ); + } +} + +// Align object +function alignObject() { + const type = $(this).attr('id'); + const object = canvas.getActiveObject(); + console.log(canvas.getActiveObject().type); + if (canvas.getActiveObject().type == 'activeSelection') { + const tempselection = canvas.getActiveObject(); + canvas.discardActiveObject(); + tempselection._objects.forEach(function (object) { + alignControls(object, type); + canvas.renderAll(); + newKeyframe( + 'left', + object, + currenttime, + object.get('left'), + true + ); + newKeyframe( + 'top', + object, + currenttime, + object.get('top'), + true + ); + }); + reselect(tempselection); + } else { + alignControls(object, type); + canvas.renderAll(); + newKeyframe( + 'left', + object, + currenttime, + object.get('left'), + true + ); + newKeyframe('top', object, currenttime, object.get('top'), true); + } +} +$(document).on('click', '.align', alignObject); + +// Alignment guides +function centerLines(e) { + if (!cropping) { + line_h.opacity = 0; + line_v.opacity = 0; + canvas.renderAll(); + const snapZone = 5; + const obj_left = e.target.left; + const obj_top = e.target.top; + const obj_width = e.target.get('width') * e.target.get('scaleX'); + const obj_height = + e.target.get('height') * e.target.get('scaleY'); + canvas.forEachObject(function (obj, index, array) { + // Check for horizontal snapping + function checkHSnap(a, b, snapZone, e, type) { + if (a > b - snapZone && a < b + snapZone) { + line_h.opacity = 1; + line_h.bringToFront(); + var value = b; + if (type == 1) { + value = b; + } else if (type == 2) { + value = + b - + (e.target.get('width') * e.target.get('scaleX')) / 2; + } else if (type == 3) { + value = + b + + (e.target.get('width') * e.target.get('scaleX')) / 2; + } + e.target + .set({ + left: value, + }) + .setCoords(); + line_h + .set({ + x1: b, + y1: artboard.get('top'), + x2: b, + y2: artboard.get('height') + artboard.get('top'), + }) + .setCoords(); + canvas.renderAll(); + } + } + + // Check for vertical snapping + function checkVSnap(a, b, snapZone, e, type) { + if (a > b - snapZone && a < b + snapZone) { + line_v.opacity = 1; + line_v.bringToFront(); + var value = b; + if (type == 1) { + value = b; + } else if (type == 2) { + value = + b - + (e.target.get('height') * e.target.get('scaleY')) / 2; + } else if (type == 3) { + value = + b + + (e.target.get('height') * e.target.get('scaleY')) / 2; + } + e.target + .set({ + top: value, + }) + .setCoords(); + line_v + .set({ + y1: b, + x1: artboard.get('left'), + y2: b, + x2: artboard.get('width') + artboard.get('left'), + }) + .setCoords(); + canvas.renderAll(); + } + } + if (obj != e.target && obj != line_h && obj != line_v) { + if ( + obj.get('id') == 'center_h' || + obj.get('id') == 'center_v' + ) { + var check1 = [[obj_left, obj.get('left'), 1]]; + var check2 = [[obj_top, obj.get('top'), 1]]; + + for (var i = 0; i < check1.length; i++) { + checkHSnap( + check1[i][0], + check1[i][1], + snapZone, + e, + check1[i][2] + ); + checkVSnap( + check2[i][0], + check2[i][1], + snapZone, + e, + check2[i][2] + ); + } + } else { + var check1 = [ + [obj_left, obj.get('left'), 1], + [ + obj_left, + obj.get('left') + + (obj.get('width') * obj.get('scaleX')) / 2, + 1, + ], + [ + obj_left, + obj.get('left') - + (obj.get('width') * obj.get('scaleX')) / 2, + 1, + ], + [obj_left + obj_width / 2, obj.get('left'), 2], + [ + obj_left + obj_width / 2, + obj.get('left') + + (obj.get('width') * obj.get('scaleX')) / 2, + 2, + ], + [ + obj_left + obj_width / 2, + obj.get('left') - + (obj.get('width') * obj.get('scaleX')) / 2, + 2, + ], + [obj_left - obj_width / 2, obj.get('left'), 3], + [ + obj_left - obj_width / 2, + obj.get('left') + + (obj.get('width') * obj.get('scaleX')) / 2, + 3, + ], + [ + obj_left - obj_width / 2, + obj.get('left') - + (obj.get('width') * obj.get('scaleX')) / 2, + 3, + ], + ]; + var check2 = [ + [obj_top, obj.get('top'), 1], + [ + obj_top, + obj.get('top') + + (obj.get('height') * obj.get('scaleY')) / 2, + 1, + ], + [ + obj_top, + obj.get('top') - + (obj.get('height') * obj.get('scaleY')) / 2, + 1, + ], + [obj_top + obj_height / 2, obj.get('top'), 2], + [ + obj_top + obj_height / 2, + obj.get('top') + + (obj.get('height') * obj.get('scaleY')) / 2, + 2, + ], + [ + obj_top + obj_height / 2, + obj.get('top') - + (obj.get('height') * obj.get('scaleY')) / 2, + 2, + ], + [obj_top - obj_height / 2, obj.get('top'), 3], + [ + obj_top - obj_height / 2, + obj.get('top') + + (obj.get('height') * obj.get('scaleY')) / 2, + 3, + ], + [ + obj_top - obj_height / 2, + obj.get('top') - + (obj.get('height') * obj.get('scaleY')) / 2, + 3, + ], + ]; + + for (var i = 0; i < check1.length; i++) { + checkHSnap( + check1[i][0], + check1[i][1], + snapZone, + e, + check1[i][2] + ); + checkVSnap( + check2[i][0], + check2[i][1], + snapZone, + e, + check2[i][2] + ); + } + } + } + }); + } +} diff --git a/public/motionity/src/js/converter.js b/public/motionity/src/js/converter.js new file mode 100644 index 000000000..fc766db0f --- /dev/null +++ b/public/motionity/src/js/converter.js @@ -0,0 +1,118 @@ +var workerPath = + 'https://archive.org/download/ffmpeg_asm/ffmpeg_asm.js'; + +function processInWebWorker() { + var blob = URL.createObjectURL( + new Blob( + [ + 'importScripts("' + + workerPath + + '");var now = Date.now;function print(text) {postMessage({"type" : "stdout","data" : text});};onmessage = function(event) {var message = event.data;if (message.type === "command") {var Module = {print: print,printErr: print,files: message.files || [],arguments: message.arguments || [],TOTAL_MEMORY: message.TOTAL_MEMORY||536870912 || false};postMessage({"type" : "start","data" : Module.arguments.join(" ")});postMessage({"type" : "stdout","data" : "Received command: " +Module.arguments.join(" ") +((Module.TOTAL_MEMORY ) ? ". Processing with " + Module.TOTAL_MEMORY + " bits." : "")});var time = now();var result = ffmpeg_run(Module);var totalTime = now() - time;postMessage({"type" : "stdout","data" : "Finished processing (took " + totalTime + "ms)"});postMessage({"type" : "done","data" : result,"time" : totalTime});}};postMessage({"type" : "ready"});', + ], + { + type: 'application/javascript', + } + ) + ); + + var worker = new Worker(blob); + URL.revokeObjectURL(blob); + return worker; +} + +var worker; + +function convertStreams(videoBlob, setting) { + var aab; + var buffersReady; + var workerReady; + var posted; + + var fileReader = new FileReader(); + fileReader.onload = function () { + aab = this.result; + postMessage(); + }; + fileReader.readAsArrayBuffer(videoBlob); + + if (!worker) { + worker = processInWebWorker(); + } + worker.onmessage = function (event) { + var message = event.data; + if (message.type == 'ready') { + workerReady = true; + if (buffersReady) postMessage(); + } else if (message.type == 'done') { + var result = message.data[0]; + if (setting == 'gif') { + var blob = new File([result.data], 'test.gif', { + type: 'image/gif', + }); + PostBlob(blob); + } else if (setting == 'mp4') { + var blob = new File([result.data], 'test.mp4', { + type: 'video/mp4', + }); + PostBlob(blob); + } + } + }; + var postMessage = function () { + posted = true; + if (setting == 'gif') { + worker.postMessage({ + type: 'command', + arguments: '-i video.webm -r 24 output-10.gif'.split(' '), + files: [ + { + data: new Uint8Array(aab), + name: 'video.webm', + }, + ], + }); + } else if (setting == 'mp4') { + worker.postMessage({ + type: 'command', + arguments: + '-i video.webm -c:v mpeg4 -b:v 6400k -strict experimental output.mp4'.split( + ' ' + ), + files: [ + { + data: new Uint8Array(aab), + name: 'video.webm', + }, + ], + }); + } + }; +} + +function PostBlob(blob) { + var url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.style.display = 'none'; + a.href = url; + a.download = name; + document.body.appendChild(a); + a.click(); + recording = false; + currenttime = 0; + animate(false, 0); + $('#seekbar').offset({ + left: + offset_left + + $('#inner-timeline').offset().left + + currenttime / timelinetime, + }); + canvas.renderAll(); + resizeCanvas(); + if (background_audio != false) { + background_audio.pause(); + background_audio = new Audio(background_audio.src); + } + $('#download-real').html('Download'); + $('#download-real').removeClass('downloading'); + updateRecordCanvas(); +} diff --git a/public/motionity/src/js/database.js b/public/motionity/src/js/database.js new file mode 100644 index 000000000..c36ac33ea --- /dev/null +++ b/public/motionity/src/js/database.js @@ -0,0 +1,660 @@ +// For debugging purposes +db.config.debug = false; + +// Check if a project exists +function checkDB() { + db.collection('projects') + .get() + .then((project) => { + if (project.length == 0) { + canvas.clipPath = null; + const inst = canvas.toDatalessJSON([ + 'volume', + 'audioSrc', + 'defaultLeft', + 'defaultTop', + 'defaultScaleX', + 'defaultScaleY', + 'notnew', + 'starttime', + 'top', + 'left', + 'width', + 'height', + 'scaleX', + 'scaleY', + 'flipX', + 'flipY', + 'originX', + 'originY', + 'transformMatrix', + 'stroke', + 'strokeWidth', + 'strokeDashArray', + 'strokeLineCap', + 'strokeDashOffset', + 'strokeLineJoin', + 'strokeMiterLimit', + 'angle', + 'opacity', + 'fill', + 'globalCompositeOperation', + 'shadow', + 'clipTo', + 'visible', + 'backgroundColor', + 'skewX', + 'skewY', + 'fillRule', + 'paintFirst', + 'strokeUniform', + 'rx', + 'ry', + 'selectable', + 'hasControls', + 'subTargetCheck', + 'id', + 'hoverCursor', + 'defaultCursor', + 'filesrc', + 'isEditing', + 'source', + 'assetType', + 'duration', + 'inGroup', + 'filters', + ]); + canvas.clipPath = artboard; + db.collection('projects').add({ + id: 1, + canvas: JSON.stringify(inst), + keyframes: JSON.stringify(keyframes.slice()), + p_keyframes: JSON.stringify(p_keyframes.slice()), + objects: JSON.stringify(objects.slice()), + colormode: colormode, + speed: speed, + duration: duration, + currenttime: currenttime, + layercount: layer_count, + width: artboard.width, + height: artboard.height, + animatedtext: JSON.stringify(animatedtext), + groups: JSON.stringify(groups), + files: JSON.stringify(files), + activepreset: activepreset, + }); + checkstatus = true; + getAssets(); + } else { + loadProject(); + } + }); +} + +// Automatically save project (locally) +function autoSave() { + if (checkstatus) { + canvas.clipPath = null; + objects.forEach(async function (object) { + var obj = canvas.getItemById(object.id); + if (obj.filters) { + if (obj.filters.length > 0) { + object.filters = []; + obj.filters.forEach(function (filter) { + if ( + filter.type == 'BlackWhite' || + filter.type == 'Invert' || + filter.type == 'Sepia' || + filter.type == 'Kodachrome' || + filter.type == 'Polaroid' || + filter.type == 'Technicolor' || + filter.type == 'Brownie' || + filter.type == 'Vintage' + ) { + object.filters.push({ type: filter.type }); + } else if (filter.type == 'Brightness') { + object.filters.push({ + type: filter.type, + value: filter.brightness, + }); + } else if (filter.type == 'Contrast') { + object.filters.push({ + type: filter.type, + value: filter.contrast, + }); + } else if (filter.type == 'Vibrance') { + object.filters.push({ + type: filter.type, + value: filter.vibrance, + }); + } else if (filter.type == 'Saturation') { + object.filters.push({ + type: filter.type, + value: filter.saturation, + }); + } else if (filter.type == 'HueRotation') { + object.filters.push({ + type: filter.type, + value: filter.rotation, + }); + } else if (filter.type == 'Blur') { + object.filters.push({ + type: filter.type, + value: filter.blur, + }); + } else if (filter.type == 'Noise') { + object.filters.push({ + type: filter.type, + value: filter.noise, + }); + } else if (filter.type == 'RemoveColor') { + object.filters.push({ + type: filter.type, + distance: filter.distance, + color: filter.color, + }); + } + }); + obj.filters = []; + obj.applyFilters(); + var backend = fabric.filterBackend; + if (backend && backend.evictCachesForKey) { + backend.evictCachesForKey(obj.cacheKey); + backend.evictCachesForKey(obj.cacheKey + '_filtered'); + } + if ( + obj.filters.length > 0 && + obj.get('id').indexOf('Video') >= 0 + ) { + await obj.setElement(obj.saveElem); + } + } else { + object.filters = []; + } + } else { + object.filters = []; + } + }); + const inst = canvas.toDatalessJSON([ + 'volume', + 'audioSrc', + 'defaultLeft', + 'defaultTop', + 'defaultScaleX', + 'defaultScaleY', + 'notnew', + 'starttime', + 'top', + 'left', + 'width', + 'height', + 'scaleX', + 'scaleY', + 'flipX', + 'flipY', + 'originX', + 'originY', + 'transformMatrix', + 'stroke', + 'strokeWidth', + 'strokeDashArray', + 'strokeLineCap', + 'strokeDashOffset', + 'strokeLineJoin', + 'strokeMiterLimit', + 'angle', + 'opacity', + 'fill', + 'globalCompositeOperation', + 'shadow', + 'clipTo', + 'visible', + 'backgroundColor', + 'skewX', + 'skewY', + 'fillRule', + 'paintFirst', + 'strokeUniform', + 'rx', + 'ry', + 'selectable', + 'hasControls', + 'subTargetCheck', + 'id', + 'hoverCursor', + 'defaultCursor', + 'filesrc', + 'isEditing', + 'source', + 'assetType', + 'duration', + 'inGroup', + ]); + canvas.clipPath = artboard; + db.collection('projects') + .doc({ id: 1 }) + .update({ + canvas: JSON.stringify(inst), + keyframes: JSON.stringify(keyframes.slice()), + p_keyframes: JSON.stringify(p_keyframes.slice()), + objects: JSON.stringify(objects.slice()), + colormode: colormode, + duration: duration, + currenttime: currenttime, + layercount: layer_count, + speed: speed, + audiosrc: background_key, + animatedtext: JSON.stringify(animatedtext), + files: JSON.stringify(files), + groups: JSON.stringify(groups), + activepreset: activepreset, + width: artboard.width, + height: artboard.height, + }); + objects.forEach(function (object) { + replaceSource(canvas.getItemById(object.id), canvas); + }); + } +} + +var isSameSet = function (arr1, arr2) { + return ( + $(arr1).not(arr2).length === 0 && $(arr2).not(arr1).length === 0 + ); +}; + +function loadProject() { + db.collection('projects') + .doc({ id: 1 }) + .get() + .then((document) => { + var project = document; + keyframes = JSON.parse(project.keyframes); + p_keyframes = JSON.parse(project.p_keyframes); + objects = JSON.parse(project.objects); + files = JSON.parse(project.files); + colormode = project.colormode; + duration = project.duration; + layer_count = project.layercount; + speed = project.speed; + animatedtext = JSON.parse(project.animatedtext); + animatedtext.forEach(function (text, index) { + var temp = new AnimatedText(text.text, text.props); + temp.assignTo(text.id); + animatedtext[index] = temp; + }); + $('#speed span').html(speed.toFixed(1) + 'x'); + groups = JSON.parse(project.groups); + activepreset = project.activepreset; + currenttime = 0; + canvas.clipPath = null; + canvas.clear(); + fabric.filterBackend = webglBackend; + f = fabric.Image.filters; + canvas.loadFromJSON(JSON.parse(project.canvas), function () { + canvas.clipPath = artboard; + canvas.getItemById('line_h').set({ opacity: 0 }); + canvas.getItemById('line_v').set({ opacity: 0 }); + canvas.renderAll(); + $('.object-props').remove(); + $('.layer').remove(); + objects.forEach(function (object) { + var animatethis = false; + if (object.animate.length > 5) { + if (isSameSet(object.animate, props)) { + animatethis = true; + } + } + renderLayer(canvas.getItemById(object.id), animatethis); + if ( + !canvas.getItemById(object.id).get('assetType') || + canvas.getItemById(object.id).get('assetType') != 'audio' + ) { + props.forEach(function (prop) { + if ( + prop != 'top' && + prop != 'scaleY' && + prop != 'width' && + prop != 'height' && + prop != 'shadow.offsetX' && + prop != 'shadow.offsetY' && + prop != 'shadow.opacity' && + prop != 'shadow.blur' && + prop != 'lineHeight' + ) { + renderProp(prop, canvas.getItemById(object.id)); + } + }); + replaceSource(canvas.getItemById(object.id), canvas); + } else { + renderProp('volume', canvas.getItemById(object.id)); + } + }); + keyframes.forEach(function (keyframe) { + if ( + keyframe.name != 'top' && + keyframe.name != 'scaleY' && + keyframe.name != 'width' && + keyframe.name != 'height' && + keyframe.name != 'shadow.offsetX' && + keyframe.name != 'shadow.offsetY' && + keyframe.name != 'shadow.opacity' && + keyframe.name != 'shadow.blur' && + keyframe.name != 'lineHeight' + ) { + renderKeyframe( + canvas.getItemById(keyframe.id), + keyframe.name, + keyframe.t + ); + } + }); + artboard.set({ + width: project.width, + height: project.height, + }); + canvas.renderAll(); + resizeCanvas(); + updatePanel(); + + animatedtext.forEach(function (text, index) { + text.reset(text.text, text.props, canvas); + canvas.renderAll(); + }); + + // Set defaults + setDuration(duration); + setTimelineZoom(5); + checkstatus = true; + + getAssets(); + + canvas.renderAll(); + + animate(false, 0); + + //newLottieAnimation(100,100); + }); + }); +} + +function blobToBase64(blob) { + return new Promise((resolve, _) => { + const reader = new FileReader(); + reader.onloadend = () => resolve(reader.result); + reader.readAsDataURL(blob); + }); +} + +async function saveFile(thumbnail, file, type, name, place, hidden) { + file = await blobToBase64(file); + thumbnail = await blobToBase64(thumbnail); + uploading = false; + var key = Math.random().toString(36).substr(2, 9); + db.collection('assets').add({ + key: key, + src: file, + thumb: thumbnail, + name: name, + type: type, + hidden: hidden, + }); + if (type === 'image') { + uploaded_images.push({ + src: file, + thumb: thumbnail, + key: key, + type: 'image', + hidden: false, + }); + populateGrid('images-tab'); + } else if (type === 'video') { + uploaded_videos.push({ + src: file, + thumb: thumbnail, + key: key, + type: 'video', + hidden: false, + }); + populateGrid('videos-tab'); + } + $('#upload-button').html( + " Upload media" + ); + $('#upload-button').removeClass('uploading'); + if (place) { + loadImage( + file, + artboard.get('left') + artboard.get('width') / 2, + artboard.get('top') + artboard.get('height') / 2, + 200 + ); + } + save(); +} + +async function savePixabayImage(url, xpos, ypos, width) { + $('#load-image').addClass('loading-active'); + fetch(url) + .then((res) => res.blob()) + .then((blob) => { + url = blob; + var reader = new FileReader(); + reader.readAsDataURL(blob); + reader.onloadend = function () { + url = reader.result; + var key = Math.random().toString(36).substr(2, 9); + db.collection('assets').add({ + key: key, + src: url, + thumb: url, + name: 'test', + type: 'image', + hidden: true, + }); + loadImage(url, xpos, ypos, width, false); + }; + }); +} + +async function saveAudio(url) { + var reader = new FileReader(); + reader.readAsDataURL(url); + reader.onloadend = function () { + var key = Math.random().toString(36).substr(2, 9); + db.collection('assets').add({ + key: key, + src: reader.result, + name: 'test', + type: 'audio', + hidden: true, + }); + newAudioLayer(reader.result); + }; +} + +async function savePixabayVideo(url, thumb, x, y) { + $('#load-video').addClass('loading-active'); + fetch(url) + .then((res) => res.blob()) + .then((blob) => { + var reader = new FileReader(); + reader.readAsDataURL(blob); + reader.onloadend = function () { + fetch(thumb) + .then((res) => res.blob()) + .then((blob2) => { + var reader2 = new FileReader(); + reader2.readAsDataURL(blob2); + reader2.onloadend = function () { + url = reader.result; + thumb = reader2.result; + var key = Math.random().toString(36).substr(2, 9); + db.collection('assets').add({ + key: key, + src: url, + thumb: thumb, + name: 'test', + type: 'video', + hidden: true, + }); + loadVideo(url, x, y, false); + }; + }); + }; + }); +} + +function deleteAsset(key) { + db.collection('assets') + .doc({ key: key }) + .get() + .then((asset) => { + var temp = files.filter((x) => x.file == asset.src); + if (temp.length > 0) { + temp.forEach(function (file) { + deleteObject(canvas.getItemById(file.name)); + files = $.grep(files, function (a) { + return a != file; + }); + }); + } + db.collection('assets').doc({ key: key }).delete(); + if (asset.type == 'image') { + uploaded_images = uploaded_images.filter(function (obj) { + return obj.key !== key; + }); + populateGrid('images-tab'); + } else { + uploaded_videos = uploaded_videos.filter(function (obj) { + return obj.key !== key; + }); + populateGrid('videos-tab'); + } + }); +} + +function getAssets() { + db.collection('assets') + .get() + .then((assets) => { + // Sometimes the assets aren't ready when importing, really annoying + if (assets === undefined) { + getAssets(); + } else if (assets.length > 0) { + assets.forEach(function (asset) { + if (asset.type == 'image') { + uploaded_images.push({ + src: asset.src, + thumb: asset.thumb, + key: asset.key, + type: 'image', + hidden: asset.hidden, + }); + } else if (asset.type == 'video') { + uploaded_videos.push({ + src: asset.src, + thumb: asset.thumb, + key: asset.key, + type: 'video', + hidden: asset.hidden, + }); + } + }); + } + }); +} + +function readTextFile(file, callback) { + var rawFile = new XMLHttpRequest(); + rawFile.overrideMimeType('application/json'); + rawFile.open('GET', file, true); + rawFile.onreadystatechange = function () { + if (rawFile.readyState === 4 && rawFile.status == '200') { + callback(rawFile.responseText); + } + }; + rawFile.send(null); +} + +async function importProject(e) { + $('#import-project span').html('Importing...'); + var file = e.target.files[0]; + var path = (window.URL || window.webkitURL).createObjectURL(file); + readTextFile(path, function (text) { + var data = JSON.parse(text); + delete data.project[0].id; + if (data.project.length > 0) { + if (data.assets.length > 0) { + data.assets.forEach(function (asset) { + delete asset.id; + db.collection('assets').add(asset); + }); + } + db.collection('projects') + .doc({ id: 1 }) + .update(data.project[0]) + .then((response) => { + $('#import-project span').html('Import'); + hideModals(); + loadProject(); + }); + } else { + alert('Wrong file type'); + } + }); +} + +function importHandle() { + $('#import').click(); +} + +function exportProject() { + $('#export-project span').html('Exporting...'); + db.collection('projects') + .get() + .then((project) => { + if (project.length > 0) { + db.collection('assets') + .get() + .then((assets) => { + var exportarr = { project: project, assets: assets }; + $('', { + download: 'data.json', + href: + 'data:application/json,' + + encodeURIComponent(JSON.stringify(exportarr)), + }) + .appendTo('body') + .click(function () { + $(this).remove(); + $('#export-project span').html('Export'); + })[0] + .click(); + }); + } else { + alert('Empty project'); + $('#export-project span').html('Export'); + } + }); +} + +$(document).on('click', '#import-project', importHandle); +$(document).on('click', '#export-project', exportProject); +$(document).on('change', '#import', importProject); + +function clearProject() { + if ( + window.confirm( + 'Are you sure you want to clear this project? This action cannot be undone.' + ) + ) { + db.collection('projects').delete(); + db.collection('assets').delete(); + window.setTimeout(function () { + location.reload(); + }, 1000); + } + hideMore(); +} +$(document).on('click', '#clear-project', clearProject); diff --git a/public/motionity/src/js/encode-worker.js b/public/motionity/src/js/encode-worker.js new file mode 100644 index 000000000..bcee815cc --- /dev/null +++ b/public/motionity/src/js/encode-worker.js @@ -0,0 +1,96 @@ +importScripts('./webm-writer2.js'); + +let webmWriter = null; +let fileWritableStream = null; +let frameReader = null; + +async function startRecording( + fileHandle, + frameStream, + trackSettings +) { + let frameCounter = 0; + + fileWritableStream = await fileHandle.createWritable(); + + webmWriter = new WebMWriter({ + fileWriter: fileWritableStream, + codec: 'VP9', + width: trackSettings.width, + height: trackSettings.height, + }); + + frameReader = frameStream.getReader(); + + const init = { + output: (chunk) => { + webmWriter.addFrame(chunk); + }, + error: (e) => { + console.log(e.message); + stopRecording(); + }, + }; + + const config = { + codec: 'vp09.00.10.08', + width: trackSettings.width, + height: trackSettings.height, + bitrate: 10e6, + }; + + let encoder = new VideoEncoder(init); + let support = await VideoEncoder.isConfigSupported(config); + console.assert(support.supported); + encoder.configure(config); + + frameReader + .read() + .then(async function processFrame({ done, value }) { + let frame = value; + + if (done) { + await encoder.flush(); + encoder.close(); + return; + } + + if (encoder.encodeQueueSize <= 30) { + if (++frameCounter % 20 == 0) { + console.log(frameCounter + ' frames processed'); + } + + const insert_keyframe = frameCounter % 150 == 0; + encoder.encode(frame, { keyFrame: insert_keyframe }); + } else { + console.log('dropping frame, encoder falling behind'); + } + + frame.close(); + frameReader.read().then(processFrame); + }); +} + +async function stopRecording() { + await frameReader.cancel(); + await webmWriter.complete(); + fileWritableStream.close(); + frameReader = null; + webmWriter = null; + fileWritableStream = null; +} + +self.addEventListener('message', function (e) { + switch (e.data.type) { + case 'start': + startRecording( + e.data.fileHandle, + e.data.frameStream, + e.data.trackSettings + ); + break; + case 'stop': + stopRecording(); + break; + } +}); diff --git a/public/motionity/src/js/events.js b/public/motionity/src/js/events.js new file mode 100644 index 000000000..8dbed5639 --- /dev/null +++ b/public/motionity/src/js/events.js @@ -0,0 +1,1022 @@ +$(document).ready(function () { + // An object is being moved in the canvas + canvas.on('object:moving', function (e) { + e.target.hasControls = false; + centerLines(e); + if (cropping) { + if ( + canvas.getItemById('crop').isContainedWithinObject(cropobj) + ) { + cropleft = canvas.getItemById('crop').get('left'); + croptop = canvas.getItemById('crop').get('top'); + cropscalex = canvas.getItemById('crop').get('scaleX'); + cropscaley = canvas.getItemById('crop').get('scaleY'); + } + crop(canvas.getItemById('cropped')); + } else if ( + lockmovement && + e.e.shiftKey && + canvas.getActiveObject() + ) { + if (canvasx < shiftx + 30 && canvasx > shiftx - 30) { + canvas.getActiveObject().set({ left: shiftx }); + canvas.getActiveObject().lockMovementX = true; + canvas.getActiveObject().lockMovementY = false; + } else { + canvas.getActiveObject().set({ top: shifty }); + canvas.getActiveObject().lockMovementX = false; + canvas.getActiveObject().lockMovementY = true; + } + } else if (canvas.getActiveObject() && !e.e.shiftKey) { + lockmovement = false; + canvas.getActiveObject().lockMovementX = false; + canvas.getActiveObject().lockMovementY = false; + } + }); + + // An object is being scaled in the canvas + canvas.on('object:scaling', function (e) { + e.target.hasControls = false; + centerLines(e); + if (cropping) { + if ( + canvas.getItemById('crop').isContainedWithinObject(cropobj) + ) { + cropleft = canvas.getItemById('crop').get('left'); + croptop = canvas.getItemById('crop').get('top'); + cropscalex = canvas.getItemById('crop').get('scaleX'); + cropscaley = canvas.getItemById('crop').get('scaleY'); + } + crop(canvas.getItemById('cropped')); + } + }); + + // An object is being resized in the canvas + canvas.on('object:resizing', function (e) { + e.target.hasControls = false; + centerLines(e); + if (cropping) { + if ( + canvas.getItemById('crop').isContainedWithinObject(cropobj) + ) { + cropleft = canvas.getItemById('crop').get('left'); + croptop = canvas.getItemById('crop').get('top'); + cropscalex = canvas.getItemById('crop').get('scaleX'); + cropscaley = canvas.getItemById('crop').get('scaleY'); + } + crop(canvas.getItemById('cropped')); + } + }); + + // An object is being rotated in the canvas + canvas.on('object:rotating', function (e) { + if (e.e.shiftKey) { + canvas.getActiveObject().snapAngle = 15; + } else { + canvas.getActiveObject().snapAngle = 0; + } + e.target.hasControls = false; + }); + + // An object has been modified in the canvas + canvas.on('object:modified', function (e) { + e.target.hasControls = true; + if (!editinggroup && !cropping) { + canvas.getActiveObject().lockMovementX = false; + canvas.getActiveObject().lockMovementY = false; + canvas.renderAll(); + if (e.target.type == 'activeSelection') { + const tempselection = canvas.getActiveObject(); + canvas.discardActiveObject(); + e.target._objects.forEach(function (object) { + autoKeyframe(object, e, true); + }); + reselect(tempselection); + } else { + autoKeyframe(e.target, e, false); + } + updatePanelValues(); + save(); + } + if (cropping) { + var obj = e.target; + checkCrop(obj); + } + }); + + // A selection has been updated in the canvas + canvas.on('selection:updated', function (e) { + updatePanel(true); + updatePanelValues(); + updateSelection(e); + closeFilters(); + }); + + // A selection has been made in the canvas + canvas.on('selection:created', function (e) { + shiftx = canvas.getActiveObject().get('left'); + shifty = canvas.getActiveObject().get('top'); + if (!editingpanel) { + updatePanel(true); + } + updateSelection(e); + canvas.renderAll(); + closeFilters(); + }); + + // A selection has been cleared in the canvas + canvas.on('selection:cleared', function (e) { + if (!editingpanel && !setting) { + updatePanel(false); + } + $('.layer-selected').removeClass('layer-selected'); + if (cropping) { + crop(cropobj); + } + closeFilters(); + }); + + function kFormatter(num) { + return Math.abs(num) > 999 + ? Math.sign(num) * (Math.abs(num) / 1000).toFixed(1) + 'k' + : Math.sign(num) * Math.abs(num); + } + + // Zoom in/out of the canvas + canvas.on('mouse:wheel', function (opt) { + var delta = opt.e.deltaY; + var zoom = canvas.getZoom(); + zoom *= 0.999 ** delta; + $('#zoom-level span').html( + kFormatter((zoom * 100).toFixed(0)) + '%' + ); + if (zoom > 20) zoom = 20; + if (zoom < 0.01) zoom = 0.01; + canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom); + opt.e.preventDefault(); + opt.e.stopPropagation(); + }); + + // Start panning if space is down or hand tool is enabled + canvas.on('mouse:down', function (opt) { + var e = opt.e; + if (spaceDown || handtool) { + this.isDragging = true; + this.selection = false; + this.lastPosX = e.clientX; + this.lastPosY = e.clientY; + } + if (opt.target) { + opt.target.hasControls = true; + wip = false; + } + }); + + // Pan while dragging mouse + canvas.on('mouse:move', function (opt) { + var pointer = canvas.getPointer(opt.e); + canvasx = pointer.x; + canvasy = pointer.y; + if (this.isDragging) { + var e = opt.e; + var vpt = this.viewportTransform; + vpt[4] += e.clientX - this.lastPosX; + vpt[5] += e.clientY - this.lastPosY; + this.requestRenderAll(); + this.lastPosX = e.clientX; + this.lastPosY = e.clientY; + } + }); + + // Stop panning + canvas.on('mouse:up', function (opt) { + this.setViewportTransform(this.viewportTransform); + this.isDragging = false; + this.selection = true; + line_h.opacity = 0; + line_v.opacity = 0; + }); + + // Detect mouse over canvas (for dragging objects from the library) + canvas.on('mouse:move', function (e) { + overCanvas = true; + if ( + e.target && + !canvas.getActiveObject() && + draggingPanel && + e.target.type == 'image' + ) { + wip = true; + e.target.hasControls = false; + canvas.setActiveObject(e.target); + } + }); + canvas.on('mouse:out', function (e) { + overCanvas = false; + if (wip) { + e.target.hasControls = true; + canvas.discardActiveObject(); + wip = false; + canvas.renderAll(); + } + }); + + // Double click on image to get into cropping mode + fabric.util.addListener( + canvas.upperCanvasEl, + 'dblclick', + function (e) { + var target = canvas.findTarget(e); + if (target) { + if (target.type == 'image') { + cropImage(target); + } + } + } + ); + + // Key event handling + $(document) + .keyup(function (e) { + // Space bar (panning and playback) + if ( + e.keyCode == 32 && + !editinglayer && + !editingproject && + $(e.target)[0].tagName != 'INPUT' + ) { + spacerelease = true; + spaceDown = false; + canvas.defaultCursor = 'default'; + canvas.renderAll(); + if (!spacehold) { + if ( + !( + canvas.getActiveObject() && + canvas.getActiveObject().isEditing + ) + ) { + if (paused) { + play(); + } else { + pause(); + } + } + } else { + if (!handtool) { + $('#hand-tool').removeClass('hand-active'); + $('#hand-tool') + .find('img') + .attr('src', 'assets/hand-tool.svg'); + } + } + spacehold = false; + } + // Delete object/keyframe + if ( + (e.keyCode == 46 || + e.key == 'Delete' || + e.code == 'Delete' || + e.key == 'Backspace') && + !focus && + !editinglayer + ) { + if ( + $('.show-properties').length > 0 || + shiftkeys.length > 0 + ) { + deleteKeyframe(); + } else { + deleteSelection(); + } + } + // Shift key is up (stop locking horizontal/vertical object movement) + if (e.keyCode == 16) { + lockmovement = false; + shiftdown = false; + } + }) + .keydown(function (e) { + // Space bar (panning and playback) + if ( + e.keyCode == 32 && + !editinglayer && + !editingproject && + $(e.target)[0].tagName != 'INPUT' + ) { + spacerelease = false; + spaceDown = true; + canvas.defaultCursor = 'grab'; + canvas.renderAll(); + window.setTimeout(function () { + if (!spacerelease) { + spacehold = true; + if (!handtool) { + $('#hand-tool').addClass('hand-active'); + $('#hand-tool') + .find('img') + .attr('src', 'assets/hand-tool-active.svg'); + } + } + }, 1000); + } + // Redo + if (e.which === 90 && (e.ctrlKey || e.metaKey) && e.shiftKey) { + undoRedo(redo, undo, redoarr, undoarr); + } + // Undo + if (e.which === 90 && (e.ctrlKey || e.metaKey)) { + undoRedo(undo, redo, undoarr, redoarr); + } + // Duplicate object + if (e.which === 68 && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + if (canvas.getActiveObject()) { + clipboard = canvas.getActiveObject(); + copyObject(); + } + } + // Shift key (Lock horizontal/vertical movement for objects) + if (e.shiftKey) { + shiftdown = true; + lockmovement = true; + if (canvas.getActiveObject()) { + shiftx = canvas.getActiveObject().get('left'); + shifty = canvas.getActiveObject().get('top'); + } + } + // Return (save layer name) + if (e.keyCode === 13 && editinglayer) { + saveLayerName(); + } + // Return (save project name) + if (e.keyCode === 13 && editingproject) { + saveProjectName(); + } + // Left arrow key (move object to the left) + if (e.keyCode === 37 && canvas.getActiveObject()) { + var obj = canvas.getActiveObject(); + var step = 2; + // Bigger step if shift is down + if (e.shiftKey) { + step = 7; + } + obj.left = obj.left - step; + canvas.renderAll(); + autoKeyframe(obj, { action: 'drag' }, false); + } + // Up arrow key (move object up) + if (e.keyCode === 38 && canvas.getActiveObject()) { + var obj = canvas.getActiveObject(); + var step = 2; + // Bigger step if shift is down + if (e.shiftKey) { + step = 7; + } + obj.top = obj.top - step; + canvas.renderAll(); + autoKeyframe(obj, { action: 'drag' }, false); + } + // Right arrow key (move object to the right) + if (e.keyCode === 39 && canvas.getActiveObject()) { + var obj = canvas.getActiveObject(); + var step = 2; + // Bigger step if shift is down + if (e.shiftKey) { + step = 7; + } + obj.left = obj.left + step; + canvas.renderAll(); + autoKeyframe(obj, { action: 'drag' }, false); + } + // Down arrow key (move object down) + if (e.keyCode === 40 && canvas.getActiveObject()) { + var obj = canvas.getActiveObject(); + var step = 2; + // Bigger step if shift is down + if (e.shiftKey) { + step = 7; + } + obj.top = obj.top + step; + canvas.renderAll(); + autoKeyframe(obj, { action: 'drag' }, false); + } + + // Move object up layer list + if ( + e.keyCode === 221 && + canvas.getActiveObjects() && + e.metaKey + ) { + if (canvas.getActiveObjects().length == 1) { + var obj = canvas.getActiveObject(); + $(".layer[data-object='" + obj.id + "']") + .prev() + .insertAfter($(".layer[data-object='" + obj.id + "']")); + $('#' + obj.id) + .prev() + .insertAfter($('#' + obj.id)); + orderLayers(); + } else { + canvas.getActiveObjects().forEach(function (obj) { + $(".layer[data-object='" + obj.id + "']") + .prev() + .insertAfter($(".layer[data-object='" + obj.id + "']")); + $('#' + obj.id) + .prev() + .insertAfter($('#' + obj.id)); + orderLayers(); + }); + } + } + + // Move object down layer list + if ( + e.keyCode === 219 && + canvas.getActiveObjects() && + e.metaKey + ) { + if (canvas.getActiveObjects().length == 1) { + var obj = canvas.getActiveObject(); + $(".layer[data-object='" + obj.id + "']") + .next() + .insertBefore($(".layer[data-object='" + obj.id + "']")); + $('#' + obj.id) + .next() + .insertBefore($('#' + obj.id)); + orderLayers(); + } else { + canvas.getActiveObjects().forEach(function (obj) { + $(".layer[data-object='" + obj.id + "']") + .next() + .insertBefore( + $(".layer[data-object='" + obj.id + "']") + ); + $('#' + obj.id) + .next() + .insertBefore($('#' + obj.id)); + orderLayers(); + }); + } + } + + // Move object top of layer list + if ( + e.keyCode === 221 && + canvas.getActiveObjects() && + e.altKey + ) { + if (canvas.getActiveObjects().length == 1) { + var obj = canvas.getActiveObject(); + $('#layer-inner-list').prepend( + $(".layer[data-object='" + obj.id + "']") + ); + $('#inner-timeline').prepend($('#' + obj.id)); + orderLayers(); + } else { + canvas.getActiveObjects().forEach(function (obj) { + $('#layer-inner-list').prepend( + $(".layer[data-object='" + obj.id + "']") + ); + $('#inner-timeline').prepend($('#' + obj.id)); + orderLayers(); + }); + } + } + + // Move object bottom of layer list + if (e.keyCode === 219 && canvas.getActiveObject() && e.altKey) { + if (canvas.getActiveObjects().length == 1) { + var obj = canvas.getActiveObject(); + $('#layer-inner-list').append( + $(".layer[data-object='" + obj.id + "']") + ); + $('#inner-timeline').append($('#' + obj.id)); + orderLayers(); + } else { + canvas.getActiveObjects().forEach(function (obj) { + $('#layer-inner-list').append( + $(".layer[data-object='" + obj.id + "']") + ); + $('#inner-timeline').append($('#' + obj.id)); + orderLayers(); + }); + } + } + + // Zoom in + if (e.keyCode === 187 && e.shiftKey) { + var zoom = canvas.getZoom() + 0.2; + if (zoom > 20) zoom = 20; + if (zoom < 0.01) zoom = 0.01; + canvas.setZoom(1); + canvas.renderAll(); + var vpw = canvas.width / zoom; + var vph = canvas.height / zoom; + var x = artboard.left + artboard.width / 2 - vpw / 2; + var y = artboard.top + artboard.height / 2 - vph / 2; + canvas.absolutePan({ x: x, y: y }); + canvas.setZoom(zoom); + canvas.renderAll(); + $('#zoom-level span').html( + (canvas.getZoom() * 100).toFixed(0) + '%' + ); + } + + // Zoom out + if (e.keyCode === 189 && e.shiftKey) { + var zoom = canvas.getZoom() - 0.2; + if (zoom > 20) zoom = 20; + if (zoom < 0.01) zoom = 0.01; + canvas.setZoom(1); + canvas.renderAll(); + var vpw = canvas.width / zoom; + var vph = canvas.height / zoom; + var x = artboard.left + artboard.width / 2 - vpw / 2; + var y = artboard.top + artboard.height / 2 - vph / 2; + canvas.absolutePan({ x: x, y: y }); + canvas.setZoom(zoom); + canvas.renderAll(); + $('#zoom-level span').html( + (canvas.getZoom() * 100).toFixed(0) + '%' + ); + } + }); + + // Copy event + window.addEventListener('copy', function (e) { + // Copy selected object + if ( + canvas.getActiveObject() && + shiftkeys.length == 0 && + !canvas.getActiveObject().isEditing + ) { + var emptyInp = document.getElementById('emptyInput'); + emptyInp.select(); + emptyInp.focus(); + setTimeout(function () { + document.execCommand('copy'); + }, 0); + clipboard = canvas.getActiveObject(); + cliptype = 'object'; + // Copy selected keyframe(s) + } else if ( + shiftkeys.length > 0 && + !canvas.getActiveObject().isEditing + ) { + var emptyInp = document.getElementById('emptyInput'); + emptyInp.select(); + emptyInp.focus(); + setTimeout(function () { + document.execCommand('copy'); + }, 0); + clipboard = []; + shiftkeys.forEach(function (keyframe) { + var drag = $(keyframe.keyframe); + var keyarr = $.grep(keyframes, function (e) { + return ( + e.t == drag.attr('data-time') && + e.id == drag.attr('data-object') && + e.name == drag.attr('data-property') + ); + }); + clipboard.push(keyarr[0]); + }); + cliptype = 'keyframe'; + } + }); + + // Paste event + window.addEventListener('paste', function (e) { + var imgs = e.clipboardData.items; + if (imgs == undefined) return false; + + // Paste object or keyframe(s) + if (imgs.length == 1 && e.clipboardData.getData('text') == ' ') { + copyObject(); + // Paste external image (by uploading it) + } else { + for (var i = 0; i < imgs.length; i++) { + if (imgs[i].type.indexOf('image') == -1) continue; + var imgObj = imgs[i].getAsFile(); + if (imgObj.size / 1024 / 1024 <= 10) { + createThumbnail(imgObj, 250).then(function (data) { + saveFile( + dataURItoBlob(data), + imgObj, + imgObj['type'].split('/')[0], + 'temp', + true, + true + ); + }); + } else { + alert('Image is too big'); + } + } + } + }); + + // Stop cropping when clicking on the blacked out properties panel + $(document).on('click', '#properties-overlay', function () { + if (cropping) { + canvas.discardActiveObject(); + } + }); + + // Scroll horizontally through assets in the library + $(document).on('click', '.right-arrow', function () { + $(this).parent().animate({ scrollLeft: '+=1000' }, 500); + }); + $(document).on('click', '.left-arrow', function () { + $(this).parent().animate({ scrollLeft: '-=1000' }, 500); + }); + + // Playback + $(document).on('click', '#play-button', function () { + if (paused) { + play(); + } else { + pause(); + } + }); + + // Detect when not clicking on certain elements + $(document).on('mousedown', function (e) { + // De-select keyframes + if ( + !$('#keyframe-properties').is(e.target) && + $('#keyframe-properties').has(e.target).length === 0 && + !$('.keyframe').is(e.target) && + $('.keyframe').has(e.target).length === 0 + ) { + $('#keyframe-properties').removeClass('show-properties'); + $('.keyframe-selected').removeClass('keyframe-selected'); + shiftkeys = []; + } + + // Hide color picker + if ( + !$('.object-color').is(e.target) && + $('.object-color').has(e.target).length === 0 && + !$('.pcr-app').is(e.target) && + $('.prc-app').has(e.target).length === 0 && + !$('.pcr-selection').is(e.target) && + $('.pcr-selection').has(e.target).length === 0 && + !$('.pcr-swatches').is(e.target) && + $('.pcr-swatches').has(e.target).length === 0 && + !$('.pcr-interaction').is(e.target) && + $('.pcr-interaction').has(e.target).length === 0 + ) { + o_fill.hide(); + } + + // Hide zoom controls + if ( + !$('#other-controls').is(e.target) && + $('#other-controls').has(e.target).length === 0 + ) { + $('#zoom-options').addClass('zoom-hidden'); + $('#zoom-level img').removeClass('zoom-open'); + } + + // Hide speed settings + if ( + !$('#speed').is(e.target) && + $('#speed').has(e.target).length === 0 + ) { + $('#speed-settings').removeClass('show-speed'); + $('#speed-arrow').removeClass('arrow-on'); + } + + // Hide more menu + if ( + !$('#more-tool').is(e.target) && + $('#more-tool').has(e.target).length === 0 && + !$('#more-over').is(e.target) && + $('#more-over').has(e.target).length === 0 + ) { + hideMore(); + } + }); + + // Detect focus on an input in the properties + $(document) + .on('focus', '.property-input', function () { + focus = true; + }) + .on('focusout', function () { + focus = false; + }); + + // Toggle zoom dropdown + $(document).on('click', '#zoom-level', function () { + $('#zoom-options').toggleClass('zoom-hidden'); + $('#zoom-level img').toggleClass('zoom-open'); + }); + + // Skip to the beginning or end + $(document).on('click', '#skip-backward', function () { + animate(false, 0); + $('#seekbar').offset({ + left: + offset_left + + $('#inner-timeline').offset().left + + currenttime / timelinetime, + }); + }); + $(document).on('click', '#skip-forward', function () { + animate(false, duration); + $('#seekbar').offset({ + left: + offset_left + + $('#inner-timeline').offset().left + + currenttime / timelinetime, + }); + }); + + // Change layer name + $(document).on('dblclick', '.layer-custom-name', function () { + $(this).prop('readonly', false); + $(this).addClass('name-active'); + $(this).focus(); + document.execCommand('selectAll', false, null); + editinglayer = true; + }); + + // Trigger file picker when clicking the upload button + $(document).on('click', '#upload-button', function () { + $('#upload-popup').addClass('upload-show'); + }); + + $(document).on('click', '#upload-overlay', function () { + $('.upload-show').removeClass('upload-show'); + }); + + $(document).on('click', '#upload-popup-close', function () { + $('.upload-show').removeClass('upload-show'); + }); + + $(document).on('click', '#upload-drop-area', function () { + $('#filepick').click(); + }); + + $(document).on('dragover', function (e) { + e.preventDefault(); + e.stopPropagation(); + }); + + $(document).on('dragover', '#upload-drop-area', function (e) { + e.preventDefault(); + e.stopPropagation(); + $('#upload-drop-area').addClass('dropping'); + }); + + $(document).on('dragenter', '#upload-drop-area', function (e) { + e.preventDefault(); + e.stopPropagation(); + $('#upload-drop-area').addClass('dropping'); + }); + + $(document).on('drop', function (e) { + e.preventDefault(); + e.stopPropagation(); + $('#upload-drop-area').removeClass('dropping'); + handleUpload(e); + }); + + $(document).on('dragleave', function () { + $('#upload-drop-area').removeClass('dropping'); + }); + + $(document).on('dragend', function () { + $('#upload-drop-area').removeClass('dropping'); + }); + + // Upload or remove background audio + $(document).on('click', '#audio-upload-button', function () { + $('#filepick2').click(); + }); + + // Sync scrolling for the timeline + syncScroll($('#layer-inner-list'), $('#timeline')); + syncScrollHoz($('#timeline'), $('#seekarea')); + + // Initialize layer sorting + sortable('#layer-inner-list', { + customDragImage: (draggedElement, elementOffset, event) => { + return { + element: document.getElementById('nothing'), + posX: event.pageX - elementOffset.left, + posY: event.pageY - elementOffset.top, + }; + }, + })[0].addEventListener('sortstop', function (e) { + const id = $(e.detail.item).attr('data-object'); + const previd = $(e.detail.item).prev().attr('data-object'); + if ($('.sortable-dragging').length == 1) { + $('.sortable-dragging').remove(); + if (previd == undefined) { + $('#inner-timeline').prepend($('#' + id)); + } else { + $('#' + id).insertAfter($('#' + previd)); + } + orderLayers(); + } + }); + + // Initialize dropdown for keyframe easing + $('#easing select').niceSelect(); + + // Initialize properties panel + updatePanel(false); + + // Initialize library + updateBrowser('shape-tool'); + + function initFilterSliders() { + var filters = [ + 'filter-brightness', + 'filter-contrast', + 'filter-saturation', + 'filter-hue', + 'filter-vibrance', + ]; + filters.forEach(function (filter) { + var selectme = document.getElementById(filter); + var slider = new RangeSlider(selectme, { + design: '2d', + theme: 'default', + handle: 'round', + popup: null, + showMinMaxLabels: false, + unit: '%', + min: -100, + max: 100, + value: 0, + step: 1, + onmove: function (x) { + if (canvas.getActiveObject()) { + var obj = canvas.getActiveObject(); + if (filter == 'filter-brightness') { + if (obj.filters.find((i) => i.type == 'Brightness')) { + obj.filters.find( + (i) => i.type == 'Brightness' + ).brightness = x / 100; + } else { + obj.filters.push( + new f.Brightness({ brightness: x / 100 }) + ); + } + } else if (filter == 'filter-contrast') { + if (obj.filters.find((i) => i.type == 'Contrast')) { + obj.filters.find( + (i) => i.type == 'Contrast' + ).contrast = x / 100; + } else { + obj.filters.push( + new f.Contrast({ contrast: x / 100 }) + ); + } + } else if (filter == 'filter-saturation') { + if (obj.filters.find((i) => i.type == 'Saturation')) { + obj.filters.find( + (i) => i.type == 'Saturation' + ).saturation = x / 100; + } else { + obj.filters.push( + new f.Saturation({ saturation: x / 100 }) + ); + } + } else if (filter == 'filter-vibrance') { + if (obj.filters.find((i) => i.type == 'Vibrance')) { + obj.filters.find( + (i) => i.type == 'Vibrance' + ).vibrance = x / 100; + } else { + obj.filters.push( + new f.Vibrance({ vibrance: x / 100 }) + ); + } + } else if (filter == 'filter-hue') { + if (obj.filters.find((i) => i.type == 'HueRotation')) { + obj.filters.find( + (i) => i.type == 'HueRotation' + ).rotation = x / 100; + } else { + obj.filters.push( + new f.HueRotation({ rotation: x / 100 }) + ); + } + } + obj.applyFilters(); + canvas.renderAll(); + } + }, + onfinish: function (x) { + save(); + }, + }); + sliders.push({ name: filter, slider: slider }); + }); + } + + var selectchroma = document.getElementById('chroma-distance'); + chromaslider = new RangeSlider(selectchroma, { + design: '2d', + theme: 'default', + handle: 'round', + popup: null, + showMinMaxLabels: false, + unit: '%', + min: 1, + max: 100, + value: 1, + step: 1, + onmove: function (x) { + if (canvas.getActiveObject()) { + var obj = canvas.getActiveObject(); + if (obj.filters.find((x) => x.type == 'RemoveColor')) { + obj.filters.find((x) => x.type == 'RemoveColor').distance = + x / 100; + } + obj.applyFilters(); + canvas.renderAll(); + } + }, + onfinish: function (x) { + save(); + }, + }); + + var selectnoise = document.getElementById('filter-noise'); + noiseslider = new RangeSlider(selectnoise, { + design: '2d', + theme: 'default', + handle: 'round', + popup: null, + showMinMaxLabels: false, + unit: '%', + min: 0, + max: 1000, + value: 0, + step: 1, + onmove: function (x) { + if (canvas.getActiveObject()) { + var obj = canvas.getActiveObject(); + if (obj.filters.find((x) => x.type == 'Noise')) { + obj.filters.find((x) => x.type == 'Noise').noise = x; + } else { + obj.filters.push( + new f.Noise({ + noise: x, + }) + ); + } + obj.applyFilters(); + canvas.renderAll(); + } + }, + onfinish: function (x) { + save(); + }, + }); + + var selectblur = document.getElementById('filter-blur'); + blurslider = new RangeSlider(selectblur, { + design: '2d', + theme: 'default', + handle: 'round', + popup: null, + showMinMaxLabels: false, + unit: '%', + min: 0, + max: 100, + value: 0, + step: 1, + onmove: function (x) { + if (canvas.getActiveObject()) { + var obj = canvas.getActiveObject(); + if (obj.filters.find((x) => x.type == 'Blur')) { + obj.filters.find((x) => x.type == 'Blur').blur = x / 100; + } else { + obj.filters.push( + new f.Blur({ + blur: x / 100, + }) + ); + } + } + obj.applyFilters(); + canvas.renderAll(); + }, + onfinish: function (x) { + save(); + }, + }); + + $('#filters-list').val('none'); + $('#filters-list').niceSelect(); + + initFilterSliders(); +}); diff --git a/public/motionity/src/js/functions.js b/public/motionity/src/js/functions.js new file mode 100644 index 000000000..11ad5ff97 --- /dev/null +++ b/public/motionity/src/js/functions.js @@ -0,0 +1,5971 @@ +// Resize the canvas +function resizeCanvas() { + canvas.discardActiveObject(); + canvas.setHeight($('#canvas-area').height()); + canvas.setWidth($('#canvas-area').width()); + artboard.set({ + left: canvas.get('width') / 2 - artboard.get('width') / 2, + top: canvas.get('height') / 2 - artboard.get('height') / 2, + }); + canvas.renderAll(); + animate(false, currenttime); + initLines(); +} +window.addEventListener('resize', resizeCanvas, false); +resizeCanvas(); + +// Highlight layers when selecting objects in the canvas, scroll into view if needed +function updateSelection(e) { + if (e.target.type == 'activeSelection') { + $('.layer-selected').removeClass('layer-selected'); + canvas.getActiveObjects().forEach(function (object) { + if ( + $('.layer').length > 0 && + $(".layer[data-object='" + object.get('id') + "']").length > 0 + ) { + $(".layer[data-object='" + object.get('id') + "']").addClass( + 'layer-selected' + ); + if (e.e != undefined) { + document + .getElementsByClassName('layer-selected')[0] + .scrollIntoView(); + } + } + }); + } else { + if ( + $('.layer').length > 0 && + $(".layer[data-object='" + e.target.get('id') + "']").length > 0 + ) { + $('.layer-selected').removeClass('layer-selected'); + $(".layer[data-object='" + e.target.get('id') + "']").addClass( + 'layer-selected' + ); + if (e.e != undefined) { + document + .getElementsByClassName('layer-selected')[0] + .scrollIntoView(); + } + } + } +} + +// Object has been modified, automatically add a keyframe +function autoKeyframe(object, e, multi) { + if (e.action == 'drag') { + newKeyframe( + 'left', + object, + currenttime, + object.get('left'), + true + ); + newKeyframe('top', object, currenttime, object.get('top'), true); + } else if (e.action == 'scale') { + newKeyframe( + 'scaleX', + object, + currenttime, + object.get('scaleX'), + true + ); + newKeyframe( + 'scaleY', + object, + currenttime, + object.get('scaleY'), + true + ); + newKeyframe( + 'left', + object, + currenttime, + object.get('left'), + true + ); + newKeyframe('top', object, currenttime, object.get('top'), true); + newKeyframe( + 'width', + object, + currenttime, + object.get('width'), + true + ); + newKeyframe( + 'height', + object, + currenttime, + object.get('height'), + true + ); + } else if (e.action == 'rotate') { + newKeyframe( + 'angle', + object, + currenttime, + object.get('angle'), + true + ); + if (multi) { + newKeyframe( + 'scaleX', + object, + currenttime, + object.get('scaleX'), + true + ); + newKeyframe( + 'scaleY', + object, + currenttime, + object.get('scaleY'), + true + ); + newKeyframe( + 'width', + object, + currenttime, + object.get('width'), + true + ); + newKeyframe( + 'left', + object, + currenttime, + object.get('left'), + true + ); + newKeyframe( + 'top', + object, + currenttime, + object.get('top'), + true + ); + } + } else if ( + e.action == 'resizing' || + e.action == 'scaleX' || + e.action == 'scaleY' + ) { + newKeyframe( + 'scaleX', + object, + currenttime, + object.get('scaleX'), + true + ); + newKeyframe( + 'scaleY', + object, + currenttime, + object.get('scaleY'), + true + ); + newKeyframe( + 'left', + object, + currenttime, + object.get('left'), + true + ); + newKeyframe( + 'width', + object, + currenttime, + object.get('width'), + true + ); + newKeyframe('top', object, currenttime, object.get('top'), true); + newKeyframe( + 'height', + object, + currenttime, + object.get('height'), + true + ); + } +} + +// Reselect +function reselect(selection) { + tempselection = false; + if (selection.type == 'activeSelection') { + var objs = []; + for (let so of selection._objects) { + for (let obj of canvas.getObjects()) { + if (obj.get('id') === so.get('id')) { + objs.push(obj); + break; + } + } + } + canvas.setActiveObject( + new fabric.ActiveSelection(objs, { + canvas: canvas, + }) + ); + canvas.renderAll(); + } else { + if (selection.get('type') == 'group') { + canvas.setActiveObject(canvas.getItemById(selection.get('id'))); + } else { + canvas.setActiveObject(selection); + } + canvas.renderAll(); + } +} + +// Group objects +function group() { + var objects = canvas.getActiveObjects(); + var object_ids = []; + var newgroup = new fabric.Group(); + objects.forEach(function (object) { + newgroup.addWithUpdate(object); + object.set({ inGroup: true }); + $(".layer[data-object='" + object.get('id') + "']").remove(); + object_ids.push(object.get('id')); + $('#' + object.get('id')).remove(); + canvas.remove(object); + }); + //var newgroup = canvas.getActiveObject().toGroup(); + newgroup.set({ + id: 'Group' + layer_count, + objectCaching: false, + isGroup: true, + color: '#F1890E', + type: 'group', + stroke: '#000', + strokeUniform: true, + strokeWidth: 0, + paintFirst: 'stroke', + absolutePositioned: true, + inGroup: false, + strokeDashArray: false, + objectCaching: true, + shadow: { + color: 'black', + offsetX: 0, + offsetY: 0, + blur: 0, + opacity: 0, + }, + }); + groups.push({ id: newgroup.get('id'), objects: object_ids }); + canvas.renderAll(); + newLayer(newgroup); + canvas.setActiveObject(newgroup); + keyframes.sort(function (a, b) { + if (a.id.indexOf('Group') >= 0 && b.id.indexOf('Group') == -1) { + return 1; + } else if ( + b.id.indexOf('Group') >= 0 && + a.id.indexOf('Group') == -1 + ) { + return -1; + } else { + return 0; + } + }); + save(); +} +$(document).on('click', '#group-objects', group); + +// Ungroup SVG +function unGroup(group) { + canvas.discardActiveObject(); + canvas.renderAll(); + tempgroup = group._objects; + group._restoreObjectsState(); + $(".layer[data-object='" + group.get('id') + "']").remove(); + $('#' + group.get('id')).remove(); + canvas.remove(group); + keyframes = $.grep(keyframes, function (e) { + return e.id != group.get('id'); + }); + p_keyframes = $.grep(p_keyframes, function (e) { + return e.id != group.get('id'); + }); + objects = $.grep(objects, function (e) { + return e.id != group.get('id'); + }); + canvas.renderAll(); + for (var i = 0; i < tempgroup.length; i++) { + if (tempgroup[i].inGroup) { + canvas.add(tempgroup[i]); + renderLayer(tempgroup[i]); + props.forEach(function (prop) { + if ( + prop != 'top' && + prop != 'scaleY' && + prop != 'width' && + prop != 'height' && + prop != 'shadow.offsetX' && + prop != 'shadow.offsetY' && + prop != 'shadow.opacity' && + prop != 'shadow.blur' && + prop != 'lineHeight' + ) { + renderProp(prop, tempgroup[i]); + } + }); + const keyarr = $.grep(keyframes, function (e) { + return e.id == tempgroup[i].id; + }); + keyarr.forEach(function (keyframe) { + if ( + keyframe.name != 'top' && + keyframe.name != 'scaleY' && + keyframe.name != 'width' && + keyframe.name != 'height' && + keyframe.name != 'shadow.offsetX' && + keyframe.name != 'shadow.offsetY' && + keyframe.name != 'shadow.opacity' && + keyframe.name != 'shadow.blur' && + keyframe.name != 'lineHeight' + ) { + renderKeyframe( + canvas.getItemById(keyframe.id), + keyframe.name, + keyframe.t + ); + } + }); + } + } + canvas.renderAll(); + save(); +} +$(document).on('click', '#ungroup-objects', function () { + if (canvas.getActiveObject()) { + unGroup(canvas.getActiveObject()); + } +}); + +// Regroup SVG +function reGroup(id) { + var group = []; + var objects = []; + groups + .find((x) => x.id == id) + .objects.forEach(function (object) { + objects.push(canvas.getItemById(object)); + }); + var activeselection = new fabric.ActiveSelection(objects); + var newgroup = activeselection.toGroup(); + newgroup.set({ + id: id, + objectCaching: false, + }); + canvas.add(newgroup); + canvas.renderAll(); +} + +// Keep record canvas up to date +function updateRecordCanvas() { + canvasrecord.setWidth(artboard.width); + canvasrecord.setHeight(artboard.height); + canvasrecord.width = artboard.width; + canvasrecord.height = artboard.height; + canvas.clipPath = null; + objects.forEach(async function (object) { + var obj = canvas.getItemById(object.id); + if (obj.filters) { + if (obj.filters.length > 0) { + object.filters = []; + obj.filters.forEach(function (filter) { + if ( + filter.type == 'BlackWhite' || + filter.type == 'Invert' || + filter.type == 'Sepia' || + filter.type == 'Kodachrome' || + filter.type == 'Polaroid' || + filter.type == 'Technicolor' || + filter.type == 'Brownie' || + filter.type == 'Vintage' + ) { + object.filters.push({ type: filter.type }); + } else if (filter.type == 'Brightness') { + object.filters.push({ + type: filter.type, + value: filter.brightness, + }); + } else if (filter.type == 'Contrast') { + object.filters.push({ + type: filter.type, + value: filter.contrast, + }); + } else if (filter.type == 'Vibrance') { + object.filters.push({ + type: filter.type, + value: filter.vibrance, + }); + } else if (filter.type == 'Saturation') { + object.filters.push({ + type: filter.type, + value: filter.saturation, + }); + } else if (filter.type == 'HueRotation') { + object.filters.push({ + type: filter.type, + value: filter.rotation, + }); + } else if (filter.type == 'Blur') { + object.filters.push({ + type: filter.type, + value: filter.blur, + }); + } else if (filter.type == 'Noise') { + object.filters.push({ + type: filter.type, + value: filter.noise, + }); + } else if (filter.type == 'RemoveColor') { + object.filters.push({ + type: filter.type, + distance: filter.distance, + color: filter.color, + }); + } + }); + obj.filters = []; + obj.applyFilters(); + var backend = fabric.filterBackend; + if (backend && backend.evictCachesForKey) { + backend.evictCachesForKey(obj.cacheKey); + backend.evictCachesForKey(obj.cacheKey + '_filtered'); + } + if ( + obj.filters.length > 0 && + obj.get('id').indexOf('Video') >= 0 + ) { + await obj.setElement(obj.saveElem); + } + } else { + object.filters = []; + } + } else { + object.filters = []; + } + }); + const canvassave = canvas.toJSON([ + 'volume', + 'audioSrc', + 'defaultLeft', + 'defaultTop', + 'defaultScaleX', + 'defaultScaleY', + 'notnew', + 'starttime', + 'top', + 'left', + 'width', + 'height', + 'scaleX', + 'scaleY', + 'flipX', + 'flipY', + 'originX', + 'originY', + 'transformMatrix', + 'stroke', + 'strokeWidth', + 'strokeDashArray', + 'strokeLineCap', + 'strokeDashOffset', + 'strokeLineJoin', + 'strokeMiterLimit', + 'angle', + 'opacity', + 'fill', + 'globalCompositeOperation', + 'shadow', + 'clipTo', + 'visible', + 'backgroundColor', + 'skewX', + 'skewY', + 'fillRule', + 'paintFirst', + 'clipPath', + 'strokeUniform', + 'rx', + 'ry', + 'selectable', + 'hasControls', + 'subTargetCheck', + 'id', + 'hoverCursor', + 'defaultCursor', + 'isEditing', + 'source', + 'assetType', + 'duration', + 'inGroup', + ]); + canvas.clipPath = artboard; + canvasrecord.loadFromJSON(canvassave, function () { + if (canvasrecord.getItemById('center_h')) { + canvasrecord.remove(canvasrecord.getItemById('center_h')); + canvasrecord.remove(canvasrecord.getItemById('center_v')); + } + if (canvasrecord.getItemById('line_h')) { + canvasrecord.remove(canvasrecord.getItemById('line_h')); + canvasrecord.remove(canvasrecord.getItemById('line_v')); + } + canvasrecord.renderAll(); + canvasrecord.setWidth(artboard.width); + canvasrecord.setHeight(artboard.height); + canvasrecord.width = artboard.width; + canvasrecord.height = artboard.height; + canvasrecord.renderAll(); + objects.forEach(function (object) { + replaceSource( + canvasrecord.getItemById(object.id), + canvasrecord + ); + replaceSource(canvas.getItemById(object.id), canvas); + }); + }); +} + +// Download recording +function downloadRecording(chunks) { + $('#download-real').html('Downloading...'); + if ($('input[name=radio]:checked').val() == 'webm') { + var url = URL.createObjectURL( + new Blob(chunks, { + type: 'video/webm', + }) + ); + const a = document.createElement('a'); + a.style.display = 'none'; + a.href = url; + a.download = name; + document.body.appendChild(a); + a.click(); + recording = false; + currenttime = 0; + animate(false, 0); + $('#seekbar').offset({ + left: + offset_left + + $('#inner-timeline').offset().left + + currenttime / timelinetime, + }); + canvas.renderAll(); + resizeCanvas(); + $('#download-real').html('Download'); + $('#download-real').removeClass('downloading'); + updateRecordCanvas(); + } else if ($('input[name=radio]:checked').val() == 'mp4') { + type = 'video/mp4'; + } else { + convertStreams(new Blob(chunks, { type: 'video/webm' }), 'gif'); + } +} + +$('#download-real').on('click', record); + +// Save everything in the canvas (for undo/redo/autosave) +function save() { + redo = []; + redoarr = []; + if (state) { + undo.push(state); + undoarr.push(statearr); + } + canvas.clipPath = null; + state = canvas.toJSON([ + 'volume', + 'audioSrc', + 'top', + 'left', + 'width', + 'height', + 'scaleX', + 'scaleY', + 'flipX', + 'flipY', + 'originX', + 'originY', + 'transformMatrix', + 'stroke', + 'strokeWidth', + 'strokeDashArray', + 'strokeLineCap', + 'strokeDashOffset', + 'strokeLineJoin', + 'strokeMiterLimit', + 'angle', + 'opacity', + 'fill', + 'globalCompositeOperation', + 'shadow', + 'clipTo', + 'visible', + 'backgroundColor', + 'skewX', + 'skewY', + 'fillRule', + 'paintFirst', + 'clipPath', + 'strokeUniform', + 'rx', + 'ry', + 'selectable', + 'hasControls', + 'subTargetCheck', + 'id', + 'hoverCursor', + 'defaultCursor', + 'isEditing', + 'source', + 'assetType', + 'duration', + 'inGroup', + 'filters', + ]); + canvas.clipPath = artboard; + statearr = { + keyframes: JSON.parse(JSON.stringify(keyframes)), + p_keyframes: JSON.parse(JSON.stringify(p_keyframes)), + objects: JSON.parse(JSON.stringify(objects)), + colormode: colormode, + duration: duration, + currenttime: currenttime, + }; + if (undo.length >= 1) { + $('#undo').addClass('history-active'); + } else { + $('#undo').removeClass('history-active'); + } + if (redo.length >= 1) { + $('#redo').addClass('history-active'); + } else { + $('#redo').removeClass('history-active'); + } + + updateRecordCanvas(); + autoSave(); +} + +// Duplicate object +function copyObject() { + if (clipboard) { + if (cliptype == 'object') { + if (clipboard.type == 'activeSelection') { + clipboard._objects.forEach(function (clone) { + clone.clone(function (cloned) { + cloned.set({ + id: 'Shape' + layer_count, + }); + canvas.add(cloned); + canvas.renderAll(); + newLayer(cloned); + canvas.setActiveObject(cloned); + }); + }); + } else { + clipboard.clone(function (cloned) { + cloned.set({ + id: 'Shape' + layer_count, + }); + canvas.add(cloned); + canvas.renderAll(); + newLayer(cloned); + canvas.setActiveObject(cloned); + }); + } + save(); + } else { + copyKeyframes(); + } + } +} + +// Replace the source of an object when reloading the canvas (since Fabric needs a DOM reference for the objects) +function replaceSource(object, canvas) { + if (object == null) { + return false; + } + if (object.get('type') != 'group') { + if (object.type) { + if (object.type == 'image') { + if (object.get('id').indexOf('Video') >= 0) { + var vidObj = document.createElement('video'); + var vidSrc = document.createElement('source'); + vidSrc.src = object.get('source'); + vidObj.crossOrigin = 'anonymous'; + vidObj.appendChild(vidSrc); + vidObj.addEventListener('loadeddata', function () { + vidObj.width = this.videoWidth; + vidObj.height = this.videoHeight; + vidObj.currentTime = 0; + vidObj.muted = false; + async function waitLoad() { + if (vidObj.readyState >= 3) { + object.setElement(vidObj); + object.saveElem = vidObj; + await canvas.renderAll(); + await animate(false, currenttime); + if ( + objects.find((x) => x.id == object.get('id')) + .filters + ) { + if ( + objects.find((x) => x.id == object.get('id')) + .filters.length > 0 + ) { + objects + .find((x) => x.id == object.get('id')) + .filters.forEach(function (filter) { + if (filter.type == 'Sepia') { + object.filters.push(new f.Sepia()); + } else if (filter.type == 'Invert') { + object.filters.push(new f.Invert()); + } else if (filter.type == 'BlackWhite') { + object.filters.push(new f.BlackWhite()); + } else if (filter.type == 'Kodachrome') { + object.filters.push(new f.Kodachrome()); + } else if (filter.type == 'Polaroid') { + object.filters.push(new f.Polaroid()); + } else if (filter.type == 'Technicolor') { + object.filters.push(new f.Technicolor()); + } else if (filter.type == 'Vintage') { + object.filters.push(new f.Vintage()); + } else if (filter.type == 'Brownie') { + object.filters.push(new f.Brownie()); + } else if (filter.type == 'Brightness') { + object.filters.push( + new f.Brightness({ + brightness: filter.value, + }) + ); + } else if (filter.type == 'Contrast') { + object.filters.push( + new f.Contrast({ contrast: filter.value }) + ); + } else if (filter.type == 'Saturation') { + object.filters.push( + new f.Saturation({ + saturation: filter.value, + }) + ); + } else if (filter.type == 'Vibrance') { + object.filters.push( + new f.Vibrance({ vibrance: filter.value }) + ); + } else if (filter.type == 'HueRotation') { + object.filters.push( + new f.HueRotation({ + rotation: filter.value, + }) + ); + } else if (filter.type == 'Noise') { + object.filters.push( + new f.Noise({ noise: filter.value }) + ); + } else if (filter.type == 'Blur') { + object.filters.push( + new f.Blur({ blur: filter.value }) + ); + } else if (filter.type == 'RemoveColor') { + object.filters.push( + new f.RemoveColor({ + distance: filter.distance, + color: filter.color, + }) + ); + } + }); + object.applyFilters(); + canvas.renderAll(); + } + } + } else { + window.setTimeout(function () { + waitLoad(); + }, 100); + } + } + window.setTimeout(function () { + waitLoad(); + }, 100); + }); + vidObj.currentTime = 0; + } else { + //var img = new Image(); + //img.onload = function(){ + // object.setElement(img); + // canvas.renderAll(); + if (objects.find((x) => x.id == object.get('id')).filters) { + if ( + objects.find((x) => x.id == object.get('id')).filters + .length > 0 + ) { + objects + .find((x) => x.id == object.get('id')) + .filters.forEach(function (filter) { + if (filter.type == 'Sepia') { + object.filters.push(new f.Sepia()); + } else if (filter.type == 'Invert') { + object.filters.push(new f.Invert()); + } else if (filter.type == 'BlackWhite') { + object.filters.push(new f.BlackWhite()); + } else if (filter.type == 'Kodachrome') { + object.filters.push(new f.Kodachrome()); + } else if (filter.type == 'Polaroid') { + object.filters.push(new f.Polaroid()); + } else if (filter.type == 'Technicolor') { + object.filters.push(new f.Technicolor()); + } else if (filter.type == 'Vintage') { + object.filters.push(new f.Vintage()); + } else if (filter.type == 'Brownie') { + object.filters.push(new f.Brownie()); + } else if (filter.type == 'Brightness') { + object.filters.push( + new f.Brightness({ brightness: filter.value }) + ); + } else if (filter.type == 'Contrast') { + object.filters.push( + new f.Contrast({ contrast: filter.value }) + ); + } else if (filter.type == 'Saturation') { + object.filters.push( + new f.Saturation({ saturation: filter.value }) + ); + } else if (filter.type == 'Vibrance') { + object.filters.push( + new f.Vibrance({ vibrance: filter.value }) + ); + } else if (filter.type == 'HueRotation') { + object.filters.push( + new f.HueRotation({ rotation: filter.value }) + ); + } else if (filter.type == 'Noise') { + object.filters.push( + new f.Noise({ noise: filter.value }) + ); + } else if (filter.type == 'Blur') { + object.filters.push( + new f.Blur({ blur: filter.value }) + ); + } else if (filter.type == 'RemoveColor') { + object.filters.push( + new f.RemoveColor({ + distance: filter.distance, + color: filter.color, + }) + ); + } + }); + object.applyFilters(); + canvas.renderAll(); + } else { + object.filters = []; + object.applyFilters(); + canvas.renderAll(); + } + } + + //} + //img.src = window.URL.createObjectURL(new Blob(files.find(x => x.name == object.get("id")).file, {type:"image/png"})); + } + } + } + } +} + +// Perform undo/redo +function undoRedo(newState, saveState, newArrState, saveArrState) { + saveState.push(state); + saveArrState.push(statearr); + statearr = newArrState.pop(); + state = newState.pop(); + keyframes = statearr.keyframes; + p_keyframes = statearr.p_keyframes; + objects = statearr.objects; + colormode = statearr.colormode; + duration = statearr.duration; + currenttime = statearr.currenttime; + canvas.clipPath = null; + canvas.loadFromJSON(state, function () { + canvas.clipPath = artboard; + canvas.getItemById('line_h').set({ opacity: 0 }); + canvas.getItemById('line_v').set({ opacity: 0 }); + canvas.renderAll(); + $('.object-props').remove(); + $('.layer').remove(); + objects.forEach(function (object) { + replaceSource(canvas.getItemById(object.id), canvas); + renderLayer(canvas.getItemById(object.id)); + props.forEach(function (prop) { + if ( + prop != 'top' && + prop != 'scaleY' && + prop != 'width' && + prop != 'height' && + prop != 'shadow.offsetX' && + prop != 'shadow.offsetY' && + prop != 'shadow.opacity' && + prop != 'shadow.blur' && + prop != 'lineHeight' + ) { + renderProp(prop, canvas.getItemById(object.id)); + } + }); + }); + keyframes.forEach(function (keyframe) { + if ( + keyframe.name != 'top' && + keyframe.name != 'scaleY' && + keyframe.name != 'width' && + keyframe.name != 'height' && + keyframe.name != 'shadow.offsetX' && + keyframe.name != 'shadow.offsetY' && + keyframe.name != 'shadow.opacity' && + keyframe.name != 'shadow.blur' && + keyframe.name != 'lineHeight' + ) { + renderKeyframe( + canvas.getItemById(keyframe.id), + keyframe.name, + keyframe.t + ); + } + }); + animate(false, currenttime); + }); + if (undo.length >= 1) { + $('#undo').addClass('history-active'); + } else { + $('#undo').removeClass('history-active'); + } + if (redo.length >= 1) { + $('#redo').addClass('history-active'); + } else { + $('#redo').removeClass('history-active'); + } +} + +// Undo/redo buttons +$(document).on('click', '#undo', function () { + if (undo.length >= 1) { + undoRedo(undo, redo, undoarr, redoarr); + } +}); +$(document).on('click', '#redo', function () { + if (undo.length >= 1) { + undoRedo(redo, undo, redoarr, undoarr); + } +}); + +// Generate keyframes +function keyframeChanges(object, type, id, selection) { + if (object.get('type') == 'rect') { + object.set({ + rx: parseFloat($('#object-corners input').val()), + ry: parseFloat($('#object-corners input').val()), + }); + } else if (object.get('type') == 'textbox') { + object.set({ + charSpacing: parseFloat($('#text-h input').val()) * 10, + lineHeight: parseFloat($('#text-v input').val() / 100), + }); + canvas.renderAll(); + } + canvas.renderAll(); + if (type && type == 'opacity') { + newKeyframe( + 'opacity', + object, + currenttime, + object.get('opacity'), + true + ); + } else if (type && type == 'opacity3') { + newKeyframe( + 'charSpacing', + object, + currenttime, + object.get('charSpacing'), + true + ); + newKeyframe( + 'lineHeight', + object, + currenttime, + object.get('lineHeight'), + true + ); + } else { + if (id == 'object-x' || id == 'object-y') { + newKeyframe( + 'left', + object, + currenttime, + object.get('left'), + true + ); + newKeyframe( + 'top', + object, + currenttime, + object.get('top'), + true + ); + } else if (id == 'object-w' || id == 'object-h') { + newKeyframe( + 'scaleX', + object, + currenttime, + object.get('scaleX'), + true + ); + newKeyframe( + 'scaleY', + object, + currenttime, + object.get('scaleY'), + true + ); + newKeyframe( + 'width', + object, + currenttime, + object.get('width'), + true + ); + newKeyframe( + 'height', + object, + currenttime, + object.get('width'), + true + ); + if (selection) { + newKeyframe( + 'left', + object, + currenttime, + object.get('left'), + true + ); + newKeyframe( + 'top', + object, + currenttime, + object.get('top'), + true + ); + } + } else if (id == 'object-r') { + newKeyframe( + 'angle', + object, + currenttime, + object.get('angle'), + true + ); + if (selection) { + newKeyframe( + 'left', + object, + currenttime, + object.get('left'), + true + ); + newKeyframe( + 'top', + object, + currenttime, + object.get('top'), + true + ); + newKeyframe( + 'scaleX', + object, + currenttime, + object.get('scaleX'), + true + ); + newKeyframe( + 'scaleY', + object, + currenttime, + object.get('scaleY'), + true + ); + newKeyframe( + 'width', + object, + currenttime, + object.get('width'), + true + ); + newKeyframe( + 'height', + object, + currenttime, + object.get('width'), + true + ); + } + } else if (id == 'object-stroke') { + newKeyframe( + 'strokeWidth', + object, + currenttime, + object.get('strokeWidth'), + true + ); + newKeyframe( + 'stroke', + object, + currenttime, + object.get('stroke'), + true + ); + } else if ( + id == 'object-shadow-x' || + id == 'object-shadow-y' || + id == 'object-blur' || + id == 'object-color-stroke-opacity' + ) { + newKeyframe( + 'shadow.color', + object, + currenttime, + object.shadow.color, + true + ); + newKeyframe( + 'shadow.opacity', + object, + currenttime, + object.shadow.opacity, + true + ); + newKeyframe( + 'shadow.offsetX', + object, + currenttime, + object.shadow.offsetX, + true + ); + newKeyframe( + 'shadow.offsetY', + object, + currenttime, + object.shadow.offsetY, + true + ); + newKeyframe( + 'shadow.blur', + object, + currenttime, + object.shadow.blur, + true + ); + } + } + save(); +} + +// Play video +function play() { + paused = false; + animate(true, currenttime); + $('#play-button').attr('src', 'assets/pause-button.svg'); +} + +// Pause video +function pause() { + paused = true; + $('#play-button').attr('src', 'assets/play-button.svg'); +} + +// Set object value (while animating) +function setObjectValue(prop, object, value, inst) { + if (object.get('type') != 'group') { + if (object.group) { + var group = object.group; + tempgroup = group._objects; + group._restoreObjectsState(); + canvas.setActiveObject(group); + inst.remove(canvas.getActiveObject()); + canvas.discardActiveObject(); + inst.renderAll(); + for (var i = 0; i < tempgroup.length; i++) { + inst.add(tempgroup[i]); + } + } + } + if (prop == 'left' && !recording) { + object.set(prop, value + artboard.get('left')); + } else if (prop == 'top' && !recording) { + object.set(prop, value + artboard.get('top')); + } else if (prop == 'shadow.blur') { + object.shadow.blur = value; + } else if (prop == 'shadow.color') { + object.shadow.color = value; + } else if (prop == 'shadow.offsetX') { + object.shadow.offsetX = value; + } else if (prop == 'shadow.offsetY') { + object.shadow.offsetY = value; + } else if (prop == 'shadow.blur') { + object.shadow.blur = value; + } else if (object.get('type') != 'group') { + object.set(prop, value); + } else if (prop != 'width') { + object.set(prop, value); + } + inst.renderAll(); +} + +// Find last keyframe in time from same object & property +function lastKeyframe(keyframe, index) { + var temparr = keyframes.slice(); + temparr.sort(function (a, b) { + return a.t - b.t; + }); + temparr.length = temparr.findIndex((x) => x === keyframe); + temparr.reverse(); + if (temparr.length == 0) { + return false; + } else { + for (var i = 0; i < temparr.length; i++) { + if ( + temparr[i].id == keyframe.id && + temparr[i].name == keyframe.name + ) { + return temparr[i]; + break; + } else if (i == temparr.length - 1) { + return false; + } + } + } +} + +// Check whether any keyframe exists for a certain property +function checkAnyKeyframe(id, prop, inst) { + const object = inst.getItemById(id); + if (object.get('assetType') == 'audio') { + return false; + } + if ( + object.get('type') != 'textbox' && + (prop == 'charSpacing' || prop == 'lineHeight') + ) { + return false; + } + if ( + object.get('type') == 'group' && + (prop == 'shadow.opacity' || + prop == 'shadow.color' || + prop == 'shadow.offsetX' || + prop == 'shadow.offsetY' || + prop == 'shadow.blur') + ) { + return false; + } + const keyarr2 = $.grep(keyframes, function (e) { + return e.id == id && e.name == prop; + }); + if (keyarr2.length == 0) { + const value = objects + .find((x) => x.id == id) + .defaults.find((x) => x.name == prop).value; + setObjectValue(prop, object, value, inst); + } +} + +// Check if parameter is a DOM element +function isDomElem(el) { + return el instanceof HTMLElement || el[0] instanceof HTMLElement + ? true + : false; +} + +// Play videos when seeking/playing +async function playVideos(time) { + objects.forEach(async function (object) { + var object = canvas.getItemById(object.id); + if (object == null) { + return false; + } + var inst = canvas; + var start = false; + if (recording) { + object = canvasrecord.getItemById(object.id); + inst = canvasrecord; + } + if ( + object.get('id').indexOf('Video') >= 0 && + p_keyframes.find((x) => x.id == object.id).trimstart + + p_keyframes.find((x) => x.id == object.id).start <= + time && + p_keyframes.find((x) => x.id == object.id).end >= time + ) { + var tempfilters = object.filters; + if (object.filters.length > 0) { + object.filters = []; + object.applyFilters(); + var image = object; + var backend = fabric.filterBackend; + if (backend && backend.evictCachesForKey) { + backend.evictCachesForKey(image.cacheKey); + backend.evictCachesForKey(image.cacheKey + '_filtered'); + } + await object.setElement(object.saveElem); + } + object.set('visible', true); + inst.renderAll(); + if ($(object.getElement())[0].paused == true) { + $(object.getElement())[0].currentTime = parseFloat( + ( + (time - + p_keyframes.find((x) => x.id == object.id).start + + p_keyframes.find((x) => x.id == object.id).trimstart) / + 1000 + ).toFixed(2) + ); + } + if (!recording) { + var animation = { + value: 0, + }; + var instance = anime({ + targets: animation, + value: [currenttime, duration], + delay: 0, + duration: duration, + easing: 'linear', + autoplay: true, + update: async function () { + if (!paused && start) { + if (object.filters.length > 0) { + object.filters = []; + object.applyFilters(); + var image = object; + var backend = fabric.filterBackend; + if (backend && backend.evictCachesForKey) { + backend.evictCachesForKey(image.cacheKey); + backend.evictCachesForKey( + image.cacheKey + '_filtered' + ); + } + await object.setElement(object.saveElem); + } + if ($(object.getElement())[0].tagName == 'VIDEO') { + $(object.getElement())[0].play(); + } + await inst.renderAll(); + if (tempfilters.length > 0) { + object.filters = tempfilters; + object.applyFilters(); + inst.renderAll(); + } + } else if (paused) { + if ( + isDomElem($(object.getElement())[0]) && + $(object.getElement())[0].tagName == 'VIDEO' + ) { + $(object.getElement())[0].pause(); + } + animation.value = duration + 1; + anime.remove(animation); + } + }, + changeBegin: function () { + start = true; + }, + }); + if (paused) { + $(object.getElement())[0].currentTime = parseFloat( + ( + (time - + p_keyframes.find((x) => x.id == object.id).start + + p_keyframes.find((x) => x.id == object.id) + .trimstart) / + 1000 + ).toFixed(2) + ); + await inst.renderAll(); + if (tempfilters.length > 0) { + object.filters = tempfilters; + object.applyFilters(); + inst.renderAll(); + } + } + } else { + if ($(object.getElement())[0].paused == true) { + $(object.getElement())[0].play(); + inst.renderAll(); + } + } + } else if (object.get('id').indexOf('Video') >= 0) { + $(object.getElement())[0].pause(); + object.set('visible', false); + inst.renderAll(); + } + }); +} + +// Play background audio +function playAudio(time) { + objects.forEach(async function (object) { + var start = false; + var obj = canvas.getItemById(object.id); + if (obj.get('assetType') == 'audio') { + var flag = false; + var animation = { + value: 0, + }; + var instance = anime({ + targets: animation, + value: [currenttime, duration], + delay: 0, + duration: duration, + easing: 'linear', + autoplay: true, + update: async function () { + if (start && play && !paused) { + if ( + !flag && + p_keyframes.find((x) => x.id == object.id).start <= + currenttime && + p_keyframes.find((x) => x.id == object.id).end >= + currenttime + ) { + if (obj.get('src')) { + obj.get('src').currentTime = + (p_keyframes.find((x) => x.id == object.id) + .trimstart - + p_keyframes.find((x) => x.id == object.id).start + + currenttime) / + 1000; + obj.get('src').volume = obj.get('volume'); + obj.get('src').play(); + flag = true; + } else { + var audio = new Audio(obj.get('audioSrc')); + obj.set('src', audio); + audio.volume = obj.get('volume'); + audio.crossOrigin = 'anonymous'; + audio.currentTime = + (p_keyframes.find((x) => x.id == object.id) + .trimstart - + p_keyframes.find((x) => x.id == object.id).start + + currenttime) / + 1000; + audio.play(); + flag = true; + } + } else if ( + p_keyframes.find((x) => x.id == object.id).start >= + currenttime || + p_keyframes.find((x) => x.id == object.id).end <= + currenttime + ) { + if (obj.get('src')) { + obj.get('src').pause(); + } + } + } else if (paused) { + if (obj.get('src')) { + obj.get('src').pause(); + anime.remove(animation); + } + } + }, + changeBegin: function () { + start = true; + }, + }); + } + }); +} + +// Temp animate with render callback +async function recordAnimate(time) { + anime.speed = 1; + //return new Promise(function(resolve){ + var inst = canvasrecord; + if (animatedtext.length > 0) { + animatedtext.forEach(function (text) { + text.seek(time, inst); + inst.renderAll(); + }); + } + keyframes.forEach(function (keyframe, index) { + // Regroup if needed (groups break to animate their children, then regroup after children have animated) + if (groups.find((x) => x.id == keyframe.id)) { + if (!canvas.getItemById(keyframe.id)) { + reGroup(keyframe.id); + } + const object = canvas.getItemById(keyframe.id); + if ( + currenttime < + p_keyframes.find((x) => x.id == keyframe.id).trimstart + + p_keyframes.find((x) => x.id == keyframe.id).start + ) { + object.set('visible', false); + inst.renderAll(); + } else if ( + currenttime > + p_keyframes.find((x) => x.id == keyframe.id).end || + currenttime > duration + ) { + object.set('visible', false); + inst.renderAll(); + } else { + object.set('visible', true); + inst.renderAll(); + } + if ( + currenttime >= + p_keyframes.find((x) => x.id == keyframe.id).trimstart + + p_keyframes.find((x) => x.id == keyframe.id).start + ) { + props.forEach(function (prop) { + checkAnyKeyframe(keyframe.id, prop, inst); + }); + } + } + + // Copy of setObjectValue function, seems to perform better inside the function + function setValue(prop, object, value, inst) { + if (object.get('type') != 'group') { + if (object.group) { + var group = object.group; + tempgroup = group._objects; + group._restoreObjectsState(); + canvas.setActiveObject(group); + inst.remove(canvas.getActiveObject()); + canvas.discardActiveObject(); + inst.renderAll(); + for (var i = 0; i < tempgroup.length; i++) { + inst.add(tempgroup[i]); + } + } + } + if (prop == 'left' && !recording) { + object.set(prop, value + artboard.get('left')); + } else if (prop == 'top' && !recording) { + object.set(prop, value + artboard.get('top')); + } else if (prop == 'shadow.blur') { + object.shadow.blur = value; + } else if (prop == 'shadow.color') { + object.shadow.color = value; + } else if (prop == 'shadow.offsetX') { + object.shadow.offsetX = value; + } else if (prop == 'shadow.offsetY') { + object.shadow.offsetY = value; + } else if (prop == 'shadow.blur') { + object.shadow.blur = value; + } else if (object.get('type') != 'group') { + object.set(prop, value); + } else if (prop != 'width') { + object.set(prop, value); + } + inst.renderAll(); + } + + // Find next keyframe in time from same object & property + function nextKeyframe(keyframe, index) { + var temparr = keyframes.slice(); + temparr.sort(function (a, b) { + return a.t - b.t; + }); + temparr.splice(0, temparr.findIndex((x) => x === keyframe) + 1); + if (temparr.length == 0) { + return false; + } else { + for (var i = 0; i < temparr.length; i++) { + if ( + temparr[i].id == keyframe.id && + temparr[i].name == keyframe.name + ) { + return temparr[i]; + break; + } else if (i == temparr.length - 1) { + return false; + } + } + } + } + + var object = canvasrecord.getItemById(keyframe.id); + if ( + keyframe.t >= time && + currenttime >= + p_keyframes.find((x) => x.id == keyframe.id).trimstart + + p_keyframes.find((x) => x.id == keyframe.id).start + ) { + var delay = 0; + var start = false; + var lasttime, lastprop; + // Find last keyframe in time from same object & property + var lastkey = lastKeyframe(keyframe, index); + if (!lastkey) { + lasttime = 0; + lastprop = objects + .find((x) => x.id == keyframe.id) + .defaults.find((x) => x.name == keyframe.name).value; + } else { + lasttime = lastkey.t; + lastprop = lastkey.value; + } + if (lastkey && lastkey.t >= time && !play) { + return; + } + + // Initiate the animation + var animation = { + value: lastprop, + }; + var instance = anime({ + targets: animation, + delay: delay, + value: keyframe.value, + duration: keyframe.t - lasttime, + easing: keyframe.easing, + autoplay: false, + update: function () { + if (start && paused) { + anime.remove(animation); + } + }, + changeBegin: function () { + start = true; + }, + }); + + if (time - lasttime <= 0) { + instance.seek(0); + } else { + instance.seek(time - lasttime); + } + + if ( + parseFloat(lasttime) <= parseFloat(time) && + parseFloat(keyframe.t) >= parseFloat(time) + ) { + setValue(keyframe.name, object, animation.value, inst); + } + } else if (keyframe.t < time && !nextKeyframe(keyframe, index)) { + var prop = keyframe.name; + if (prop == 'shadow.blur') { + if (object.shadow.blur != keyframe.value) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } else if (prop == 'shadow.color') { + if (object.shadow.color != keyframe.value) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } else if (prop == 'shadow.offsetX') { + if (object.shadow.offsetX != keyframe.value) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } else if (prop == 'shadow.offsetY') { + if (object.shadow.offsetY != keyframe.value) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } else { + if (object.get(prop) != keyframe.value) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } + } + }); + + objects.forEach(function (object) { + if (object.id.indexOf('Group') == -1) { + const object2 = canvas.getItemById(object.id); + if ( + currenttime < + p_keyframes.find((x) => x.id == object.id).trimstart + + p_keyframes.find((x) => x.id == object.id).start + ) { + object2.set('visible', false); + } else if ( + currenttime > + p_keyframes.find((x) => x.id == object.id).end || + currenttime > duration + ) { + object2.set('visible', false); + } else { + object2.set('visible', true); + } + if ( + currenttime >= + p_keyframes.find((x) => x.id == object.id).trimstart + + p_keyframes.find((x) => x.id == object.id).start + ) { + props.forEach(function (prop) { + checkAnyKeyframe(object.id, prop, inst); + }); + } + } + }); + inst.renderAll(); + + playVideos(time); + //}); +} + +// Animate timeline (or seek to specific point in time) +async function animate(play, time) { + anime.speed = speed; + if (!draggingPanel) { + var starttime = new Date(); + var offset = time; + var inst = canvas; + keyframes.forEach(function (keyframe, index) { + // Find next keyframe in time from same object & property + function nextKeyframe(keyframe, index) { + var temparr = keyframes.slice(); + temparr.sort(function (a, b) { + return a.t - b.t; + }); + temparr.splice( + 0, + temparr.findIndex((x) => x === keyframe) + 1 + ); + if (temparr.length == 0) { + return false; + } else { + for (var i = 0; i < temparr.length; i++) { + if ( + temparr[i].id == keyframe.id && + temparr[i].name == keyframe.name + ) { + return temparr[i]; + break; + } else if (i == temparr.length - 1) { + return false; + } + } + } + } + // Regroup if needed (groups break to animate their children, then regroup after children have animated) + if (groups.find((x) => x.id == keyframe.id)) { + if (!canvas.getItemById(keyframe.id)) { + reGroup(keyframe.id); + } + const object = canvas.getItemById(keyframe.id); + if ( + currenttime < + p_keyframes.find((x) => x.id == keyframe.id).trimstart + + p_keyframes.find((x) => x.id == keyframe.id).start + ) { + object.set('visible', false); + inst.renderAll(); + } else if ( + currenttime > + p_keyframes.find((x) => x.id == keyframe.id).end || + currenttime > duration + ) { + object.set('visible', false); + inst.renderAll(); + } else { + object.set('visible', true); + inst.renderAll(); + } + if ( + currenttime >= + p_keyframes.find((x) => x.id == keyframe.id).trimstart + + p_keyframes.find((x) => x.id == keyframe.id).start + ) { + props.forEach(function (prop) { + checkAnyKeyframe(keyframe.id, prop, inst); + }); + } + } + + // Copy of setObjectValue function, seems to perform better inside the function + function setValue(prop, object, value, inst) { + if (object.get('assetType') == 'audio' && play) { + if (object.get('src')) { + object.get('src').volume = value; + object.set('volume', value); + } + return false; + } + if (object.get('type') != 'group') { + if (object.group) { + /* + var group = object.group; + tempgroup = group._objects; + group._restoreObjectsState(); + canvas.setActiveObject(group); + inst.remove(canvas.getActiveObject()); + canvas.discardActiveObject(); + inst.renderAll(); + for (var i = 0; i < tempgroup.length; i++) { + inst.add(tempgroup[i]); + } + */ + } + } + if (prop == 'left' && !recording) { + object.set(prop, value + artboard.get('left')); + } else if (prop == 'top' && !recording) { + object.set(prop, value + artboard.get('top')); + } else if (prop == 'shadow.blur') { + object.shadow.blur = value; + } else if (prop == 'shadow.color') { + object.shadow.color = value; + } else if (prop == 'shadow.offsetX') { + object.shadow.offsetX = value; + } else if (prop == 'shadow.offsetY') { + object.shadow.offsetY = value; + } else if (prop == 'shadow.blur') { + object.shadow.blur = value; + } else if (object.get('type') != 'group') { + object.set(prop, value); + } else if (prop != 'width') { + object.set(prop, value); + } + inst.renderAll(); + } + + var object = canvas.getItemById(keyframe.id); + if ( + keyframe.t >= time && + currenttime >= + p_keyframes.find((x) => x.id == keyframe.id).trimstart + + p_keyframes.find((x) => x.id == keyframe.id).start + ) { + var delay = 0; + var start = false; + var lasttime, lastprop; + // Find last keyframe in time from same object & property + var lastkey = lastKeyframe(keyframe, index); + if (!lastkey) { + lasttime = 0; + lastprop = objects + .find((x) => x.id == keyframe.id) + .defaults.find((x) => x.name == keyframe.name).value; + } else { + lasttime = lastkey.t; + lastprop = lastkey.value; + } + if (lastkey && lastkey.t >= time && !play) { + return; + } + // Set delay for the animation if playing + if (play) { + if (lasttime > currenttime) { + delay = lasttime - time; + } + } + // Initiate the animation + var animation = { + value: lastprop, + }; + var instance = anime({ + targets: animation, + delay: delay, + value: keyframe.value, + duration: keyframe.t - lasttime, + easing: keyframe.easing, + autoplay: false, + update: function () { + if (start && !paused) { + if ( + currenttime < + p_keyframes.find((x) => x.id == keyframe.id) + .trimstart + + p_keyframes.find((x) => x.id == keyframe.id) + .start || + currenttime > + p_keyframes.find((x) => x.id == keyframe.id).end || + currenttime > duration + ) { + object.set('visible', false); + inst.renderAll(); + } else { + setValue( + keyframe.name, + object, + animation.value, + inst + ); + object.set('visible', true); + inst.renderAll(); + } + } else if (start && paused) { + anime.remove(animation); + } + }, + changeBegin: function () { + start = true; + }, + }); + + if (time - lasttime <= 0) { + instance.seek(0); + } else { + instance.seek(time - lasttime); + } + + if (play) { + instance.play(); + } else if ( + parseFloat(lasttime) <= parseFloat(time) && + parseFloat(keyframe.t) >= parseFloat(time) + ) { + setValue(keyframe.name, object, animation.value, inst); + } + } else if ( + keyframe.t < time && + !nextKeyframe(keyframe, index) + ) { + var prop = keyframe.name; + if (prop == 'left' && !recording) { + if ( + object.get('left') - artboard.get('left') != + keyframe.value + ) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } else if (prop == 'top' && !recording) { + if ( + object.get('top') - artboard.get('top') != + keyframe.value + ) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } else if (prop == 'shadow.blur') { + if (object.shadow.blur != keyframe.value) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } else if (prop == 'shadow.color') { + if (object.shadow.color != keyframe.value) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } else if (prop == 'shadow.offsetX') { + if (object.shadow.offsetX != keyframe.value) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } else if (prop == 'shadow.offsetY') { + if (object.shadow.offsetY != keyframe.value) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } else { + if (object.get(prop) != keyframe.value) { + setValue(keyframe.name, object, keyframe.value, inst); + } + } + } + }); + /* + if (play) { + p_keyframes.forEach(function(keyframe){ + inst.getItemById(keyframe.id).set("visible", false); + window.setTimeout(function(){ + if (!paused) { + inst.getItemById(keyframe.id).set("visible", true); + inst.renderAll(); + } + }, keyframe.start-time) + window.setTimeout(function(){ + if (!paused) { + inst.getItemById(keyframe.id).set("visible", false); + inst.renderAll(); + } + }, keyframe.end-time) + }) + } + */ + objects.forEach(function (object) { + if (object.id.indexOf('Group') == -1) { + const object2 = canvas.getItemById(object.id); + if ( + currenttime < + p_keyframes.find((x) => x.id == object.id).trimstart + + p_keyframes.find((x) => x.id == object.id).start + ) { + object2.set('visible', false); + } else if ( + currenttime > + p_keyframes.find((x) => x.id == object.id).end || + currenttime > duration + ) { + object2.set('visible', false); + } else { + object2.set('visible', true); + } + if ( + currenttime >= + p_keyframes.find((x) => x.id == object.id).trimstart + + p_keyframes.find((x) => x.id == object.id).start + ) { + props.forEach(function (prop) { + checkAnyKeyframe(object.id, prop, inst); + }); + } + } + var obj = canvas.getItemById(object.id); + if (obj.type == 'lottie') { + obj.goToSeconds(currenttime); + inst.renderAll(); + } + }); + inst.renderAll(); + + if (animatedtext.length > 0) { + animatedtext.forEach(function (text) { + text.seek(currenttime, canvas); + inst.renderAll(); + }); + } + + playVideos(time); + if (play) { + playAudio(time); + } + if (play && !paused) { + var animation = { + value: 0, + }; + var main_instance = anime({ + targets: animation, + value: [currenttime, duration], + duration: duration - currenttime, + easing: 'linear', + autoplay: true, + update: function () { + if (!paused) { + currenttime = animation.value; + if (animatedtext.length > 0) { + animatedtext.forEach(function (text) { + text.seek(currenttime, canvas); + inst.renderAll(); + }); + } + objects.forEach(function (object) { + if (object.id.indexOf('Group') == -1) { + const object2 = inst.getItemById(object.id); + if ( + currenttime < + p_keyframes.find((x) => x.id == object.id) + .trimstart + + p_keyframes.find((x) => x.id == object.id).start + ) { + object2.set('visible', false); + } else if ( + currenttime > + p_keyframes.find((x) => x.id == object.id).end || + currenttime > duration + ) { + object2.set('visible', false); + } else { + object2.set('visible', true); + } + if ( + currenttime >= + p_keyframes.find((x) => x.id == object.id) + .trimstart + + p_keyframes.find((x) => x.id == object.id).start + ) { + props.forEach(function (prop) { + checkAnyKeyframe(object.id, prop, inst); + }); + } + } + var obj = canvas.getItemById(object.id); + if (obj.type == 'lottie') { + obj.goToSeconds(currenttime); + inst.renderAll(); + } + }); + inst.renderAll(); + if (!recording) { + renderTime(); + $('#seekbar').css({ + left: currenttime / timelinetime + offset_left, + }); + } + } else { + pause(); + animation.value = duration + 1; + anime.remove(animation); + } + }, + complete: function () { + pause(); + }, + }); + } else if (paused) { + currenttime = time; + } + } +} + +// Render a keyframe +function renderKeyframe(object, prop, time) { + const color = objects.find((x) => x.id == object.id).color; + if (prop == 'shadow.color') { + if ( + $('#' + object.get('id')) + .find('.shadowcolor') + .is(':visible') + ) { + time = + time - + parseFloat( + p_keyframes.find((x) => x.id == object.get('id')).start + ); + } + $('#' + object.get('id')) + .find('.shadowcolor') + .prepend( + "
" + ); + $('#' + object.get('id')) + .find('.shadowcolor') + .find("[data-time='" + time + "']") + .css({ left: time / timelinetime, background: color }); + } else { + if ( + $('#' + object.get('id')) + .find('.' + prop) + .is(':visible') + ) { + time = + time - + parseFloat( + p_keyframes.find((x) => x.id == object.get('id')).start + ); + } + $('#' + object.get('id')) + .find('.' + prop) + .prepend( + "
" + ); + $('#' + object.get('id')) + .find('.' + prop) + .find("[data-time='" + time + "']") + .css({ left: time / timelinetime, background: color }); + } +} + +// Create a keyframe +function newKeyframe(property, object, time, value, render) { + // Check if property can be animated + if ( + $.inArray( + property, + objects.find((x) => x.id == object.get('id')).animate + ) != -1 + ) { + const keyarr = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(time) && + e.id == object.get('id') && + e.name == property + ); + }); + const keyarr2 = $.grep(keyframes, function (e) { + return e.id == object.get('id') && e.name == property; + }); + if (keyarr2.length == 0) { + if (property == 'left') { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == property).value = + object.get(property) - artboard.get('left'); + } else if (property == 'top') { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == property).value = + object.get(property) - artboard.get('top'); + } else { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == property).value = value; + } + } + if (keyarr.length == 0) { + if (property == 'left') { + keyframes.push({ + t: time, + name: property, + value: value - artboard.get('left'), + id: object.get('id'), + easing: 'linear', + }); + } else if (property == 'top') { + keyframes.push({ + t: time, + name: property, + value: value - artboard.get('top'), + id: object.get('id'), + easing: 'linear', + }); + } else { + keyframes.push({ + t: time, + name: property, + value: value, + id: object.get('id'), + easing: 'linear', + }); + } + if ( + render && + property != 'top' && + property != 'scaleY' && + property != 'width' && + property != 'height' && + property != 'stroke' && + property != 'shadow.opacity' && + property != 'shadow.offsetX' && + property != 'shadow.offsetY' && + property != 'shadow.blur' && + property != 'lineHeight' + ) { + renderKeyframe(object, property, time); + } + keyframes.sort(function (a, b) { + if ( + a.id.indexOf('Group') >= 0 && + b.id.indexOf('Group') == -1 + ) { + return 1; + } else if ( + b.id.indexOf('Group') >= 0 && + a.id.indexOf('Group') == -1 + ) { + return -1; + } else { + return 0; + } + }); + } else if (render) { + if ( + property != 'top' && + property != 'scaleY' && + property != 'width' && + property != 'height' && + property != 'stroke' && + property != 'shadow.opacity' && + property != 'shadow.offsetX' && + property != 'shadow.offsetY' && + property != 'shadow.blur' && + property != 'lineHeight' + ) { + updateKeyframe( + $('#' + object.get('id')).find( + ".keyframe[data-time='" + + time + + "'][data-property='" + + property + + "']" + ), + true + ); + } + } + } else { + if (property == 'left') { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == property).value = + object.get(property) - artboard.get('left'); + } else if (property == 'top') { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == property).value = + object.get(property) - artboard.get('top'); + } else { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == property).value = value; + } + } +} + +// Create a keyframe (manually) +function manualKeyframe() { + var prop = $(this).parent().attr('data-property'); + const object = canvas.getItemById( + $(this).parent().parent().parent().attr('data-object') + ); + if (prop == 'position') { + prop = 'left'; + newKeyframe('top', object, currenttime, object.get('top'), true); + } else if (prop == 'scale') { + prop = 'scaleX'; + newKeyframe( + 'scaleY', + object, + currenttime, + object.get('scaleY'), + true + ); + newKeyframe( + 'width', + object, + currenttime, + object.get('width'), + true + ); + newKeyframe( + 'height', + object, + currenttime, + object.get('height'), + true + ); + } else if (prop == 'stroke') { + prop = 'strokeWidth'; + newKeyframe( + 'stroke', + object, + currenttime, + object.get('stroke'), + true + ); + } else if (prop == 'shadow') { + prop = 'shadow.color'; + newKeyframe( + 'shadow.opacity', + object, + currenttime, + object.get('shadow.opacity'), + true + ); + newKeyframe( + 'shadow.offsetX', + object, + currenttime, + object.get('shadow.offsetX'), + true + ); + newKeyframe( + 'shadow.offsetY', + object, + currenttime, + object.get('shadow.offsetY'), + true + ); + newKeyframe( + 'shadow.blur', + object, + currenttime, + object.get('shadow.blur'), + true + ); + } else if (prop == 'text') { + prop = 'charSpacing'; + newKeyframe( + 'lineHeight', + object, + currenttime, + object.get('lineHeight'), + true + ); + } + newKeyframe(prop, object, currenttime, object.get(prop), true); + save(); +} +$(document).on('click', '.property-keyframe', manualKeyframe); + +// Freeze all properties (this is counterintuitve because I initially programmed it to work the other way around) +function toggleAnimate(e) { + e.stopPropagation(); + const object = canvas.getItemById( + $(this).parent().parent().parent().attr('data-object') + ); + // Turn off clock -> Stop animation + if ($(this).hasClass('frozen')) { + $(this).removeClass('frozen'); + $(this).attr('src', 'assets/freeze.svg'); + objects.find((x) => x.id == object.get('id')).animate = []; + // Turn on clock -> Start animation + } else { + $(this).addClass('frozen'); + $(this).attr('src', 'assets/frozen.svg'); + objects.find((x) => x.id == object.get('id')).animate = []; + if (object.get('assetType') == 'audio') { + objects + .find((x) => x.id == object.get('id')) + .animate.push('volume'); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id'); + }); + $(".keyframe[data-object='" + object.get('id') + "']").remove(); + $(this) + .parent() + .parent() + .parent() + .find('.freeze-prop') + .removeClass('frozen'); + newKeyframe('volume', object, 0, 0.5, true); + } else { + props.forEach(function (prop) { + objects + .find((x) => x.id == object.get('id')) + .animate.push(prop); + }); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id'); + }); + $(".keyframe[data-object='" + object.get('id') + "']").remove(); + $(this) + .parent() + .parent() + .parent() + .find('.freeze-prop') + .removeClass('frozen'); + + props.forEach(function (prop) { + if (prop == 'lineHeight' || prop == 'charSpacing') { + if (object.get('type') == 'textbox') { + newKeyframe(prop, object, 0, object.get(prop), true); + } + } else if ( + prop == 'shadow.opacity' || + prop == 'shadow.blur' || + prop == 'shadow.offsetX' || + prop == 'shadow.offsetY' || + prop == 'shadow.color' + ) { + if (object.get('type') != 'group') { + if (prop == 'shadow.color') { + newKeyframe(prop, object, 0, object.shadow.color, true); + } else if (prop == 'shadow.opacity') { + newKeyframe( + prop, + object, + 0, + object.shadow.opacity, + true + ); + } else if (prop == 'shadow.offsetX') { + newKeyframe( + prop, + object, + 0, + object.shadow.offsetX, + true + ); + } else if (prop == 'shadow.offsetY') { + newKeyframe( + prop, + object, + 0, + object.shadow.offsetY, + true + ); + } else if (prop == 'shadow.blur') { + newKeyframe(prop, object, 0, object.shadow.blur, true); + } + } + } else { + newKeyframe(prop, object, 0, object.get(prop), true); + } + }); + } + } + save(); +} +$(document).on('click', '.freeze', toggleAnimate); + +function animateProp(prop, object) { + objects.find((x) => x.id == object.get('id')).animate.push(prop); + + // Prop counterparts + if (prop == 'left') { + objects.find((x) => x.id == object.get('id')).animate.push('top'); + newKeyframe( + 'left', + object, + currenttime, + object.get('left'), + true + ); + newKeyframe('top', object, currenttime, object.get('top'), true); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'left').value = + object.get('left') - artboard.get('left'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'top').value = + object.get('top') - artboard.get('top'); + } else if (prop == 'scaleX') { + newKeyframe( + 'scaleY', + object, + currenttime, + object.get('scaleY'), + true + ); + newKeyframe( + 'width', + object, + currenttime, + object.get('width'), + true + ); + newKeyframe( + 'height', + object, + currenttime, + object.get('height'), + true + ); + objects + .find((x) => x.id == object.get('id')) + .animate.push('scaleY'); + objects + .find((x) => x.id == object.get('id')) + .animate.push('width'); + objects + .find((x) => x.id == object.get('id')) + .animate.push('height'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'height').value = + object.get('height'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'width').value = + object.get('width'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'scaleY').value = + object.get('scaleY'); + } else if (prop == 'strokeWidth') { + newKeyframe( + 'stroke', + object, + currenttime, + object.get('stroke'), + true + ); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'stroke').value = + object.get('stroke'); + objects + .find((x) => x.id == object.get('id')) + .animate.push('stroke'); + } else if (prop == 'shadow.color') { + newKeyframe( + 'shadow.color', + object, + currenttime, + object.shadow.color, + true + ); + newKeyframe( + 'shadow.opacity', + object, + currenttime, + object.shadow.opacity, + true + ); + newKeyframe( + 'shadow.offsetX', + object, + currenttime, + object.shadow.offsetX, + true + ); + newKeyframe( + 'shadow.offsetY', + object, + currenttime, + object.shadow.offsetY, + true + ); + newKeyframe( + 'shadow.blur', + object, + currenttime, + object.shadow.blur, + true + ); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'shadow.color').value = + object.get('shadow.color'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'shadow.opacity').value = + object.get('shadow.opacity'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'shadow.offsetX').value = + object.get('shadow.offsetX'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'shadow.offsetY').value = + object.get('shadow.offsetY'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'shadow.blur').value = + object.get('shadow.blur'); + objects + .find((x) => x.id == object.get('id')) + .animate.push('shadow.opacity'); + objects + .find((x) => x.id == object.get('id')) + .animate.push('shadow.offsetX'); + objects + .find((x) => x.id == object.get('id')) + .animate.push('shadow.offsetY'); + objects + .find((x) => x.id == object.get('id')) + .animate.push('shadow.blur'); + } else if (prop == 'charSpacing') { + newKeyframe( + 'lineHeight', + object, + currenttime, + object.get('lineHeight'), + true + ); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'lineHeight').value = + object.get('lineHeight'); + objects + .find((x) => x.id == object.get('id')) + .animate.push('lineHeight'); + } + + // Exception + if (prop != 'left' && prop != 'shadow.color') { + newKeyframe(prop, object, currenttime, object.get(prop), true); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == prop).value = object.get(prop); + } +} + +function freezeProp(prop, object) { + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != prop; + } + ); + // Also add prop counterparts (should probably have done in a better way) + if (prop == 'left') { + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != 'top'; + } + ); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != 'top'; + }); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'left').value = + object.get('left') - artboard.get('left'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'top').value = + object.get('top') - artboard.get('top'); + } else if (prop == 'scaleX') { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'height').value = + object.get('height'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'width').value = + object.get('width'); + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'scaleY').value = + object.get('scaleY'); + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != 'scaleY'; + } + ); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != 'scaleY'; + }); + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != 'width'; + } + ); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != 'width'; + }); + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != 'height'; + } + ); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != 'height'; + }); + } else if (prop == 'strokeWidth') { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'stroke').value = + object.get('stroke'); + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != 'stroke'; + } + ); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != 'stroke'; + }); + } else if (prop == 'shadow.color') { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'shadow.opacity').value = + object.shadow.opacity; + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'shadow.offsetX').value = + object.shadow.offsetX; + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'shadow.offsetY').value = + object.shadow.offsetY; + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'shadow.blur').value = + object.shadow.blur; + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != 'shadow.opacity'; + }); + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != 'shadow.opacity'; + } + ); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != 'shadow.offsetX'; + }); + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != 'shadow.offsetX'; + } + ); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != 'shadow.offsetY'; + }); + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != 'shadow.offsetY'; + } + ); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != 'shadow.blur'; + }); + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != 'shadow.blur'; + } + ); + } else if (prop == 'charSpacing') { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == 'lineHeight').value = + object.get('lineHeight'); + objects.find((x) => x.id == object.get('id')).animate = $.grep( + objects.find((x) => x.id == object.get('id')).animate, + function (e) { + return e != 'lineHeight'; + } + ); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != 'lineHeight'; + }); + } + + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id') || e.name != prop; + }); + + // Exception + if (prop != 'left' && prop != 'shadow.color') { + objects + .find((x) => x.id == object.get('id')) + .defaults.find((x) => x.name == prop).value = object.get(prop); + } + + $( + ".keyframe[data-object='" + + object.get('id') + + "'][data-property='" + + prop + + "']" + ).remove(); +} + +// Toggle animation mode for property +function toggleAnimateProp(e) { + e.stopPropagation(); + var prop = $(this).parent().attr('data-property'); + const object = canvas.getItemById( + $(this).parent().parent().parent().attr('data-object') + ); + if (prop == 'position') { + prop = 'left'; + } else if (prop == 'scale') { + prop = 'scaleX'; + } else if (prop == 'stroke') { + prop = 'strokeWidth'; + } else if (prop == 'shadow') { + prop = 'shadow.color'; + } else if (prop == 'text') { + prop = 'charSpacing'; + } + + // Check layer global "freezing" state + if ( + $(this) + .parent() + .parent() + .parent() + .find('.freeze') + .hasClass('frozen') + ) { + objects.find((x) => x.id == object.get('id')).animate = []; + $(this) + .parent() + .parent() + .parent() + .find('.freeze') + .removeClass('frozen'); + + // Stop animating all props except selected + var propmatch = [ + prop, + 'scaleY', + 'width', + 'height', + 'top', + 'stroke', + 'shadow.opacity', + 'shadow.offsetX', + 'shadow.offsetY', + 'shadow.blur', + 'lineHeight', + ]; + props.forEach(function (p) { + if ($.inArray(p, propmatch) == -1) { + if ( + (object.get('type') == 'textbox' && p == 'charSpacing') || + p == 'lineHeight' + ) { + freezeProp(p, object); + } else if (p != 'charSpacing' && p != 'lineHeight') { + freezeProp(p, object); + } + } + }); + } + + // Turn off clock -> Stop animating + if ($(this).hasClass('frozen')) { + $(this).removeClass('frozen'); + $(this).attr('src', 'assets/freeze.svg'); + freezeProp(prop, object); + // Turn on clock -> Animate + } else { + $(this).addClass('frozen'); + $(this).attr('src', 'assets/frozen.svg'); + animateProp(prop, object); + } + save(); +} +$(document).on('click', '.freeze-prop', toggleAnimateProp); + +// Lock layer +function lockLayer(e) { + e.stopPropagation(); + const object = canvas.getItemById( + $(this).parent().parent().parent().attr('data-object') + ); + if ($(this).hasClass('locked')) { + $(this).removeClass('locked'); + $(this).attr('src', 'assets/lock.svg'); + object.selectable = true; + $(this).parent().parent().parent().attr('draggable', true); + } else { + $(this).addClass('locked'); + $(this).attr('src', 'assets/locked.svg'); + object.selectable = false; + if (canvas.getActiveObject() == object) { + canvas.discardActiveObject(); + canvas.renderAll(); + } + $(this).parent().parent().parent().attr('draggable', false); + } + save(); +} +$(document).on('click', '.lock', lockLayer); + +// Center an object in the canvas +function centerObject(object) { + object.set('top', artboard.get('top') + artboard.get('height') / 2); + object.set( + 'left', + artboard.get('left') + artboard.get('width') / 2 + ); + canvas.renderAll(); + save(); +} + +// Render a layer +function renderLayer(object, animate = false) { + $('#nolayers').addClass('yaylayers'); + const color = objects.find((x) => x.id == object.get('id')).color; + var src = ''; + var classlock = ''; + var srclock = 'lock'; + var freeze = 'freeze'; + if (object.get('type') == 'textbox') { + src = 'assets/text.svg'; + } else if ( + object.get('type') == 'rect' || + object.get('type') == 'group' || + object.get('type') == 'circle' || + object.get('type') == 'path' + ) { + src = 'assets/star.svg'; + if (object.get('assetType') == 'animatedText') { + src = 'assets/text.svg'; + } + if (object.get('assetType') == 'audio') { + src = 'assets/audio.svg'; + } + } else if (object.get('type') == 'image') { + if ( + object.get('assetType') && + object.get('assetType') == 'video' + ) { + src = 'assets/video.svg'; + } else { + src = 'assets/image.svg'; + } + } else if (object.get('type') == 'lottie') { + src = 'assets/zappy.svg'; + } else if (object.get('assetType') == 'audio') { + src = 'assets/audio.svg'; + } + if (object.selectable == false) { + classlock = 'locked'; + srclock = 'locked'; + } + if (animate != false) { + freeze = 'frozen'; + } + const leftoffset = + p_keyframes.find((x) => x.id == object.get('id')).trimstart / + timelinetime; + const width = + (p_keyframes.find((x) => x.id == object.get('id')).end - + p_keyframes.find((x) => x.id == object.get('id')).trimstart) / + timelinetime; + $('#inner-timeline').prepend( + "
x.id == object.get('id')).start) / + timelinetime + + "px'>
" + ); + if (object.get('assetType') == 'audio') { + object.setControlsVisibility({ + mt: false, + mb: false, + ml: false, + mr: false, + }); + $('#layer-inner-list').prepend( + "
" + ); + } else { + $('#layer-inner-list').prepend( + "
" + ); + } + $(".layer[data-object='" + object.get('id') + "']") + .find('.properties') + .toggle(); + setTimelineZoom(timelinetime); + sortable('#layer-inner-list', { + placeholderClass: 'hovering', + copy: true, + customDragImage: (draggedElement, elementOffset, event) => { + return { + element: document.getElementById('nothing'), + posX: event.pageX - elementOffset.left, + posY: event.pageY - elementOffset.top, + }; + }, + }); + if (object.selectable == false) { + $(".layer[data-object='" + object.get('id') + "']").attr( + 'draggable', + false + ); + } +} + +// Render a property +function renderProp(prop, object) { + var classfreeze = ''; + srcfreeze = 'freeze'; + if ( + $.inArray( + prop, + objects.find((x) => x.id == object.get('id')).animate + ) != -1 + ) { + classfreeze = 'frozen'; + srcfreeze = 'frozen'; + } + if (prop == 'shadow.color') { + prop = 'shadowcolor'; + } + $('#' + object.get('id')).append( + "
" + ); + if (prop == 'left') { + $(".layer[data-object='" + object.get('id') + "']") + .find('.properties') + .append( + "
Position
" + ); + } else if (prop == 'scaleX') { + $(".layer[data-object='" + object.get('id') + "']") + .find('.properties') + .append( + "
Scale
" + ); + } else if (prop == 'strokeWidth') { + $(".layer[data-object='" + object.get('id') + "']") + .find('.properties') + .append( + "
Stroke
" + ); + } else if (prop == 'shadowcolor') { + $(".layer[data-object='" + object.get('id') + "']") + .find('.properties') + .append( + "
Shadow
" + ); + } else if (prop == 'charSpacing') { + $(".layer[data-object='" + object.get('id') + "']") + .find('.properties') + .append( + "
Text
" + ); + } else { + $(".layer[data-object='" + object.get('id') + "']") + .find('.properties') + .append( + "
" + + prop + + "
" + ); + } + $('#' + object.get('id')) + .find('.keyframe-row' + '.' + prop) + .toggle(); +} + +// Create a layer +function newLayer(object) { + layer_count++; + var color; + if (object.get('type') == 'image') { + if ( + object.get('assetType') && + object.get('assetType') == 'video' + ) { + color = '#106CF6'; + } else { + color = '#92F711'; + } + } else if (object.get('type') == 'textbox') { + color = '#F7119B'; + } else if ( + object.get('type') == 'rect' || + object.get('type') == 'group' || + object.get('type') == 'circle' || + object.get('type') == 'path' + ) { + color = '#9211F7'; + if (object.get('assetType') == 'animatedText') { + color = '#F7119B'; + } else if (object.get('assetType') == 'audio') { + color = '#11C0F7'; + } + } + if ( + (object.get('assetType') && object.get('assetType') == 'video') || + object.get('type') == 'lottie' || + object.get('assetType') == 'audio' + ) { + objects.push({ + object: object, + id: object.get('id'), + label: object.get('id'), + color: color, + defaults: [], + locked: [], + mask: 'none', + start: 0, + end: object.get('duration'), + }); + if (object.get('duration') < duration) { + p_keyframes.push({ + start: currenttime, + end: object.get('duration') + currenttime, + trimstart: 0, + trimend: object.get('duration') + currenttime, + object: object, + id: object.get('id'), + }); + } else { + p_keyframes.push({ + start: currenttime, + end: duration - currenttime, + trimstart: 0, + trimend: duration - currenttime, + object: object, + id: object.get('id'), + }); + } + } else { + objects.push({ + object: object, + id: object.get('id'), + label: object.get('id'), + color: color, + defaults: [], + locked: [], + mask: 'none', + }); + if (object.get('notnew')) { + p_keyframes.push({ + start: object.get('starttime'), + end: duration - object.get('starttime'), + trimstart: 0, + trimend: duration - currenttime, + object: object, + id: object.get('id'), + }); + } else { + p_keyframes.push({ + start: currenttime, + end: duration - currenttime, + trimstart: 0, + trimend: duration - currenttime, + object: object, + id: object.get('id'), + }); + } + } + renderLayer(object); + if ( + !object.get('assetType') || + object.get('assetType') != 'audio' + ) { + props.forEach(function (prop) { + if (prop == 'lineHeight' || prop == 'charSpacing') { + if (object.get('type') == 'textbox') { + if (prop != 'lineHeight') { + renderProp(prop, object); + } + objects + .find((x) => x.id == object.id) + .defaults.push({ name: prop, value: object.get(prop) }); + } + } else if ( + prop == 'shadow.opacity' || + prop == 'shadow.blur' || + prop == 'shadow.offsetX' || + prop == 'shadow.offsetY' || + prop == 'shadow.color' + ) { + if (object.get('type') != 'group') { + if (prop == 'shadow.color') { + renderProp(prop, object); + objects + .find((x) => x.id == object.id) + .defaults.push({ + name: prop, + value: object.shadow.color, + }); + } else if (prop == 'shadow.blur') { + objects + .find((x) => x.id == object.id) + .defaults.push({ + name: prop, + value: object.shadow.blur, + }); + } else if (prop == 'shadow.offsetX') { + objects + .find((x) => x.id == object.id) + .defaults.push({ + name: prop, + value: object.shadow.offsetX, + }); + } else if (prop == 'shadow.offsetY') { + objects + .find((x) => x.id == object.id) + .defaults.push({ + name: prop, + value: object.shadow.offsetY, + }); + } else if (prop == 'shadow.opacity') { + objects + .find((x) => x.id == object.id) + .defaults.push({ + name: prop, + value: object.shadow.opacity, + }); + } + } + } else { + if ( + prop != 'top' && + prop != 'scaleY' && + prop != 'stroke' && + prop != 'width' && + prop != 'height' + ) { + renderProp(prop, object); + } + objects + .find((x) => x.id == object.id) + .defaults.push({ name: prop, value: object.get(prop) }); + } + }); + } else { + renderProp('volume', object); + objects + .find((x) => x.id == object.id) + .defaults.push({ name: 'volume', value: 0 }); + } + $('.layer-selected').removeClass('layer-selected'); + $(".layer[data-object='" + object.get('id') + "']").addClass( + 'layer-selected' + ); + document + .getElementsByClassName('layer-selected')[0] + .scrollIntoView(); + objects.find((x) => x.id == object.id).animate = []; + animate(false, currenttime); + save(); + checkFilter(); +} + +// Add a (complex) SVG shape to the canvas +function newSVG(svg, x, y, width, center) { + var svggroup = []; + fabric.loadSVGFromURL(svg, function (objects, options) { + var newsvg = objects[0]; + if (objects.length > 1) { + newsvg = fabric.util.groupSVGElements(objects, options); + } + newsvg.set({ + id: 'Shape' + layer_count, + stroke: '#000', + left: x, + top: y, + strokeWidth: 0, + strokeUniform: true, + originX: 'center', + originY: 'center', + strokeDashArray: false, + absolutePositioned: true, + paintFirst: 'stroke', + objectCaching: true, + sourcePath: svg, + inGroup: false, + shadow: { + color: '#000', + offsetX: 0, + offsetY: 0, + blur: 0, + opacity: 0, + }, + }); + newsvg.scaleToWidth(width); + newsvg.set({ + scaleX: parseFloat(newsvg.get('scaleX').toFixed(2)), + scaleY: parseFloat(newsvg.get('scaleY').toFixed(2)), + }); + canvas.add(newsvg); + newLayer(newsvg); + canvas.setActiveObject(newsvg); + canvas.bringToFront(newsvg); + canvas.renderAll(); + if (center) { + newsvg.set( + 'left', + artboard.get('left') + artboard.get('width') / 2 + ); + newsvg.set( + 'top', + artboard.get('top') + artboard.get('height') / 2 + ); + canvas.renderAll(); + } + }); +} + +// Add a video to the canvas +function newVideo(file, src, x, y, duration, center) { + var newvid = new fabric.Image(file, { + left: x, + top: y, + width: file.width, + height: file.height, + originX: 'center', + originY: 'center', + backgroundColor: 'rgba(255,255,255,0)', + cursorWidth: 1, + stroke: '#000', + strokeUniform: true, + paintFirst: 'stroke', + strokeWidth: 0, + cursorDuration: 1, + cursorDelay: 250, + source: src, + duration: duration * 1000, + assetType: 'video', + id: 'Video' + layer_count, + objectCaching: false, + strokeDashArray: false, + inGroup: false, + shadow: { + color: '#000', + offsetX: 0, + offsetY: 0, + blur: 0, + opacity: 0, + }, + }); + files.push({ name: newvid.get('id'), file: src }); + newvid.saveElem = newvid.getElement(); + canvas.add(newvid); + if (newvid.get('width') > artboard.get('width')) { + newvid.scaleToWidth(artboard.get('width')); + } + newvid.scaleToWidth(150); + canvas.renderAll(); + if (window.duration < newvid.duration + currenttime) { + window.duration = + ((newvid.duration + currenttime) / 1000).toFixed(2) * 1000; + } + newLayer(newvid); + canvas.setActiveObject(newvid); + canvas.bringToFront(newvid); + if (center) { + newvid.set( + 'left', + artboard.get('left') + artboard.get('width') / 2 + ); + newvid.set( + 'top', + artboard.get('top') + artboard.get('height') / 2 + ); + canvas.renderAll(); + } + $('#load-video').removeClass('loading-active'); +} + +// Load a video +function loadVideo(src, x, y, center) { + var vidObj = document.createElement('video'); + var vidSrc = document.createElement('source'); + vidSrc.src = src; + vidObj.crossOrigin = 'anonymous'; + vidObj.appendChild(vidSrc); + vidObj.addEventListener('loadeddata', function () { + vidObj.width = this.videoWidth; + vidObj.height = this.videoHeight; + vidObj.currentTime = 0; + vidObj.muted = false; + function waitLoad() { + if (vidObj.readyState >= 3) { + newVideo(vidObj, src, x, y, vidObj.duration, center); + } else { + window.setTimeout(function () { + waitLoad(); + }, 100); + } + } + window.setTimeout(function () { + waitLoad(); + }, 100); + }); + vidObj.currentTime = 0; +} + +// Check that crop controls are inside image +function checkCrop(obj) { + if (obj.isContainedWithinObject(cropobj)) { + croptop = obj.get('top'); + cropleft = obj.get('left'); + cropscalex = obj.get('scaleX'); + cropscaley = obj.get('scaleY'); + } else { + obj.top = croptop; + obj.left = cropleft; + obj.scaleX = cropscalex; + obj.scaleY = cropscaley; + obj.setCoords(); + obj.saveState(); + } + obj.set({ + borderColor: '#51B9F9', + }); + canvas.renderAll(); + crop(canvas.getItemById('cropped')); +} + +// Perform a crop +function crop(obj) { + var crop = canvas.getItemById('crop'); + cropobj.setCoords(); + crop.setCoords(); + var cleft = + crop.get('left') - (crop.get('width') * crop.get('scaleX')) / 2; + var ctop = + crop.get('top') - (crop.get('height') * crop.get('scaleY')) / 2; + var height = + (crop.get('height') / cropobj.get('scaleY')) * crop.get('scaleY'); + var width = + (crop.get('width') / cropobj.get('scaleX')) * crop.get('scaleX'); + var img_height = cropobj.get('height') * cropobj.get('scaleY'); + var img_width = cropobj.get('width') * cropobj.get('scaleX'); + var left = + cleft - + (cropobj.get('left') - + (cropobj.get('width') * cropobj.get('scaleX')) / 2); + var top = + ctop - + (cropobj.get('top') - + (cropobj.get('height') * cropobj.get('scaleY')) / 2); + if (left < 0 && top > 0) { + obj + .set({ cropY: top / cropobj.get('scaleY'), height: height }) + .setCoords(); + canvas.renderAll(); + obj.set({ + top: ctop + (obj.get('height') * obj.get('scaleY')) / 2, + }); + canvas.renderAll(); + } else if (top < 0 && left > 0) { + obj + .set({ cropX: left / cropobj.get('scaleX'), width: width }) + .setCoords(); + canvas.renderAll(); + obj.set({ + left: cleft + (obj.get('width') * obj.get('scaleX')) / 2, + }); + canvas.renderAll(); + } else if (top > 0 && left > 0) { + obj + .set({ + cropX: left / cropobj.get('scaleX'), + cropY: top / cropobj.get('scaleY'), + height: height, + width: width, + }) + .setCoords(); + canvas.renderAll(); + obj.set({ + left: cleft + (obj.get('width') * obj.get('scaleX')) / 2, + top: ctop + (obj.get('height') * obj.get('scaleY')) / 2, + }); + canvas.renderAll(); + } + if (obj.get('id') != 'cropped') { + canvas.remove(crop); + canvas.remove(canvas.getItemById('overlay')); + canvas.remove(canvas.getItemById('cropped')); + cropping = false; + resetControls(); + canvas.uniformScaling = true; + canvas.renderAll(); + newKeyframe('scaleX', obj, currenttime, obj.get('scaleX'), true); + newKeyframe('scaleY', obj, currenttime, obj.get('scaleY'), true); + newKeyframe('width', obj, currenttime, obj.get('width'), true); + newKeyframe('height', obj, currenttime, obj.get('width'), true); + newKeyframe('left', obj, currenttime, obj.get('left'), true); + newKeyframe('top', obj, currenttime, obj.get('top'), true); + $('#properties-overlay').removeClass('properties-disabled'); + save(); + } + canvas.renderAll(); +} + +var tlcrop = new Image(); +tlcrop.src = 'assets/tlcrop.svg'; +var trcrop = new Image(); +trcrop.src = 'assets/trcrop.svg'; +var blcrop = new Image(); +blcrop.src = 'assets/blcrop.svg'; +var brcrop = new Image(); +brcrop.src = 'assets/brcrop.svg'; + +function overlay() { + canvas.add( + new fabric.Rect({ + left: artboard.left, + top: artboard.top, + originX: 'left', + originY: 'top', + width: artboard.width, + height: artboard.height, + fill: 'rgba(0,0,0,0.5)', + selectable: false, + id: 'overlay', + }) + ); +} + +// Start cropping an image +function cropImage(object) { + if (!cropping) { + $('#properties-overlay').addClass('properties-disabled'); + cropping = true; + cropobj = object; + canvas.uniformScaling = false; + cropobj.setCoords(); + var left = + cropobj.get('left') - + (cropobj.get('width') * cropobj.get('scaleX')) / 2; + var top = + cropobj.get('top') - + (cropobj.get('height') * cropobj.get('scaleY')) / 2; + var cropx = cropobj.get('cropX'); + var cropy = cropobj.get('cropY'); + overlay(); + var cropUI = new fabric.Rect({ + left: object.get('left'), + top: object.get('top'), + width: object.get('width') * object.get('scaleX') - 5, + height: object.get('height') * object.get('scaleY') - 5, + originX: 'center', + originY: 'center', + id: 'crop', + fill: 'rgba(0,0,0,0)', + shadow: { + color: 'black', + offsetX: 0, + offsetY: 0, + blur: 0, + opacity: 0, + }, + }); + cropobj.clone(function (cloned) { + cloned.set({ + id: 'cropped', + selectable: false, + originX: 'center', + originY: 'center', + }); + canvas.add(cloned); + canvas.bringToFront(cloned); + canvas.bringToFront(cropUI); + canvas.renderAll(); + cropobj = object; + }); + cropobj + .set({ + cropX: 0, + cropY: 0, + width: cropobj.get('ogWidth'), + height: cropobj.get('ogHeight'), + }) + .setCoords(); + canvas.renderAll(); + cropobj.set({ + left: + left + + (cropobj.get('width') * cropobj.get('scaleX')) / 2 - + cropx * cropobj.get('scaleX'), + top: + top + + (cropobj.get('height') * cropobj.get('scaleY')) / 2 - + cropy * cropobj.get('scaleY'), + }); + cropUI.setControlsVisibility({ + mt: false, + mb: false, + mr: false, + ml: false, + mtr: false, + }); + cropUI.controls.tl = new fabric.Control({ + x: -0.5, + y: -0.5, + offsetX: 3, + offsetY: 3, + cursorStyleHandler: + fabric.controlsUtils.scaleCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingEqually, + render: function (ctx, left, top, styleOverride, fabricObject) { + const wsize = 27; + const hsize = 27; + ctx.save(); + ctx.translate(left, top); + ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle)); + ctx.drawImage(tlcrop, -wsize / 2, -hsize / 2, wsize, hsize); + ctx.restore(); + }, + }); + cropUI.controls.tr = new fabric.Control({ + x: 0.5, + y: -0.5, + offsetX: -3, + offsetY: 3, + cursorStyleHandler: + fabric.controlsUtils.scaleCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingEqually, + render: function (ctx, left, top, styleOverride, fabricObject) { + const wsize = 27; + const hsize = 27; + ctx.save(); + ctx.translate(left, top); + ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle)); + ctx.drawImage(trcrop, -wsize / 2, -hsize / 2, wsize, hsize); + ctx.restore(); + }, + }); + cropUI.controls.bl = new fabric.Control({ + x: -0.5, + y: 0.5, + offsetX: 3, + offsetY: -3, + cursorStyleHandler: + fabric.controlsUtils.scaleCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingEqually, + render: function (ctx, left, top, styleOverride, fabricObject) { + const wsize = 27; + const hsize = 27; + ctx.save(); + ctx.translate(left, top); + ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle)); + ctx.drawImage(blcrop, -wsize / 2, -hsize / 2, wsize, hsize); + ctx.restore(); + }, + }); + cropUI.controls.br = new fabric.Control({ + x: 0.5, + y: 0.5, + offsetX: -3, + offsetY: -3, + cursorStyleHandler: + fabric.controlsUtils.scaleCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingEqually, + render: function (ctx, left, top, styleOverride, fabricObject) { + const wsize = 27; + const hsize = 27; + ctx.save(); + ctx.translate(left, top); + ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle)); + ctx.drawImage(brcrop, -wsize / 2, -hsize / 2, wsize, hsize); + ctx.restore(); + }, + }); + canvas.add(cropUI); + canvas.setActiveObject(cropUI); + canvas.renderAll(); + cropleft = cropUI.get('left'); + croptop = cropUI.get('top'); + cropscalex = cropUI.get('scaleX') - 0.03; + cropscaley = cropUI.get('scaleY') - 0.03; + } +} +$(document).on('click', '#crop-image', function () { + if (canvas.getActiveObject()) { + cropImage(canvas.getActiveObject()); + } +}); + +// Add an image to the canvas +function newImage(file, x, y, width, center) { + var newimg = new fabric.Image(file, { + left: x, + top: y, + originX: 'center', + originY: 'center', + stroke: '#000', + strokeUniform: true, + strokeWidth: 0, + paintFirst: 'stroke', + absolutePositioned: true, + id: 'Image' + layer_count, + inGroup: false, + strokeDashArray: false, + objectCaching: true, + shadow: { + color: 'black', + offsetX: 0, + offsetY: 0, + blur: 0, + opacity: 0, + }, + }); + files.push({ name: newimg.get('id'), file: file.src }); + canvas.add(newimg); + newimg.scaleToWidth(width); + newimg.set({ + scaleX: parseFloat(newimg.get('scaleX').toFixed(2)), + scaleY: parseFloat(newimg.get('scaleY').toFixed(2)), + ogWidth: newimg.get('width'), + ogHeight: newimg.get('height'), + }); + canvas.bringToFront(newimg); + canvas.renderAll(); + newLayer(newimg); + canvas.setActiveObject(newimg); + if (center) { + newimg.set( + 'left', + artboard.get('left') + artboard.get('width') / 2 + ); + newimg.set( + 'top', + artboard.get('top') + artboard.get('height') / 2 + ); + canvas.renderAll(); + } + $('#load-image').removeClass('loading-active'); +} + +function loadImage(src, x, y, width, center) { + var image = new Image(); + image.onload = function (img) { + newImage(image, x, y, width, center); + }; + image.src = src; +} + +function createVideoThumbnail(file, max, seekTo = 0.0, isURL) { + return new Promise((resolve, reject) => { + const videoPlayer = document.createElement('video'); + if (isURL) { + videoPlayer.setAttribute('src', file); + } else { + videoPlayer.setAttribute('src', URL.createObjectURL(file)); + } + videoPlayer.setAttribute('crossorigin', 'anonymous'); + videoPlayer.load(); + videoPlayer.addEventListener('error', (ex) => { + reject('error when loading video file', ex); + }); + videoPlayer.addEventListener('loadedmetadata', () => { + if (videoPlayer.duration < seekTo) { + reject('video is too short.'); + return; + } + setTimeout(() => { + videoPlayer.currentTime = seekTo; + }, 200); + videoPlayer.addEventListener('seeked', () => { + var oc = document.createElement('canvas'); + var octx = oc.getContext('2d'); + oc.width = videoPlayer.videoWidth; + oc.height = videoPlayer.videoheight; + octx.drawImage(videoPlayer, 0, 0); + if (videoPlayer.videoWidth > videoPlayer.videoHeight) { + oc.height = + (videoPlayer.videoHeight / videoPlayer.videoWidth) * max; + oc.width = max; + } else { + oc.width = + (videoPlayer.videoWidth / videoPlayer.videoHeight) * max; + oc.height = max; + } + octx.drawImage(oc, 0, 0, oc.width, oc.height); + octx.drawImage(videoPlayer, 0, 0, oc.width, oc.height); + resolve(oc.toDataURL()); + }); + }); + }); +} + +function createThumbnail(file, max) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onload = function (event) { + var img = new Image(); + img.onload = function () { + if (img.width > max) { + var oc = document.createElement('canvas'); + var octx = oc.getContext('2d'); + oc.width = img.width; + oc.height = img.height; + octx.drawImage(img, 0, 0); + if (img.width > img.height) { + oc.height = (img.height / img.width) * max; + oc.width = max; + } else { + oc.width = (img.width / img.height) * max; + oc.height = max; + } + octx.drawImage(oc, 0, 0, oc.width, oc.height); + octx.drawImage(img, 0, 0, oc.width, oc.height); + resolve(oc.toDataURL()); + } else { + resolve(img.src); + } + }; + img.src = event.target.result; + }; + reader.readAsDataURL(file); + }); +} + +function dataURItoBlob(dataURI) { + var byteString = atob(dataURI.split(',')[1]); + var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; + var ab = new ArrayBuffer(byteString.length); + var ia = new Uint8Array(ab); + for (var i = 0; i < byteString.length; i++) { + ia[i] = byteString.charCodeAt(i); + } + var blob = new Blob([ab], { type: mimeString }); + return blob; +} + +async function uploadFromURL() { + var url = $('#upload-link-input').val(); + let file = await fetch(url).then((r) => r.blob()); + if (file.type.split('/')[0] === 'image') { + $('#upload-link-input').val(''); + $('.upload-show').removeClass('upload-show'); + createThumbnail(file, 250).then(function (data) { + saveFile( + dataURItoBlob(data), + file, + file.type.split('/')[0], + 'temp', + false, + false + ); + }); + } else if (file.type.split('/')[0] === 'video') { + $('.upload-show').removeClass('upload-show'); + createVideoThumbnail(file, 250, 0, false).then(function (data) { + saveFile( + dataURItoBlob(data), + file, + file.type.split('/')[0], + 'temp', + false, + false + ); + }); + $('#upload-link-input').val(''); + } else { + alert('File type not accepted'); + } +} +$(document).on('click', '#upload-link-add', uploadFromURL); + +function handleUpload(custom = false) { + var files2; + if (custom == false) { + files2 = $('#filepick').get(0).files; + } else { + files2 = custom.originalEvent.dataTransfer.files; + } + if (files2) { + Array.from(files2).forEach((file) => { + uploading = true; + if (file.size / 1024 / 1024 <= 10) { + $('#upload-button').html( + " Uploading..." + ); + $('#upload-button').addClass('uploading'); + if (file['type'].split('/')[0] === 'image') { + $('.upload-show').removeClass('upload-show'); + createThumbnail(file, 250).then(function (data) { + saveFile( + dataURItoBlob(data), + file, + file['type'].split('/')[0], + 'temp', + false, + false + ); + }); + } else if (file['type'].split('/')[0] === 'video') { + $('.upload-show').removeClass('upload-show'); + createVideoThumbnail(file, 250, 0, false).then(function ( + data + ) { + saveFile( + dataURItoBlob(data), + file, + file['type'].split('/')[0], + 'temp', + false, + false + ); + }); + } else { + alert('File type not accepted'); + } + } else { + alert('File is too big'); + } + }); + if (files2.length == 1) { + if (files2[0]['type'].split('/')[0] === 'image') { + $('.upload-tab-active').removeClass('upload-tab-active'); + $('#images-tab').addClass('upload-tab-active'); + } else if (files2[0]['type'].split('/')[0] === 'video') { + $('.upload-tab-active').removeClass('upload-tab-active'); + $('#videos-tab').addClass('upload-tab-active'); + } else if (files2[0]['type'].split('/')[0] === 'audio') { + $('.upload-tab-active').removeClass('upload-tab-active'); + $('#audio-tab').addClass('upload-tab-active'); + } + } + } +} +$(document).on('change', '#filepick', function () { + handleUpload(false); +}); + +// Upload audio +function audioUpload() { + const files = $('#filepick2').get(0).files; + if (files) { + if (files.length == 1) { + if (files[0]['type'].split('/')[0] === 'audio') { + if (files[0].size / 1024 / 1024 <= 10) { + $('#audio-upload-button').html('Uploading...'); + $('#audio-upload-button').addClass('uploading'); + saveAudio(files[0]); + } else { + alert('File is too big'); + } + } else { + alert('Wrong file type'); + } + } + } +} +$(document).on('change', '#filepick2', audioUpload); + +// Create a rectangle +function newRectangle(color) { + var newrect = new fabric.Rect({ + left: 0, + top: 0, + originX: 'center', + originY: 'center', + width: 200, + height: 200, + stroke: '#000', + strokeWidth: 0, + strokeUniform: true, + backgroundColor: 'rgba(255,255,255,0)', + rx: 0, + ry: 0, + fill: color, + cursorWidth: 1, + cursorDuration: 1, + paintFirst: 'stroke', + cursorDelay: 250, + strokeDashArray: false, + inGroup: false, + id: 'Shape' + layer_count, + shadow: { + color: '#000', + offsetX: 0, + offsetY: 0, + blur: 0, + opacity: 0, + }, + }); + canvas.add(newrect); + newLayer(newrect); + canvas.setActiveObject(newrect); + canvas.bringToFront(newrect); + canvas.renderAll(); +} + +// Change text format +function formatText() { + var isselected = false; + if (!canvas.getActiveObject().isEditing) { + canvas.getActiveObject().enterEditing(); + canvas.getActiveObject().selectAll(); + isselected = true; + } + if ($(this).hasClass('format-text-active')) { + if ($(this).attr('id') == 'format-bold') { + $(this).find('img').attr('src', 'assets/bold.svg'); + canvas + .getActiveObject() + .setSelectionStyles({ fontWeight: 'normal' }); + } else if ($(this).attr('id') == 'format-italic') { + $(this).find('img').attr('src', 'assets/italic.svg'); + canvas + .getActiveObject() + .setSelectionStyles({ fontStyle: 'normal' }); + } else if ($(this).attr('id') == 'format-underline') { + $(this).find('img').attr('src', 'assets/underline.svg'); + canvas + .getActiveObject() + .setSelectionStyles({ underline: false }); + } else { + $(this).find('img').attr('src', 'assets/strike.svg'); + canvas + .getActiveObject() + .setSelectionStyles({ linethrough: false }); + } + $(this).removeClass('format-text-active'); + } else { + $(this).addClass('format-text-active'); + if ($(this).attr('id') == 'format-bold') { + $(this).find('img').attr('src', 'assets/bold-active.svg'); + canvas + .getActiveObject() + .setSelectionStyles({ fontWeight: 'bold' }); + } else if ($(this).attr('id') == 'format-italic') { + $(this).find('img').attr('src', 'assets/italic-active.svg'); + canvas + .getActiveObject() + .setSelectionStyles({ fontStyle: 'italic' }); + } else if ($(this).attr('id') == 'format-underline') { + $(this).find('img').attr('src', 'assets/underline-active.svg'); + canvas + .getActiveObject() + .setSelectionStyles({ underline: true }); + } else { + $(this).find('img').attr('src', 'assets/strike-active.svg'); + canvas + .getActiveObject() + .setSelectionStyles({ linethrough: true }); + } + } + if (isselected) { + canvas.getActiveObject().exitEditing(); + } + canvas.renderAll(); + save(); +} +$(document).on('click', '.format-text', formatText); + +// Change stroke type (e.g. dashed), ignore naming (used to be for line join) +function lineJoin() { + if ($('.line-join-active').attr('id') == 'miter') { + $('.line-join-active') + .find('img') + .attr('src', 'assets/miter.svg'); + } else if ($('.line-join-active').attr('id') == 'bevel') { + $('.line-join-active') + .find('img') + .attr('src', 'assets/bevel.svg'); + } else if ($('.line-join-active').attr('id') == 'round') { + $('.line-join-active') + .find('img') + .attr('src', 'assets/round.svg'); + } else if ($('.line-join-active').attr('id') == 'small-dash') { + $('.line-join-active') + .find('img') + .attr('src', 'assets/dash2.svg'); + } + $('.line-join-active').removeClass('line-join-active'); + $(this).addClass('line-join-active'); + if ($(this).attr('id') == 'miter') { + $(this).find('img').attr('src', 'assets/miter-active.svg'); + canvas + .getActiveObject() + .set({ strokeWidth: 0, strokeDashArray: false }); + canvas.renderAll(); + updatePanelValues(); + } else if ($(this).attr('id') == 'bevel') { + $(this).find('img').attr('src', 'assets/bevel-active.svg'); + canvas.getActiveObject().set({ strokeDashArray: false }); + if (canvas.getActiveObject().get('strokeWidth') == 0) { + canvas.getActiveObject().set({ strokeWidth: 1 }); + canvas.renderAll(); + updatePanelValues(); + } + } else if ($(this).attr('id') == 'round') { + $(this).find('img').attr('src', 'assets/round-active.svg'); + canvas.getActiveObject().set({ strokeDashArray: [10, 5] }); + if (canvas.getActiveObject().get('strokeWidth') == 0) { + canvas.getActiveObject().set({ strokeWidth: 1 }); + canvas.renderAll(); + updatePanelValues(); + } + } else { + $(this).find('img').attr('src', 'assets/dash2-active.svg'); + canvas.getActiveObject().set({ strokeDashArray: [3, 3] }); + if (canvas.getActiveObject().get('strokeWidth') == 0) { + canvas.getActiveObject().set({ strokeWidth: 1 }); + canvas.renderAll(); + updatePanelValues(); + } + } + canvas.renderAll(); + save(); +} +$(document).on('click', '.line-join', lineJoin); + +// Change text alignment +function alignText() { + var textalign; + if ($('.align-text-active').attr('id') == 'align-text-left') { + $('.align-text-active') + .find('img') + .attr('src', 'assets/align-text-left.svg'); + } else if ( + $('.align-text-active').attr('id') == 'align-text-center' + ) { + $('.align-text-active') + .find('img') + .attr('src', 'assets/align-text-center.svg'); + } else if ( + $('.align-text-active').attr('id') == 'align-text-right' + ) { + $('.align-text-active') + .find('img') + .attr('src', 'assets/align-text-right.svg'); + } else { + $('.align-text-active') + .find('img') + .attr('src', 'assets/align-text-justify.svg'); + } + $('.align-text-active').removeClass('align-text-active'); + $(this).addClass('align-text-active'); + if ($(this).attr('id') == 'align-text-left') { + textalign = 'left'; + $(this) + .find('img') + .attr('src', 'assets/align-text-left-active.svg'); + } else if ($(this).attr('id') == 'align-text-center') { + textalign = 'center'; + $(this) + .find('img') + .attr('src', 'assets/align-text-center-active.svg'); + } else if ($(this).attr('id') == 'align-text-right') { + textalign = 'right'; + $(this) + .find('img') + .attr('src', 'assets/align-text-right-active.svg'); + } else { + textalign = 'justify'; + $(this) + .find('img') + .attr('src', 'assets/align-text-justify-active.svg'); + } + canvas.getActiveObject().set({ textAlign: textalign }); + canvas.renderAll(); + save(); +} +$(document).on('click', '.align-text', alignText); + +// Change font +function changeFont() { + var font = $('#font-picker').val(); + if (canvas.getActiveObject().get('assetType')) { + WebFont.load({ + google: { + families: [font], + }, + active: () => { + var object = canvas.getActiveObject(); + animatedtext + .find((x) => x.id == object.id) + .reset( + animatedtext.find((x) => x.id == object.id).text, + $.extend( + animatedtext.find((x) => x.id == object.id).props, + { fontFamily: font } + ), + canvas + ); + save(); + }, + }); + save(); + } else { + WebFont.load({ + google: { + families: [font], + }, + active: () => { + canvas.getActiveObject().set('fontFamily', font); + canvas.renderAll(); + save(); + }, + }); + } +} +$(document).on('change', '#font-picker', changeFont); + +// Calculate text width to display it in 1 line +function calculateTextWidth(text, font) { + var ctx = canvas.getContext('2d'); + ctx.font = font; + return ctx.measureText(text).width + 10; +} + +// Create an audio layer +function newAudioLayer(src) { + var audio = new Audio(src); + audio.crossOrigin = 'anonymous'; + audio.addEventListener('loadeddata', () => { + var nullobject = new fabric.Rect({ + id: 'Audio' + layer_count, + width: 10, + height: 10, + audioSrc: src, + duration: audio.duration * 1000, + opacity: 0, + selectable: false, + volume: 0.5, + assetType: 'audio', + shadow: { + color: '#000', + offsetX: 0, + offsetY: 0, + blur: 0, + opacity: 0, + }, + }); + canvas.add(nullobject); + newLayer(nullobject); + }); +} + +// Create a textbox +function newTextbox( + fontsize, + fontweight, + text, + x, + y, + width, + center, + font +) { + var newtext = new fabric.Textbox(text, { + left: x, + top: y, + originX: 'center', + originY: 'center', + fontFamily: 'Inter', + fill: '#000', + fontSize: fontsize, + fontWeight: fontweight, + textAlign: 'center', + cursorWidth: 1, + stroke: '#000', + strokeWidth: 0, + cursorDuration: 1, + paintFirst: 'stroke', + objectCaching: false, + absolutePositioned: true, + strokeUniform: true, + inGroup: false, + cursorDelay: 250, + strokeDashArray: false, + width: calculateTextWidth( + text, + fontweight + ' ' + fontsize + 'px Inter' + ), + id: 'Text' + layer_count, + shadow: { + color: '#000', + offsetX: 0, + offsetY: 0, + blur: 0, + opacity: 0, + }, + }); + newtext.setControlsVisibility({ + mt: false, + mb: false, + }); + canvas.add(newtext); + newLayer(newtext); + canvas.setActiveObject(newtext); + canvas.bringToFront(newtext); + newtext.enterEditing(); + newtext.selectAll(); + canvas.renderAll(); + if (center) { + newtext.set( + 'left', + artboard.get('left') + artboard.get('width') / 2 + ); + newtext.set( + 'top', + artboard.get('top') + artboard.get('height') / 2 + ); + canvas.renderAll(); + } + canvas.getActiveObject().set('fontFamily', font); + canvas.renderAll(); +} + +function deleteObject(object, def = true) { + if (object.get('assetType') == 'animatedText' && def) { + animatedtext = $.grep(animatedtext, function (a) { + return a.id != object.id; + }); + } + if (object.type == 'image') { + var temp = files.find((x) => x.name == object.get('id')); + files = $.grep(files, function (a) { + return a != temp.name; + }); + } + $(".layer[data-object='" + object.get('id') + "']").remove(); + $('#' + object.get('id')).remove(); + keyframes = $.grep(keyframes, function (e) { + return e.id != object.get('id'); + }); + p_keyframes = $.grep(p_keyframes, function (e) { + return e.id != object.get('id'); + }); + objects = $.grep(objects, function (e) { + return e.id != object.get('id'); + }); + canvas.remove(object); + canvas.renderAll(); + canvas.discardActiveObject(); + save(); + if (objects.length == 0) { + $('#nolayers').removeClass('yaylayers'); + } +} + +// Delete selected object +function deleteSelection() { + if ( + canvas.getActiveObject() && + !canvas.getActiveObject().isEditing + ) { + const selection = canvas.getActiveObject(); + if (selection.type == 'activeSelection') { + canvas.discardActiveObject(); + selection._objects.forEach(function (object) { + deleteObject(object); + }); + } else { + deleteObject(canvas.getActiveObject()); + } + } +} + +// Expand / collapse layer +function toggleLayer() { + const layerid = $(this).parent().parent().attr('data-object'); + $(this).parent().parent().find('.properties').toggle(); + $(this).parent().parent().find('.droparrow').toggleClass('layeron'); + $(".keyframe-row[data-object='" + layerid + "']").toggle(); + setTimelineZoom(timelinetime); +} +$(document).on('click', '.droparrow', toggleLayer); + +// Select layer +function selectLayer(e) { + if (!$(e.target).hasClass('droparrow')) { + const layerid = $(this).parent().attr('data-object'); + $('.layer-selected').removeClass('layer-selected'); + $(this).parent().addClass('layer-selected'); + canvas.setActiveObject(canvas.getItemById(layerid)); + } +} +$(document).on('click', '.layer-name', selectLayer); + +// Set video duration +function setDuration(length) { + $('#inner-timeline').css('width', length / timelinetime + 50); + $('#inner-seekarea').css('width', length / timelinetime + 50); + duration = length; + var minutes = Math.floor(duration / 1000 / 60); + var seconds = (duration / 1000 - minutes * 60).toFixed(2); + $('#total-time input').val( + ('0' + minutes).slice(-2) + + ':' + + ('0' + Math.floor(seconds)).slice(-2) + + ':' + + ('0' + Math.floor((seconds % 1) * 100)).slice(-2) + ); + $('.object-props').each(function () { + $(this).css( + 'width', + duration / timelinetime - + p_keyframes.find((x) => x.id == $(this).attr('id')).start / + timelinetime + + 'px' + ); + p_keyframes.find((x) => x.id == $(this).attr('id')).end = + duration; + if ( + p_keyframes.find((x) => x.id == $(this).attr('id')).trimend > + p_keyframes.find((x) => x.id == $(this).attr('id')).end + ) { + p_keyframes.find((x) => x.id == $(this).attr('id')).trimend = + duration; + $(this) + .find('.trim-row') + .css( + 'width', + duration / timelinetime - + p_keyframes.find((x) => x.id == $(this).attr('id')) + .trimstart / + timelinetime + + 'px' + ); + } + }); + setTimelineZoom(timelinetime); + save(); +} + +// Render time markers +function renderTimeMarkers() { + var renderoffset = 1000 / timelinetime - 20; + var timenumber = 0; + var modulo = 1; + if (timelinetime > 18) { + modulo = 5; + } else if (timelinetime > 12) { + modulo = 2; + } + $('#time-numbers').html(''); + $('#time-numbers').append( + "
" + + timenumber + + 's
' + ); + timenumber++; + while (timenumber * 1000 <= duration) { + $('#time-numbers').append( + "
" + + timenumber + + 's
' + ); + if (timenumber % modulo != 0) { + $('.time-number:last-child()').css('opacity', '0'); + } + timenumber++; + } +} + +// Change timeline zoom level +function setTimelineZoom(time) { + $('.object-props').each(function () { + $(this).offset({ + left: + p_keyframes.find((x) => x.id == $(this).attr('id')).start / + time + + $('#inner-timeline').offset().left + + offset_left, + }); + $(this).css({ width: ($(this).width() * timelinetime) / time }); + $(this) + .find('.trim-row') + .css({ + left: + p_keyframes.find((x) => x.id == $(this).attr('id')) + .trimstart / time, + }); + $(this) + .find('.trim-row') + .css({ + width: + ($(this).find('.trim-row').width() * timelinetime) / time, + }); + }); + timelinetime = time; + $('.keyframe').each(function () { + $(this).offset({ + left: + $(this).attr('data-time') / timelinetime + + $('#inner-timeline').offset().left + + offset_left, + }); + }); + $('#seekbar').offset({ + left: + $('#inner-timeline').offset().left + + currenttime / timelinetime + + offset_left, + }); + $('#inner-timeline').css({ width: duration / timelinetime + 50 }); + $('#inner-seekarea').css({ + minWidth: duration / timelinetime + 50, + }); + renderTimeMarkers(); +} +$(document).on('input', '#timeline-zoom', function () { + setTimelineZoom($('#timeline-zoom').val()); +}); + +function removeKeyframe() { + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != selectedkeyframe.attr('data-property') + ); + }); + if (selectedkeyframe.attr('data-property') == 'left') { + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != 'top' + ); + }); + } else if (selectedkeyframe.attr('data-property') == 'scaleX') { + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != 'scaleY' + ); + }); + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != 'width' + ); + }); + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != 'height' + ); + }); + } else if ( + selectedkeyframe.attr('data-property') == 'strokeWidth' + ) { + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != 'stroke' + ); + }); + } else if ( + selectedkeyframe.attr('data-property') == 'shadow.color' + ) { + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != 'shadow.blur' + ); + }); + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != 'shadow.offsetX' + ); + }); + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != 'shadow.offsetY' + ); + }); + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != 'shadow.opacity' + ); + }); + } else if ( + selectedkeyframe.attr('data-property') == 'charSpacing' + ) { + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != selectedkeyframe.attr('data-time') || + e.id != selectedkeyframe.attr('data-object') || + e.name != 'lineHeight' + ); + }); + } + selectedkeyframe.remove(); + $('#keyframe-properties').removeClass('show-properties'); +} + +// Delete a keyframe +function deleteKeyframe() { + if (shiftkeys.length > 0) { + shiftkeys.forEach(function (key) { + selectedkeyframe = $(key.keyframe); + removeKeyframe(); + }); + shiftkeys = []; + } else { + removeKeyframe(); + } + animate(false, currenttime); + save(); +} +$(document).on('click', '#delete-keyframe', deleteKeyframe); + +// Copy keyframes +function copyKeyframes() { + clipboard.sort(function (a, b) { + return a.t - b.t; + }); + var inittime = clipboard[0].t; + clipboard.forEach(function (keyframe) { + var newtime = keyframe.t - inittime + currenttime; + newKeyframe( + keyframe.name, + canvas.getItemById(keyframe.id), + newtime, + keyframe.value, + true + ); + var keyprop = keyframe.name; + if (keyprop == 'left') { + const keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == keyframe.t && e.id == keyframe.id && e.name == 'top' + ); + }); + newKeyframe( + 'top', + canvas.getItemById(keyframe.id), + newtime, + keyarr2[0].value, + true + ); + } else if (keyprop == 'scaleX') { + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == keyframe.t && + e.id == keyframe.id && + e.name == 'scaleY' + ); + }); + newKeyframe( + 'scaleY', + canvas.getItemById(keyframe.id), + newtime, + keyarr2[0].value, + true + ); + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == keyframe.t && + e.id == keyframe.id && + e.name == 'width' + ); + }); + if (keyarr2.length > 0) { + newKeyframe( + 'width', + canvas.getItemById(keyframe.id), + newtime, + keyarr2[0].value, + true + ); + } + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == keyframe.t && + e.id == keyframe.id && + e.name == 'height' + ); + }); + if (keyarr2.length > 0) { + newKeyframe( + 'height', + canvas.getItemById(keyframe.id), + newtime, + keyarr2[0].value, + true + ); + } + } else if (keyprop == 'strokeWidth') { + const keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == keyframe.t && + e.id == keyframe.id && + e.name == 'stroke' + ); + }); + newKeyframe( + 'stroke', + canvas.getItemById(keyframe.id), + newtime, + keyarr2[0].value, + true + ); + } else if (keyprop == 'charSpacing') { + const keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == keyframe.t && + e.id == keyframe.id && + e.name == 'lineHeight' + ); + }); + newKeyframe( + 'lineHeight', + canvas.getItemByid(keyframe.id), + newtime, + keyarr2[0].value, + true + ); + } else if (keyprop == 'shadow.color') { + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == keyframe.t && + e.id == keyframe.id && + e.name == 'shadow.opacity' + ); + }); + newKeyframe( + 'shadow.opacity', + canvas.getItemById(keyframe.id), + newtime, + keyarr2[0].value, + true + ); + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == keyframe.t && + e.id == keyframe.id && + e.name == 'shadow.offsetX' + ); + }); + newKeyframe( + 'shadow.offsetX', + canvas.getItemById(keyframe.id), + newtime, + keyarr2[0].value, + true + ); + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == keyframe.t && + e.id == keyframe.id && + e.name == 'shadow.offsetY' + ); + }); + + newKeyframe( + 'shadow.offsetY', + canvas.getItemById(keyframe.id), + newtime, + keyarr2[0].value, + true + ); + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == keyframe.t && + e.id == keyframe.id && + e.name == 'shadow.blur' + ); + }); + newKeyframe( + 'shadow.blur', + canvas.getItemById(keyframe.id), + newtime, + keyarr2[0].value, + true + ); + } + save(); + }); +} + +// Update keyframe (after dragging) +function updateKeyframe(drag, newval, offset) { + var time = parseFloat( + (drag.position().left * timelinetime).toFixed(1) + ); + const keyprop = drag.attr('data-property'); + const keytime = drag.attr('data-time'); + const keyarr = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == keyprop + ); + }); + const keyobj = canvas.getItemById(keyarr[0].id); + time = + parseFloat( + p_keyframes.find((x) => x.id == keyobj.get('id')).start + ) + time; + if (newval) { + time = currenttime; + } + var keyval = keyarr[0].value; + if (newval) { + if (keyprop == 'shadow.color') { + keyval = keyobj.shadow.color; + } else if (keyprop == 'volume') { + keyval = parseFloat($('#object-volume input').val() / 200); + } else { + keyval = keyobj.get(keyprop); + } + } else if (keyprop == 'left') { + keyval = keyval + artboard.get('left'); + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != keyprop + ); + }); + newKeyframe(keyprop, keyobj, time, keyval, false); + if (keyprop == 'left') { + const keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == 'top' + ); + }); + var keyval2 = keyarr2[0].value + artboard.get('top'); + if (newval) { + keyval2 = canvas.getItemById(keyarr2[0].id).get('top'); + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != 'top' + ); + }); + newKeyframe('top', keyobj, time, keyval2, false); + } else if (keyprop == 'scaleX') { + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == 'scaleY' + ); + }); + var keyval2 = keyarr2[0].value; + if (newval) { + keyval2 = canvas.getItemById(keyarr2[0].id).get('scaleY'); + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != 'scaleY' + ); + }); + newKeyframe('scaleY', keyobj, time, keyval2, false); + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == 'width' + ); + }); + if (keyarr2.length > 0) { + var keyval2 = keyarr2[0].value; + if (newval) { + keyval2 = canvas.getItemById(keyarr2[0].id).get('width'); + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != 'width' + ); + }); + newKeyframe('width', keyobj, time, keyval2, false); + } + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == 'height' + ); + }); + if (keyarr2.length > 0) { + var keyval2 = keyarr2[0].value; + if (newval) { + keyval2 = canvas.getItemById(keyarr2[0].id).get('height'); + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != 'height' + ); + }); + newKeyframe('height', keyobj, time, keyval2, false); + } + } else if (keyprop == 'strokeWidth') { + const keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == 'stroke' + ); + }); + var keyval2 = keyarr2[0].value; + if (newval) { + keyval2 = canvas.getItemById(keyarr2[0].id).get('stroke'); + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != 'stroke' + ); + }); + newKeyframe('stroke', keyobj, time, keyval2, false); + } else if (keyprop == 'charSpacing') { + const keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == 'lineHeight' + ); + }); + var keyval2 = keyarr2[0].value; + if (newval) { + keyval2 = canvas.getItemById(keyarr2[0].id).get('lineHeight'); + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != 'lineHeight' + ); + }); + newKeyframe('lineHeight', keyobj, time, keyval2, false); + } else if (keyprop == 'shadow.color') { + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == 'shadow.opacity' + ); + }); + var keyval2 = keyarr2[0].value; + if (newval) { + keyval2 = canvas.getItemById(keyarr2[0].id).shadow.opacity; + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != 'shadow.opacity' + ); + }); + newKeyframe('shadow.opacity', keyobj, time, keyval2, false); + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == 'shadow.offsetX' + ); + }); + var keyval2 = keyarr2[0].value; + if (newval) { + keyval2 = canvas.getItemById(keyarr2[0].id).shadow.offsetX; + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != 'shadow.offsetX' + ); + }); + newKeyframe('shadow.offsetX', keyobj, time, keyval2, false); + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == 'shadow.offsetY' + ); + }); + var keyval2 = keyarr2[0].value; + if (newval) { + keyval2 = canvas.getItemById(keyarr2[0].id).shadow.offsetY; + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != 'shadow.offsetY' + ); + }); + newKeyframe('shadow.offsetY', keyobj, time, keyval2, false); + var keyarr2 = $.grep(keyframes, function (e) { + return ( + e.t == parseFloat(keytime) && + e.id == drag.attr('data-object') && + e.name == 'shadow.blur' + ); + }); + var keyval2 = keyarr2[0].value; + if (newval) { + keyval2 = canvas.getItemById(keyarr2[0].id).shadow.blur; + } + keyframes = $.grep(keyframes, function (e) { + return ( + e.t != parseFloat(keytime) || + e.id != drag.attr('data-object') || + e.name != 'shadow.blur' + ); + }); + newKeyframe('shadow.blur', keyobj, time, keyval2, false); + } + if (offset) { + drag.attr('data-time', time); + } else { + drag.attr( + 'data-time', + time + p_keyframes.find((x) => x.id == keyarr[0].id).start + ); + } + keyframes.sort(function (a, b) { + if (a.id.indexOf('Group') >= 0 && b.id.indexOf('Group') == -1) { + return 1; + } else if ( + b.id.indexOf('Group') >= 0 && + a.id.indexOf('Group') == -1 + ) { + return -1; + } else { + return 0; + } + }); +} + +function keyframeSnap(drag) { + if (shiftkeys.length == 0) { + if ( + drag.offset().left > $('#seekbar').offset().left - 5 && + drag.offset().left < $('#seekbar').offset().left + 5 + ) { + drag.offset({ left: $('#seekbar').offset().left }); + $('#line-snap').offset({ + left: $('#seekbar').offset().left, + top: drag.parent().parent().offset().top, + }); + $('#line-snap').css({ + height: drag.parent().parent().height(), + }); + $('#line-snap').addClass('line-active'); + } else { + drag + .parent() + .parent() + .find('.keyframe') + .each(function (index) { + if (!drag.is($(this))) { + if ( + drag.offset().left > $(this).offset().left - 5 && + drag.offset().left < $(this).offset().left + 5 + ) { + drag.offset({ left: $(this).offset().left }); + $('#line-snap').offset({ + left: $(this).offset().left, + top: drag.parent().parent().offset().top, + }); + $('#line-snap').css({ + height: drag.parent().parent().height(), + }); + $('#line-snap').addClass('line-active'); + return false; + } + } + if (index == $('.keyframe').length - 1) { + $('#line-snap').removeClass('line-active'); + } + }); + } + } +} + +// Dragging a keyframe +function dragKeyframe(e) { + if (e.which == 3) { + return false; + } + e.stopPropagation(); + e.preventDefault(); + var inst = this; + var drag = $(this); + var pageX = e.pageX; + var offset = $(this).offset(); + var move = false; + if (e.shiftKey) { + if (!$(this).hasClass('keyframe-selected')) { + shiftkeys.push({ + keyframe: this, + offset: $(this).offset().left, + }); + $(this).addClass('keyframe-selected'); + } else { + shiftkeys = $.grep(shiftkeys, function (e) { + return e.keyframe != this; + }); + $(this).removeClass('keyframe-selected'); + } + } + if (shiftkeys.length > 0) { + shiftkeys.forEach(function (key) { + key.offset = $(key.keyframe).offset().left; + }); + } + function draggingKeyframe(e) { + move = true; + var left = offset.left + (e.pageX - pageX); + if (shiftkeys.length == 0) { + if (left > $('#timearea').offset().left + offset_left) { + drag.offset({ left: left }); + } else { + drag.offset({ + left: $('#timearea').offset().left + offset_left, + }); + } + keyframeSnap(drag); + } else { + shiftkeys.forEach(function (key) { + if (key.keyframe != inst) { + $(key.keyframe).offset({ + left: key.offset + (e.pageX - pageX), + }); + keyframeSnap($(key.keyframe)); + } else { + drag.offset({ left: left }); + keyframeSnap(drag); + } + }); + } + } + function releasedKeyframe(e) { + $('body') + .off('mousemove', draggingKeyframe) + .off('mouseup', releasedKeyframe); + $('#line-snap').removeClass('line-active'); + if (move) { + if (shiftkeys.length == 0) { + // Check for 60FPS playback, 16ms "slots" + var time = parseFloat( + (drag.position().left * timelinetime).toFixed(1) + ); + if (time % 16.666 != 0) { + drag.offset({ + left: + (Math.ceil(time / 16.666) * 16.666) / timelinetime + + drag.parent().offset().left, + }); + updateKeyframe(drag, false); + } else { + updateKeyframe(drag, false); + } + } else { + shiftkeys.forEach(function (key) { + // Check for 60FPS playback, 16ms "slots" + var time = parseFloat( + ($(key.keyframe).position().left * timelinetime).toFixed( + 1 + ) + ); + if (time % 16.666 != 0) { + $(key.keyframe).offset({ + left: + (Math.ceil(time / 16.666) * 16.666) / timelinetime + + $(key.keyframe).parent().offset().left, + }); + updateKeyframe($(key.keyframe), false); + } else { + updateKeyframe($(key.keyframe), false); + } + }); + } + } else if (!e.shiftDown) { + keyframeProperties(inst); + } + move = false; + $('.line-active').removeClass('line-active'); + save(); + } + $('body') + .on('mouseup', releasedKeyframe) + .on('mousemove', draggingKeyframe); +} +$(document).on('mousedown', '.keyframe', dragKeyframe); + +// Render current time in the playback area +function renderTime() { + var minutes = Math.floor(currenttime / 1000 / 60); + var seconds = (currenttime / 1000 - minutes * 60).toFixed(2); + $('#current-time input').val( + ('0' + minutes).slice(-2) + + ':' + + ('0' + Math.floor(seconds)).slice(-2) + + ':' + + ('0' + Math.floor((seconds % 1) * 100)).slice(-2) + ); +} + +// Update current time (and account for frame "slots") +function updateTime(drag, check) { + if ($('#timeline').scrollLeft() > offset_left) { + currenttime = parseFloat( + ( + (drag.position().left + + $('#timeline').scrollLeft() - + offset_left) * + timelinetime + ).toFixed(1) + ); + } else { + currenttime = parseFloat( + ( + (drag.position().left + + $('#timeline').scrollLeft() - + offset_left) * + timelinetime + ).toFixed(1) + ); + } + // Check for 60FPS playback, 16ms "slots" + if (currenttime % 16.666 != 0 && !check) { + currenttime = Math.ceil(currenttime / 16.666) * 16.666; + } + renderTime(); + pause(); + animate(false, currenttime); +} + +// Dragging the seekbar +function dragSeekBar(e) { + if (e.which == 3) { + return false; + } + var drag = $(this); + var pageX = e.pageX; + var offset = $(this).offset(); + tempselection = canvas.getActiveObject(); + canvas.discardActiveObject(); + function dragging(e) { + paused = true; + var left = offset.left + (e.pageX - pageX); + if ( + left > $('#timearea').offset().left + offset_left && + left - $('#timearea').offset().left < + duration / timelinetime + offset_left + ) { + drag.offset({ left: left }); + } else if (left < $('#timearea').offset().left + offset_left) { + drag.offset({ + left: offset_left + $('#timearea').offset().left, + }); + } + if ($('#timeline').scrollLeft() > offset_left) { + currenttime = parseFloat( + ( + (drag.position().left + + $('#timeline').scrollLeft() - + offset_left) * + timelinetime + ).toFixed(1) + ); + } else { + currenttime = parseFloat( + ( + (drag.position().left + + $('#timeline').scrollLeft() - + offset_left) * + timelinetime + ).toFixed(1) + ); + } + animate(false, currenttime); + seeking = true; + renderTime(); + } + function released(e) { + $('body').off('mousemove', dragging).off('mouseup', released); + updateTime(drag, false); + seeking = false; + if (tempselection && tempselection.type != 'activeSelection') { + reselect(tempselection); + } + updatePanelValues(); + } + $('body').on('mouseup', released).on('mousemove', dragging); +} +$(document).on('mousedown', '#seekbar', dragSeekBar); + +// Dragging layer horizontally +function dragObjectProps(e) { + if (e.which == 3) { + return false; + } + var drag = $(this).parent(); + var drag2 = $(this).find('.trim-row'); + var target = e.target; + var pageX = e.pageX; + var offset = drag.offset(); + var offset2 = drag2.offset(); + var initwidth = drag2.width(); + var initpos = drag2.position().left; + var opened = false; + var trim = 'no'; + // Trim layer to hovered area + if (e.metaKey) { + if (e.shiftKey) { + if (drag2.position().left + e.pageX >= 0) { + drag2.offset({ + left: + hovertime / timelinetime - + p_keyframes.find((x) => x.id == drag.attr('id')) + .trimstart / + timelinetime + + offset2.left, + }); + const leftval = parseFloat( + (drag2.position().left * timelinetime).toFixed(1) + ); + p_keyframes.find((x) => x.id == drag.attr('id')).trimstart = + leftval; + drag2.css({ + width: + (p_keyframes.find((x) => x.id == drag.attr('id')) + .trimend - + p_keyframes.find((x) => x.id == drag.attr('id')) + .trimstart) / + timelinetime, + }); + return false; + } + } else { + if ( + hovertime + + p_keyframes.find((x) => x.id == drag.attr('id')).start < + duration + ) { + drag2.css({ + width: + hovertime / timelinetime - + p_keyframes.find((x) => x.id == drag.attr('id')) + .trimstart / + timelinetime, + }); + save(); + p_keyframes.find((x) => x.id == drag.attr('id')).end = + hovertime; + p_keyframes.find((x) => x.id == drag.attr('id')).trimend = + hovertime; + } + return false; + } + } + if (pageX - $(this).find('.trim-row').offset().left < 7) { + trim = 'left'; + } else if ( + pageX - $(this).find('.trim-row').offset().left > + $(this).find('.trim-row').width() - 7 + ) { + trim = 'right'; + } + function dragging(e) { + if (trim == 'no') { + var left = offset.left + (e.pageX - pageX); + if ( + left > + $('#timearea').offset().left + + offset_left - + $('#timeline').scrollLeft() + ) { + drag.offset({ left: left }); + } else if ( + left + $('#timeline').scrollLeft() < + $('#timearea').offset().left + offset_left + ) { + drag.css({ left: offset_left }); + } + p_keyframes.find((x) => x.id == drag.attr('id')).start = + parseFloat( + ( + (drag.position().left - + offset_left + + $('#timeline').scrollLeft()) * + timelinetime + ).toFixed(1) + ); + p_keyframes.find((x) => x.id == drag.attr('id')).end = + parseFloat( + ( + (drag.position().left + + drag.width() - + offset_left + + $('#timeline').scrollLeft()) * + timelinetime + ).toFixed(1) + ); + if ( + $(".keyframe-row[data-object='" + drag.attr('id') + "']").is( + ':hidden' + ) + ) { + opened = true; + $(".layer[data-object='" + drag.attr('id') + "']") + .find('.properties') + .toggle(); + $(".layer[data-object='" + drag.attr('id') + "']") + .find('.properties') + .toggleClass('layeron'); + $( + ".keyframe-row[data-object='" + drag.attr('id') + "']" + ).toggle(); + setTimelineZoom(timelinetime); + } + drag.find('.keyframe').each(function () { + updateKeyframe($(this), false, true); + }); + animate(false, currenttime); + } else if (trim == 'left') { + if (drag2.position().left + (e.pageX - pageX) >= 0) { + drag2.offset({ + left: offset2.left + (e.pageX - pageX), + }); + drag2.css({ + width: initwidth - (-initpos + drag2.position().left), + }); + const leftval = parseFloat( + (drag2.position().left * timelinetime).toFixed(1) + ); + p_keyframes.find((x) => x.id == drag.attr('id')).trimstart = + leftval; + } + } else if (trim == 'right') { + if (initwidth + (e.pageX - pageX) < duration / timelinetime) { + drag2.css({ + width: initwidth + (e.pageX - pageX), + }); + } else { + drag2.css({ + width: + duration / timelinetime - + drag.position().left - + $('#timeline').scrollLeft() + + offset_left, + }); + } + const rightval = parseFloat( + ( + (drag2.position().left + drag2.width()) * + timelinetime + ).toFixed(1) + ); + p_keyframes.find((x) => x.id == drag.attr('id')).end = rightval; + p_keyframes.find((x) => x.id == drag.attr('id')).trimend = + rightval; + } + } + function released(e) { + $('body').off('mousemove', dragging).off('mouseup', released); + if (opened) { + $(".layer[data-object='" + drag.attr('id') + "']") + .find('.properties') + .toggle(); + $(".layer[data-object='" + drag.attr('id') + "']") + .find('.properties') + .toggleClass('layeron'); + $( + ".keyframe-row[data-object='" + drag.attr('id') + "']" + ).toggle(); + setTimelineZoom(timelinetime); + } + animate(false, currenttime); + save(); + } + $('body').on('mouseup', released).on('mousemove', dragging); +} +$(document).on('mousedown', '.main-row', dragObjectProps); + +function resetHeight() { + var top = $(window).height() - oldtimelinepos - 92; + if ($('#upload-tool').hasClass('tool-active')) { + $('#browser').css('top', '150px'); + $('#browser').css( + 'height', + 'calc(100% - ' + (top + 97 + 150) + 'px)' + ); + } else { + $('#browser').css('top', '110px'); + $('#browser').css( + 'height', + 'calc(100% - ' + (top + 97 + 100) + 'px)' + ); + } + $('#timearea').css('height', top); + $('#layer-list').css('height', top); + $('#toolbar').css('height', 'calc(100% - ' + (top + 97) + 'px)'); + $('#canvas-area').css( + 'height', + 'calc(100% - ' + (top + 97) + 'px)' + ); + $('#properties').css('height', 'calc(100% - ' + (top + 97) + 'px)'); + $('#timeline-handle').css('bottom', top + 95); + resizeCanvas(); +} + +// Dragging timeline vertically +function dragTimeline(e) { + const disableselect = (e) => { + return false + } + document.onselectstart = disableselect + document.onmousedown = disableselect + + oldtimelinepos = e.pageY; + if (e.which == 3) { + return false; + } + function draggingKeyframe(e) { + oldtimelinepos = e.pageY; + resetHeight(e); + } + function releasedKeyframe(e) { + $('body') + .off('mousemove', draggingKeyframe) + .off('mouseup', releasedKeyframe); + } + $('body') + .on('mouseup', releasedKeyframe) + .on('mousemove', draggingKeyframe); +} + +$(document).on('mousedown', '#timeline-handle', dragTimeline); + +oldtimelinepos = $(window).height() - 92 - $('#timearea').height(); + +// Sync scrolling (vertical) +function syncScroll(el1, el2) { + var $el1 = $(el1); + var $el2 = $(el2); + var forcedScroll = false; + $el1.scroll(function () { + performScroll($el1, $el2); + }); + $el2.scroll(function () { + performScroll($el2, $el1); + }); + + function performScroll($scrolled, $toScroll) { + if (forcedScroll) return (forcedScroll = false); + var percent = + ($scrolled.scrollTop() / + ($scrolled[0].scrollHeight - $scrolled.outerHeight())) * + 100; + setScrollTopFromPercent($toScroll, percent); + } + + function setScrollTopFromPercent($el, percent) { + var scrollTopPos = + (percent / 100) * ($el[0].scrollHeight - $el.outerHeight()); + forcedScroll = true; + $el.scrollTop(scrollTopPos); + } +} + +// Sync scrolling (horizontal) +function syncScrollHoz(el1, el2) { + var $el1 = $(el1); + var $el2 = $(el2); + var forcedScroll = false; + $el1.scroll(function () { + performScroll($el1, $el2); + }); + $el2.scroll(function () { + performScroll($el2, $el1); + }); + + function performScroll($scrolled, $toScroll) { + if (forcedScroll) return (forcedScroll = false); + var percent = + ($scrolled.scrollLeft() / $scrolled.outerWidth()) * 100; + setScrollLeftFromPercent($toScroll, percent); + } + + function setScrollLeftFromPercent($el, percent) { + var scrollLeftPos = (percent / 100) * $el.outerWidth(); + forcedScroll = true; + $el.scrollLeft(scrollLeftPos); + } +} + +// Show keyframe properties +function keyframeProperties(inst) { + if (!shiftdown) { + selectedkeyframe = $(inst); + const popup = $('#keyframe-properties'); + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == selectedkeyframe.attr('data-property') + ); + }); + $('#easing select').val(keyarr[0].easing); + $('#easing select').niceSelect('update'); + popup.css({ + left: $(inst).offset().left - popup.width() / 2, + top: $(inst).offset().top - popup.height() - 20, + }); + popup.addClass('show-properties'); + $(inst).addClass('keyframe-selected'); + } +} + +// Apply easing to keyframe +function applyEasing() { + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == selectedkeyframe.attr('data-property') + ); + }); + keyarr[0].easing = $(this).attr('data-value'); + if (selectedkeyframe.attr('data-property') == 'left') { + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == 'top' + ); + }); + keyarr[0].easing = $('#easing select').val(); + } else if (selectedkeyframe.attr('data-property') == 'scaleX') { + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == 'scaleY' + ); + }); + keyarr[0].easing = $('#easing select').val(); + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == 'width' + ); + }); + keyarr[0].easing = $('#easing select').val(); + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == 'height' + ); + }); + keyarr[0].easing = $('#easing select').val(); + } else if ( + selectedkeyframe.attr('data-property') == 'strokeWidth' + ) { + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == 'stroke' + ); + }); + keyarr[0].easing = $('#easing select').val(); + } else if ( + selectedkeyframe.attr('data-property') == 'shadow.color' + ) { + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == 'shadow.opacity' + ); + }); + keyarr[0].easing = $('#easing select').val(); + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == 'shadow.offsetX' + ); + }); + keyarr[0].easing = $('#easing select').val(); + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == 'shadow.offsetY' + ); + }); + keyarr[0].easing = $('#easing select').val(); + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == 'shadow.blur' + ); + }); + keyarr[0].easing = $('#easing select').val(); + } else if ( + selectedkeyframe.attr('data-property') == 'charSpacing' + ) { + var keyarr = keyframes.filter(function (e) { + return ( + e.t == selectedkeyframe.attr('data-time') && + e.id == selectedkeyframe.attr('data-object') && + e.name == 'lineHeight' + ); + }); + keyarr[0].easing = $('#easing select').val(); + } + $('#keyframe-properties').removeClass('show-properties'); + selectedkeyframe.removeClass('keyframe-selected'); + save(); +} +$(document).on('mouseup', '#easing li', applyEasing); + +// Click on seek area to seek (still not working properly) +function seekTo(e) { + if ($(e.target).hasClass('keyframe')) { + return false; + } + paused = true; + if ($('#seekarea').scrollLeft() > offset_left) { + currenttime = parseFloat( + ( + (e.pageX + + $('#seekarea').scrollLeft() - + $('#timearea').offset().left - + offset_left) * + timelinetime + ).toFixed(1) + ); + } else { + currenttime = parseFloat( + ( + (e.pageX + + $('#seekarea').scrollLeft() - + $('#timearea').offset().left - + offset_left) * + timelinetime + ).toFixed(1) + ); + } + if (currenttime < 0) { + currenttime = 0; + } + // Check for 60FPS playback, 16ms "slots" + if (currenttime % 16.666 != 0) { + currenttime = Math.ceil(currenttime / 16.666) * 16.666; + } + renderTime(); + $('#seekbar').offset({ + left: + offset_left + + $('#inner-timeline').offset().left + + currenttime / timelinetime, + }); + animate(false, currenttime); + updatePanelValues(); +} +$(document).on('click', '#seekevents', seekTo); +$(document).on('click', '#timearea', seekTo); + +function hideSeekbar() { + $('#seek-hover').css({ opacity: 0 }); +} +function followCursor(e) { + $('#seek-hover').css({ opacity: 0.3 }); + if ($('#seekarea').scrollLeft() > offset_left) { + hovertime = parseFloat( + ( + (e.pageX + + $('#seekarea').scrollLeft() - + $('#timearea').offset().left - + offset_left) * + timelinetime + ).toFixed(1) + ); + } else { + hovertime = parseFloat( + ( + (e.pageX + + $('#seekarea').scrollLeft() - + $('#timearea').offset().left - + offset_left) * + timelinetime + ).toFixed(1) + ); + } + if (e.pageX >= offset_left + $('#inner-timeline').offset().left) { + $('#seek-hover').offset({ left: e.pageX }); + } +} +$(document).on('mousemove', '#timearea', followCursor); +$(document).on('mousemove', '#seekevents', followCursor); +$(document).on('mousemove', '#toolbar', hideSeekbar); +$(document).on('mousemove', '#canvas-area', hideSeekbar); +$(document).on('mousemove', '#browser', hideSeekbar); +$(document).on('mousemove', '#properties', hideSeekbar); +$(document).on('mousemove', '#controls', hideSeekbar); + +function orderLayers() { + $('.layer').each(function (index) { + const object = canvas.getItemById($(this).attr('data-object')); + canvas.sendToBack(object); + canvas.renderAll(); + objects.splice( + $('.layer').length - index - 1, + 0, + objects.splice( + objects.findIndex((x) => x.id == object.get('id')), + 1 + )[0] + ); + }); + save(); +} + +function handTool() { + if ($(this).hasClass('hand-active')) { + $(this).removeClass('hand-active'); + $(this).find('img').attr('src', 'assets/hand-tool.svg'); + handtool = false; + canvas.defaultCursor = 'default'; + canvas.renderAll(); + } else { + $(this).addClass('hand-active'); + $(this).find('img').attr('src', 'assets/hand-tool-active.svg'); + handtool = true; + canvas.defaultCursor = 'grab'; + canvas.renderAll(); + } +} +$(document).on('click', '#hand-tool', handTool); +// Set defaults +setDuration(10000); +checkDB(); diff --git a/public/motionity/src/js/init.js b/public/motionity/src/js/init.js new file mode 100644 index 000000000..cde44d4a1 --- /dev/null +++ b/public/motionity/src/js/init.js @@ -0,0 +1,1075 @@ +var API_KEY = 'PIXABAY_API'; +var GOOGLE_FONTS_API_KEY = 'GOOGLE_FONTS_API_KEY'; + +// for legacy browsers +const AudioContext = window.AudioContext || window.webkitAudioContext; +const audioContext = new AudioContext(); +var oldsrc, oldobj; +var oldtimelinepos; +var speed = 1; +var page = 1; +var checkstatus = false; +let db = new Localbase('db'); +var wip = false; +var paused = true; +var currenttime = 0; +var timelinetime = 5; +const offset_left = 20; +var duration = 30000; +var keyframes = []; +var p_keyframes = []; +var props = [ + 'left', + 'top', + 'scaleX', + 'scaleY', + 'width', + 'height', + 'angle', + 'opacity', + 'fill', + 'strokeWidth', + 'stroke', + 'shadow.color', + 'shadow.opacity', + 'shadow.offsetX', + 'shadow.offsetY', + 'shadow.blur', + 'charSpacing', + 'lineHeight', +]; +var objects = []; +var o_slider, o_letter_slider, o_line_slider; +var colormode = 'fill'; +var spaceDown = false; +var selectedkeyframe; +var undo = []; +var undoarr = []; +var redo = []; +var groups = []; +var redoarr = []; +var state; +var statearr = []; +var recording = false; +var canvasrecord; +var clipboard; +var focus = false; +var editingpanel = false; +var files = []; +var re = /(?:\.([^.]+))?$/; +var filelist = []; +var timeout; +var spacehold = false; +var spacerelease = false; +var tempselection; +var line_h, line_v; +var tempgroup = []; +var editinggroup = false; +var tempgroupid; +var fontPicker; +var fonts = []; +var seeking = false; +var setting = false; +var handtool = false; +var canvasx = 0; +var canvasy = 0; +var overCanvas = false; +var draggingPanel = false; +var cropping = false; +var cropobj; +var cropscalex; +var cropscaley; +var croptop; +var cropleft; +var layer_count = 1; +var lockmovement = false; +var shiftx = 0; +var shifty = 0; +var editinglayer = false; +var editingproject = false; +var shiftkeys = []; +var shiftdown = false; +var cliptype = 'object'; +var chromaslider, noiseslider, blurslider; +var isChrome = + window.chrome && Object.values(window.chrome).length !== 0; +var eyeDropper; +if (isChrome) { + eyeDropper = new EyeDropper(); +} +var presets = [ + { + name: 'Dribbble shot', + id: 'dribbble', + width: 1600, + height: 1200, + }, + { name: 'Facebook post', id: 'facebook', width: 1280, height: 720 }, + { + name: 'Facebook ad', + id: 'facebook-ad', + width: 1080, + height: 1080, + }, + { name: 'Youtube video', id: 'youtube', width: 1920, height: 1080 }, + { + name: 'Instagram video', + id: 'instagram-id', + width: 1080, + height: 1920, + }, + { + name: 'Instagram stories', + id: 'instagram-stories', + width: 1080, + height: 1920, + }, + { name: 'Twitter video', id: 'twitter', width: 1280, height: 720 }, + { name: 'Snapchat ad', id: 'snapchat', width: 1080, height: 1920 }, + { + name: 'LinkedIn video', + id: 'linkedin', + width: 1920, + height: 1080, + }, + { + name: 'Product Hunt thumbnail', + id: 'product-hunt', + width: 600, + height: 600, + }, + { + name: 'Pinterest ad', + id: 'pinterest', + width: 1080, + height: 1920, + }, +]; +var activepreset = 'custom'; +var uploaded_images = []; +var uploaded_videos = []; +var uploading = false; +var background_audio = false; +var temp_audio = false; +var background_key; +var sliders = []; +var hovertime = 0; +var animatedtext = []; + +// Get list of fonts +$.ajax({ + url: + 'https://www.googleapis.com/webfonts/v1/webfonts?key=' + + GOOGLE_FONTS_API_KEY + + '&sort=alpha', + type: 'GET', + dataType: 'json', // added data type + success: function (response) { + response.items.forEach(function (item) { + fonts.push(item.family); + }); + }, +}); + +// Panel variants +const canvas_panel = + '

Canvas settings

Preset
Size
Color
Duration
'; +const object_panel = + '

Layout

Position
Size
Rotation
'; +const back_panel = + '

Layer

Opacity
Mask
'; +const image_panel = + '

Layer

Opacity
Mask
'; +const selection_panel = + '

Layer

Opacity
Group
Group selection
'; +const group_panel = + '

Layer

Opacity
Mask
Group
Ungroup selection
'; +const other_panel = + '

Layer

Opacity
Mask
'; +const shape_panel = + '

Rectangle

Color
Radius
'; +const path_panel = + '

Shape

Color
'; +const text_panel = + '

Text

Font
Align
Format
Color
Letter
Line
'; +const stroke_panel = + '

Stroke

Type
Color
Width
'; +const shadow_panel = + '

Shadow

Offset
Color
Blur
'; +const image_more_panel = + '

Image

Edit filters
Crop image
'; +const video_more_panel = + '

Video

Edit filters
'; +const animated_text_panel = + '

Text

Content
Set
Font
Color
'; +const start_animation_panel = + '

Start animation

Preset
Easing
Order
Backward
Forward
Order
Letters
Words
Duration
'; +const audio_panel = + '

Audio

Volume
'; + +// Browser variants +const shape_browser = + '

Objects

Shapes

Emojis

'; +const image_browser = + '

Images

Browse millions of high quality images from Pixabay. Use the search bar above or choose from popular categories below.
'; +const text_browser = + '

Text

Basic text

Add a heading
Add a subheading
Add body text
'; +const video_browser = + '

Videos

Browse millions of high quality images from Pixabay. Use the search bar above or choose from popular categories below.
'; +const upload_browser = + '

Uploads

Upload media
Images
Videos
'; +const audio_browser = + '

Audio

Upload audio
Audio provided by Pixabay. Browse millions of assets from Pixabay by clicking here.
'; + +// Text animation list +var text_animation_list = [ + { name: 'fade in', label: 'Fade in', src: 'assets/fade-in.svg' }, + { + name: 'typewriter', + label: 'Typewriter', + src: 'assets/typewriter.svg', + }, + { + name: 'slide top', + label: 'Slide top', + src: 'assets/slide-top.svg', + }, + { + name: 'slide bottom', + label: 'Slide bottom', + src: 'assets/slide-bottom.svg', + }, + { + name: 'slide left', + label: 'Slide left', + src: 'assets/slide-left.svg', + }, + { + name: 'slide right', + label: 'Slide right', + src: 'assets/slide-right.svg', + }, + { name: 'scale', label: 'Scale', src: 'assets/scale.svg' }, + { name: 'shrink', label: 'Shrink', src: 'assets/shrink.svg' }, +]; + +// Shapes list +var shape_grid_items = [ + 'assets/shapes/rectangle.svg', + 'assets/shapes/circle.svg', + 'assets/shapes/triangle.svg', + 'assets/shapes/polygon.svg', + 'assets/shapes/star.svg', + 'assets/thingy.svg', + 'assets/shapes/heart.svg', + 'assets/shapes/arrow.svg', +]; +var emoji_items = [ + 'assets/twemojis/laughing-emoji.png', + 'assets/twemojis/crying-emoji.png', + 'assets/twemojis/surprised-emoji.png', + 'assets/twemojis/smiling-emoji.png', + 'assets/twemojis/tongue-emoji.png', + 'assets/twemojis/heart-eyes-emoji.png', + 'assets/twemojis/heart-kiss-emoji.png', + 'assets/twemojis/sunglasses-cool-emoji.png', + 'assets/twemojis/ghost-emoji.png', + 'assets/twemojis/skull-emoji.png', + 'assets/twemojis/mindblown-emoji.png', + 'assets/twemojis/bomb-emoji.png', + 'assets/twemojis/hundred-100-points-emoji.png', + 'assets/twemojis/thought-balloon-emoji.png', + 'assets/twemojis/wave-emoji.png', + 'assets/twemojis/point-emoji.png', + 'assets/twemojis/thumbs-up-emoji.png', + 'assets/twemojis/clap-emoji.png', + 'assets/twemojis/raising-hands-emoji.png', + 'assets/twemojis/praying-hands-emoji.png', + 'assets/twemojis/nail-polish-emoji.png', + 'assets/twemojis/eyes-emoji.png', + 'assets/twemojis/cat-face-emoji.png', + 'assets/twemojis/dog-face-emoji.png', + 'assets/twemojis/rose-emoji.png', + 'assets/twemojis/tulip-emoji.png', + 'assets/twemojis/pizza-emoji.png', + 'assets/twemojis/construction-emoji.png', + 'assets/twemojis/plane-emoji.png', + 'assets/twemojis/rocket-emoji.png', + 'assets/twemojis/clock-emoji.png', + 'assets/twemojis/star-emoji.png', + 'assets/twemojis/sun-emoji.png', + 'assets/twemojis/moon-emoji.png', + 'assets/twemojis/fire-emoji.png', + 'assets/twemojis/sparkles-emoji.png', + 'assets/twemojis/party-popper-emoji.png', + 'assets/twemojis/gift-emoji.png', + 'assets/twemojis/trophy-emoji.png', + 'assets/twemojis/target-emoji.png', + 'assets/twemojis/gem-emoji.png', + 'assets/twemojis/money-emoji.png', + 'assets/twemojis/pencil-emoji.png', + 'assets/twemojis/graph-emoji.png', + 'assets/twemojis/wip-emoji.png', + 'assets/twemojis/winking-face-emoji.png', + 'assets/twemojis/pleading-face-emoji.png', + 'assets/twemojis/thinking-face-emoji.png', +]; + +// Image list +var image_grid_items = [ + 'https://images.unsplash.com/photo-1609153259378-a8b23c766aec?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1866&q=80', + 'https://images.unsplash.com/photo-1614435082296-ef0cbdb16b70?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=934&q=80', + 'https://images.unsplash.com/photo-1614432254115-7e756705e910?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxMHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', + 'https://images.unsplash.com/photo-1614423234685-544477464e15?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw4fHx8ZW58MHx8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', + 'https://images.unsplash.com/photo-1614357235247-99fabbee67f9?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxNHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', + 'https://images.unsplash.com/photo-1614373371549-c7d2e4885f17?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxOXx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60', +]; +var image_categories = [ + { name: 'background', image: 'assets/background.png' }, + { name: 'wallpaper', image: 'assets/wallpaper.png' }, + { name: 'nature', image: 'assets/nature.png' }, + { name: 'summer', image: 'assets/summer.png' }, + { name: 'beach', image: 'assets/beach.png' }, + { name: 'space', image: 'assets/space.png' }, + { name: 'office', image: 'assets/office.png' }, + { name: 'food', image: 'assets/food.png' }, +]; + +// Video list +var video_categories = [ + { name: 'rain', image: 'assets/rain.png' }, + { name: 'cars', image: 'assets/cars.png' }, + { name: 'meditation', image: 'assets/meditation.png' }, + { name: 'forest', image: 'assets/forest.png' }, + { name: 'animals', image: 'assets/animals.png' }, + { name: 'street', image: 'assets/street.png' }, + { name: 'travel', image: 'assets/travel.png' }, + { name: 'work', image: 'assets/work.png' }, +]; + +// Audio list +var audio_items = [ + { + name: 'Lofi Study', + desc: 'FASSounds', + duration: '2:27', + thumb: 'assets/audio/lofi-thumb.png', + src: 'assets/audio/lofi.mp3', + link: 'https://pixabay.com/users/fassounds-3433550/', + }, + { + name: 'Stomping Rock (Four Shots)', + desc: 'AlexGrohl', + duration: '1:59', + thumb: 'assets/audio/stomping-rock-thumb.png', + src: 'assets/audio/stomping-rock.mp3', + link: 'https://pixabay.com/users/alexgrohl-25289918/', + }, + { + name: 'Everything Feels New', + desc: 'EvgenyBardyuzha', + duration: '1:06', + thumb: 'assets/audio/everything-feels-new-thumb.png', + src: 'assets/audio/everything-feels-new.mp3', + link: 'https://pixabay.com/users/evgenybardyuzha-25235210/', + }, + { + name: 'Both of Us', + desc: 'madiRFAN', + duration: '2:48', + thumb: 'assets/audio/both-of-us-thumb.png', + src: 'assets/audio/both-of-us.mp3', + link: 'https://pixabay.com/users/madirfan-50411/', + }, + { + name: 'The Podcast Intro', + desc: 'Music Unlimited', + duration: '1:51', + thumb: 'assets/audio/the-podcast-intro-thumb.png', + src: 'assets/audio/the-podcast-intro.mp3', + link: 'https://pixabay.com/users/music_unlimited-27600023/', + }, + { + name: 'Epic Cinematic Trailer', + desc: 'PavelYudin', + duration: '2:27', + thumb: 'assets/audio/epic-cinematic-trailer-thumb.png', + src: 'assets/audio/epic-cinematic-trailer.mp3', + link: 'https://pixabay.com/users/pavelyudin-27739282/', + }, + { + name: 'Inspirational Background', + desc: 'AudioCoffee', + duration: '2:19', + thumb: 'assets/audio/inspirational-background-thumb.png', + src: 'assets/audio/inspirational-background.mp3', + link: 'https://pixabay.com/users/audiocoffee-27005420/', + }, + { + name: 'Tropical Summer Music', + desc: 'Music Unlimited', + duration: '2:35', + thumb: 'assets/audio/tropical-summer-music-thumb.png', + src: 'assets/audio/tropical-summer-music.mp3', + link: 'https://pixabay.com/users/music_unlimited-27600023/', + }, +]; + +// Text list +var text_items = { + sansserif: [ + { name: 'Roboto', fontname: 'Roboto' }, + { name: 'Montserrat', fontname: 'Montserrat' }, + { name: 'Poppins', fontname: 'Poppins' }, + ], + serif: [ + { name: 'Playfair Display', fontname: 'Playfair Display' }, + { name: 'Merriweather', fontname: 'Merriweather' }, + { name: 'IBM Plex Serif', fontname: 'IBM Plex Serif' }, + ], + monospace: [ + { name: 'Roboto Mono', fontname: 'Roboto Mono' }, + { name: 'Inconsolata', fontname: 'Inconsolata' }, + { name: 'Source Code Pro', fontname: 'Source Code Pro' }, + ], + handwriting: [ + { name: 'Dancing Script', fontname: 'Dancing Script' }, + { name: 'Pacifico', fontname: 'Pacifico' }, + { name: 'Indie Flower', fontname: 'Indie Flower' }, + ], + display: [ + { name: 'Lobster', fontname: 'Lobster' }, + { name: 'Bebas Neue', fontname: 'Bebas Neue' }, + { name: 'Titan One', fontname: 'Titan One' }, + ], +}; + +WebFont.load({ + google: { + families: ['Syne'], + }, + active: () => {}, +}); + +var webglBackend; +try { + webglBackend = new fabric.WebglFilterBackend(); +} catch (e) { + console.log(e); +} +var canvas2dBackend = new fabric.Canvas2dFilterBackend(); + +fabric.filterBackend = fabric.initFilterBackend(); +fabric.filterBackend = webglBackend; + +// Lottie support +fabric.Lottie = fabric.util.createClass(fabric.Image, { + type: 'lottie', + lockRotation: true, + lockSkewingX: true, + lockSkewingY: true, + srcFromAttribute: false, + + initialize: function (path, options) { + if (!options.width) options.width = 480; + if (!options.height) options.height = 480; + + this.path = path; + this.tmpCanvasEl = fabric.util.createCanvasElement(); + this.tmpCanvasEl.width = options.width; + this.tmpCanvasEl.height = options.height; + + this.lottieItem = bodymovin.loadAnimation({ + renderer: 'canvas', + loop: false, + autoplay: false, + path: path, + rendererSettings: { + context: this.tmpCanvasEl.getContext('2d'), + preserveAspectRatio: 'xMidYMid meet', + }, + }); + + this.lottieItem.addEventListener('enterFrame', (e) => { + this.canvas.requestRenderAll(); + }); + + this.lottieItem.addEventListener('DOMLoaded', () => { + this.lottieItem.goToAndStop(currenttime, false); + this.lottieItem.duration = + this.lottieItem.getDuration(false) * 1000; + this.canvas.requestRenderAll(); + canvas.renderAll(); + canvas.fire('lottie:loaded', { any: 'payload' }); + }); + + this.callSuper('initialize', this.tmpCanvasEl, options); + }, + + goToSeconds: function (seconds) { + this.lottieItem.goToAndStop(seconds, false); + this.canvas.requestRenderAll(); + }, + goToFrame: function (frame) { + this.lottieItem.goToAndStop(frame, true); + }, + getDuration: function () { + return this.lottieItem.getDuration(false); + }, + play: function () { + this.lottieItem.play(); + }, + pause: function () { + this.lottieItem.pause(); + }, + getSrc: function () { + return this.path; + }, +}); + +fabric.Lottie.fromObject = function (_object, callback) { + const object = fabric.util.object.clone(_object); + fabric.Image.prototype._initFilters.call( + object, + object.filters, + function (filters) { + object.filters = filters || []; + fabric.Image.prototype._initFilters.call( + object, + [object.resizeFilter], + function (resizeFilters) { + object.resizeFilter = resizeFilters[0]; + fabric.util.enlivenObjects( + [object.clipPath], + function (enlivedProps) { + object.clipPath = enlivedProps[0]; + const fabricLottie = new fabric.Lottie( + object.src, + object + ); + callback(fabricLottie, false); + } + ); + } + ); + } + ); +}; + +// Initialize canvas +var canvas = new fabric.Canvas('canvas', { + preserveObjectStacking: true, + backgroundColor: '#FFF', + stateful: true, +}); +canvas.selection = false; +canvas.controlsAboveOverlay = true; + +// Customize controls +fabric.Object.prototype.set({ + transparentCorners: false, + borderColor: '#51B9F9', + cornerColor: '#FFF', + borderScaleFactor: 2.5, + cornerStyle: 'circle', + cornerStrokeColor: '#0E98FC', + borderOpacityWhenMoving: 1, +}); + +canvas.selectionColor = 'rgba(46, 115, 252, 0.11)'; +canvas.selectionBorderColor = 'rgba(98, 155, 255, 0.81)'; +canvas.selectionLineWidth = 1.5; + +var img = document.createElement('img'); +img.src = 'assets/middlecontrol.svg'; + +var img2 = document.createElement('img'); +img2.src = 'assets/middlecontrolhoz.svg'; + +var img3 = document.createElement('img'); +img3.src = 'assets/edgecontrol.svg'; + +var img4 = document.createElement('img'); +img4.src = 'assets/rotateicon.svg'; + +function renderIcon(ctx, left, top, styleOverride, fabricObject) { + const wsize = 20; + const hsize = 25; + ctx.save(); + ctx.translate(left, top); + ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle)); + ctx.drawImage(img, -wsize / 2, -hsize / 2, wsize, hsize); + ctx.restore(); +} +function renderIconHoz(ctx, left, top, styleOverride, fabricObject) { + const wsize = 25; + const hsize = 20; + ctx.save(); + ctx.translate(left, top); + ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle)); + ctx.drawImage(img2, -wsize / 2, -hsize / 2, wsize, hsize); + ctx.restore(); +} +function renderIconEdge(ctx, left, top, styleOverride, fabricObject) { + const wsize = 25; + const hsize = 25; + ctx.save(); + ctx.translate(left, top); + ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle)); + ctx.drawImage(img3, -wsize / 2, -hsize / 2, wsize, hsize); + ctx.restore(); +} + +function renderIconRotate( + ctx, + left, + top, + styleOverride, + fabricObject +) { + const wsize = 40; + const hsize = 40; + ctx.save(); + ctx.translate(left, top); + ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle)); + ctx.drawImage(img4, -wsize / 2, -hsize / 2, wsize, hsize); + ctx.restore(); +} +function resetControls() { + fabric.Object.prototype.controls.ml = new fabric.Control({ + x: -0.5, + y: 0, + offsetX: -1, + cursorStyleHandler: + fabric.controlsUtils.scaleSkewCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingXOrSkewingY, + getActionName: fabric.controlsUtils.scaleOrSkewActionName, + render: renderIcon, + }); + + fabric.Object.prototype.controls.mr = new fabric.Control({ + x: 0.5, + y: 0, + offsetX: 1, + cursorStyleHandler: + fabric.controlsUtils.scaleSkewCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingXOrSkewingY, + getActionName: fabric.controlsUtils.scaleOrSkewActionName, + render: renderIcon, + }); + + fabric.Object.prototype.controls.mb = new fabric.Control({ + x: 0, + y: 0.5, + offsetY: 1, + cursorStyleHandler: + fabric.controlsUtils.scaleSkewCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingYOrSkewingX, + getActionName: fabric.controlsUtils.scaleOrSkewActionName, + render: renderIconHoz, + }); + + fabric.Object.prototype.controls.mt = new fabric.Control({ + x: 0, + y: -0.5, + offsetY: -1, + cursorStyleHandler: + fabric.controlsUtils.scaleSkewCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingYOrSkewingX, + getActionName: fabric.controlsUtils.scaleOrSkewActionName, + render: renderIconHoz, + }); + + fabric.Object.prototype.controls.tl = new fabric.Control({ + x: -0.5, + y: -0.5, + cursorStyleHandler: fabric.controlsUtils.scaleCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingEqually, + render: renderIconEdge, + }); + + fabric.Object.prototype.controls.tr = new fabric.Control({ + x: 0.5, + y: -0.5, + cursorStyleHandler: fabric.controlsUtils.scaleCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingEqually, + render: renderIconEdge, + }); + + fabric.Object.prototype.controls.bl = new fabric.Control({ + x: -0.5, + y: 0.5, + cursorStyleHandler: fabric.controlsUtils.scaleCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingEqually, + render: renderIconEdge, + }); + + fabric.Object.prototype.controls.br = new fabric.Control({ + x: 0.5, + y: 0.5, + cursorStyleHandler: fabric.controlsUtils.scaleCursorStyleHandler, + actionHandler: fabric.controlsUtils.scalingEqually, + render: renderIconEdge, + }); + + fabric.Object.prototype.controls.mtr = new fabric.Control({ + x: 0, + y: 0.5, + cursorStyleHandler: fabric.controlsUtils.rotationStyleHandler, + actionHandler: fabric.controlsUtils.rotationWithSnapping, + offsetY: 30, + withConnecton: false, + actionName: 'rotate', + render: renderIconRotate, + }); +} +resetControls(); +var textBoxControls = (fabric.Textbox.prototype.controls = {}); + +textBoxControls.mtr = fabric.Object.prototype.controls.mtr; +textBoxControls.tr = fabric.Object.prototype.controls.tr; +textBoxControls.br = fabric.Object.prototype.controls.br; +textBoxControls.tl = fabric.Object.prototype.controls.tl; +textBoxControls.bl = fabric.Object.prototype.controls.bl; +textBoxControls.mt = fabric.Object.prototype.controls.mt; +textBoxControls.mb = fabric.Object.prototype.controls.mb; + +textBoxControls.ml = new fabric.Control({ + x: -0.5, + y: 0, + offsetX: -1, + cursorStyleHandler: + fabric.controlsUtils.scaleSkewCursorStyleHandler, + actionHandler: fabric.controlsUtils.changeWidth, + actionName: 'resizing', + render: renderIcon, +}); + +textBoxControls.mr = new fabric.Control({ + x: 0.5, + y: 0, + offsetX: 1, + cursorStyleHandler: + fabric.controlsUtils.scaleSkewCursorStyleHandler, + actionHandler: fabric.controlsUtils.changeWidth, + actionName: 'resizing', + render: renderIcon, +}); + +// Get any object by ID +fabric.Canvas.prototype.getItemById = function (name) { + var object = null, + objects = this.getObjects(); + for (var i = 0, len = this.size(); i < len; i++) { + if (objects[i].get('type') == 'group') { + if (objects[i].get('id') && objects[i].get('id') === name) { + object = objects[i]; + break; + } + var wip = i; + for (var o = 0; o < objects[i]._objects.length; o++) { + if ( + objects[wip]._objects[o].id && + objects[wip]._objects[o].id === name + ) { + object = objects[wip]._objects[o]; + break; + } + } + } else if (objects[i].id && objects[i].id === name) { + object = objects[i]; + break; + } + } + return object; +}; + +// Create the artboard +var a_width = 600; +var a_height = 500; +var artboard = new fabric.Rect({ + left: canvas.get('width') / 2 - a_width / 2, + top: canvas.get('height') / 2 - a_height / 2, + width: a_width, + height: a_height, + absolutePositioned: true, + rx: 0, + ry: 0, + fill: '#FFF', + hasControls: true, + transparentCorners: false, + borderColor: '#0E98FC', + cornerColor: '#0E98FC', + cursorWidth: 1, + cursorDuration: 1, + cursorDelay: 250, + id: 'overlay', +}); +canvas.renderAll(); + +// Clip canvas to the artboard +canvas.clipPath = artboard; +canvas.renderAll(); + +// Initialize color picker (fill) +var o_fill = Pickr.create({ + el: '#color-picker-fill', + theme: 'nano', + inline: true, + useAsButton: true, + swatches: null, + default: '#FFFFFF', + showAlways: true, + components: { + preview: true, + opacity: true, + hue: true, + interaction: { + hex: true, + rgba: true, + hsla: false, + hsva: false, + cmyk: false, + input: true, + clear: false, + save: false, + }, + }, +}); + +// Color picker events +o_fill + .on('init', (instance) => { + o_fill.hide(); + }) + .on('change', (instance) => { + if (canvas.getActiveObject()) { + const object = canvas.getActiveObject(); + if (colormode == 'fill') { + $('#object-color-fill input').val( + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + $('#object-color-fill-opacity input').val( + Math.round(o_fill.getColor().toRGBA()[3] * 100 * 100) / 100 + ); + $('#color-fill-side').css( + 'background-color', + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + object.set('fill', o_fill.getColor().toRGBA().toString()); + if (!seeking && !setting) { + newKeyframe( + 'fill', + object, + currenttime, + object.get('fill'), + true + ); + } + } else if (colormode == 'stroke') { + $('#object-color-stroke input').val( + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + $('#object-color-stroke-opacity input').val( + Math.round(o_fill.getColor().toRGBA()[3] * 100 * 100) / 100 + ); + $('#color-stroke-side').css( + 'background-color', + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + object.set('stroke', o_fill.getColor().toRGBA().toString()); + if (!seeking && !setting) { + newKeyframe( + 'stroke', + object, + currenttime, + object.get('stroke'), + true + ); + newKeyframe( + 'strokeWidth', + object, + currenttime, + object.get('strokeWidth'), + true + ); + } + } else if (colormode == 'shadow') { + $('#object-color-shadow input').val( + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + $('#object-color-shadow-opacity input').val( + Math.round(o_fill.getColor().toRGBA()[3] * 100 * 100) / 100 + ); + $('#color-shadow-side').css( + 'background-color', + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + object.set( + 'shadow', + new fabric.Shadow({ + color: o_fill.getColor().toRGBA().toString(), + offsetX: object.shadow.offsetX, + offsetY: object.shadow.offsetY, + blur: object.shadow.blur, + opacity: object.shadow.opacity, + }) + ); + if (!seeking && !setting) { + newKeyframe( + 'shadow.color', + object, + currenttime, + object.shadow.color, + true + ); + } + } else if (colormode == 'chroma') { + var obj = canvas.getActiveObject(); + $('#chroma-color input').val( + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + $('#color-chroma-side').css( + 'background-color', + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + if (obj.filters.find((x) => x.type == 'RemoveColor')) { + obj.filters.find((x) => x.type == 'RemoveColor').color = + o_fill.getColor().toRGBA().toString(); + } + updateChromaValues(); + } else if (colormode == 'text') { + var obj = canvas.getActiveObject(); + $('#text-color input').val( + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + $('#color-text-side').css( + 'background-color', + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + animatedtext + .find((x) => x.id == obj.id) + .setProps( + { fill: o_fill.getColor().toRGBA().toString() }, + canvas + ); + } + canvas.renderAll(); + } else { + if (colormode == 'back') { + $('#canvas-color input').val( + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + $('#canvas-color-opacity input').val( + Math.round(o_fill.getColor().toRGBA()[3] * 100 * 100) / 100 + ); + $('#color-side').css( + 'background-color', + o_fill.getColor().toHEXA().toString().substring(0, 7) + ); + canvas.setBackgroundColor( + o_fill.getColor().toRGBA().toString() + ); + canvas.renderAll(); + } + } + }) + .on('show', (instance) => { + $('.pcr-current-color').html( + "" + ); + }); + +var f = fabric.Image.filters; + +// Canvas recorder initialization +var canvasrecord = new fabric.Canvas('canvasrecord', { + preserveObjectStacking: true, + backgroundColor: '#FFF', + width: artboard.width, + height: artboard.height, +}); + +var timelineslider = document.getElementById('timeline-zoom'); +var t_slider = new RangeSlider(timelineslider, { + design: '2d', + theme: 'default', + handle: 'round', + popup: null, + showMinMaxLabels: false, + unit: '%', + min: 5, + max: 47, + value: 47, + onmove: function (x) { + setTimelineZoom(-1 * (x - 51)); + }, + onfinish: function (x) { + setTimelineZoom(-1 * (x - 51)); + }, + onstart: function (x) {}, +}); + +const selectbox = new SelectionArea({ + class: 'selection-area', + selectables: ['.keyframe'], + container: '#timeline', + // Query selectors for elements from where a selection can be started from. + startareas: ['html'], + + // Query selectors for elements which will be used as boundaries for the selection. + boundaries: ['#timeline'], + + startThreshold: 10, + + allowTouch: true, + + intersect: 'touch', + + overlap: 'invert', + + // Configuration in case a selectable gets just clicked. + singleTap: { + allow: false, + intersect: 'native', + }, + + // Scroll configuration. + scrolling: { + speedDivider: 10, + manualSpeed: 750, + }, +}); + +selectbox + .on('beforestart', (evt) => { + if ( + $(evt.event.target).hasClass('keyframe') || + $(evt.event.target).attr('id') == 'seekbar' || + $(evt.event.target).parent().hasClass('main-row') || + $(evt.event.target).hasClass('main-row') || + $(evt.event.target).hasClass('trim-row') || + evt.event.which === 3 + ) { + return false; + } + }) + .on('start', (evt) => {}) + .on('move', (evt) => {}) + .on('stop', (evt) => { + $('.keyframe-selected').removeClass('keyframe-selected'); + shiftkeys = []; + if (evt.store.selected.length == 0) { + $('.keyframe-selected').removeClass('keyframe-selected'); + } else { + canvas.discardActiveObject(); + canvas.renderAll(); + evt.store.selected.forEach(function (key) { + shiftkeys.push({ + keyframe: key, + offset: $(key).offset().left, + }); + $(key).addClass('keyframe-selected'); + }); + } + }); diff --git a/public/motionity/src/js/libraries/anime.min.js b/public/motionity/src/js/libraries/anime.min.js new file mode 100644 index 000000000..7696a5bcc --- /dev/null +++ b/public/motionity/src/js/libraries/anime.min.js @@ -0,0 +1,8 @@ +/* + * anime.js v3.2.1 + * (c) 2020 Julian Garnier + * Released under the MIT license + * animejs.com + */ + +!function(n,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):n.anime=e()}(this,function(){"use strict";var n={update:null,begin:null,loopBegin:null,changeBegin:null,change:null,changeComplete:null,loopComplete:null,complete:null,loop:1,direction:"normal",autoplay:!0,timelineOffset:0},e={duration:1e3,delay:0,endDelay:0,easing:"easeOutElastic(1, .5)",round:0},t=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],r={CSS:{},springs:{}};function a(n,e,t){return Math.min(Math.max(n,e),t)}function o(n,e){return n.indexOf(e)>-1}function u(n,e){return n.apply(null,e)}var i={arr:function(n){return Array.isArray(n)},obj:function(n){return o(Object.prototype.toString.call(n),"Object")},pth:function(n){return i.obj(n)&&n.hasOwnProperty("totalLength")},svg:function(n){return n instanceof SVGElement},inp:function(n){return n instanceof HTMLInputElement},dom:function(n){return n.nodeType||i.svg(n)},str:function(n){return"string"==typeof n},fnc:function(n){return"function"==typeof n},und:function(n){return void 0===n},nil:function(n){return i.und(n)||null===n},hex:function(n){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(n)},rgb:function(n){return/^rgb/.test(n)},hsl:function(n){return/^hsl/.test(n)},col:function(n){return i.hex(n)||i.rgb(n)||i.hsl(n)},key:function(t){return!n.hasOwnProperty(t)&&!e.hasOwnProperty(t)&&"targets"!==t&&"keyframes"!==t}};function c(n){var e=/\(([^)]+)\)/.exec(n);return e?e[1].split(",").map(function(n){return parseFloat(n)}):[]}function s(n,e){var t=c(n),o=a(i.und(t[0])?1:t[0],.1,100),u=a(i.und(t[1])?100:t[1],.1,100),s=a(i.und(t[2])?10:t[2],.1,100),f=a(i.und(t[3])?0:t[3],.1,100),l=Math.sqrt(u/o),d=s/(2*Math.sqrt(u*o)),p=d<1?l*Math.sqrt(1-d*d):0,v=1,h=d<1?(d*l-f)/p:-f+l;function g(n){var t=e?e*n/1e3:n;return t=d<1?Math.exp(-t*d*l)*(v*Math.cos(p*t)+h*Math.sin(p*t)):(v+h*t)*Math.exp(-t*l),0===n||1===n?n:1-t}return e?g:function(){var e=r.springs[n];if(e)return e;for(var t=0,a=0;;)if(1===g(t+=1/6)){if(++a>=16)break}else a=0;var o=t*(1/6)*1e3;return r.springs[n]=o,o}}function f(n){return void 0===n&&(n=10),function(e){return Math.ceil(a(e,1e-6,1)*n)*(1/n)}}var l,d,p=function(){var n=11,e=1/(n-1);function t(n,e){return 1-3*e+3*n}function r(n,e){return 3*e-6*n}function a(n){return 3*n}function o(n,e,o){return((t(e,o)*n+r(e,o))*n+a(e))*n}function u(n,e,o){return 3*t(e,o)*n*n+2*r(e,o)*n+a(e)}return function(t,r,a,i){if(0<=t&&t<=1&&0<=a&&a<=1){var c=new Float32Array(n);if(t!==r||a!==i)for(var s=0;s=.001?function(n,e,t,r){for(var a=0;a<4;++a){var i=u(e,t,r);if(0===i)return e;e-=(o(e,t,r)-n)/i}return e}(r,l,t,a):0===d?l:function(n,e,t,r,a){for(var u,i,c=0;(u=o(i=e+(t-e)/2,r,a)-n)>0?t=i:e=i,Math.abs(u)>1e-7&&++c<10;);return i}(r,i,i+e,t,a)}}}(),v=(l={linear:function(){return function(n){return n}}},d={Sine:function(){return function(n){return 1-Math.cos(n*Math.PI/2)}},Circ:function(){return function(n){return 1-Math.sqrt(1-n*n)}},Back:function(){return function(n){return n*n*(3*n-2)}},Bounce:function(){return function(n){for(var e,t=4;n<((e=Math.pow(2,--t))-1)/11;);return 1/Math.pow(4,3-t)-7.5625*Math.pow((3*e-2)/22-n,2)}},Elastic:function(n,e){void 0===n&&(n=1),void 0===e&&(e=.5);var t=a(n,1,10),r=a(e,.1,2);return function(n){return 0===n||1===n?n:-t*Math.pow(2,10*(n-1))*Math.sin((n-1-r/(2*Math.PI)*Math.asin(1/t))*(2*Math.PI)/r)}}},["Quad","Cubic","Quart","Quint","Expo"].forEach(function(n,e){d[n]=function(){return function(n){return Math.pow(n,e+2)}}}),Object.keys(d).forEach(function(n){var e=d[n];l["easeIn"+n]=e,l["easeOut"+n]=function(n,t){return function(r){return 1-e(n,t)(1-r)}},l["easeInOut"+n]=function(n,t){return function(r){return r<.5?e(n,t)(2*r)/2:1-e(n,t)(-2*r+2)/2}},l["easeOutIn"+n]=function(n,t){return function(r){return r<.5?(1-e(n,t)(1-2*r))/2:(e(n,t)(2*r-1)+1)/2}}}),l);function h(n,e){if(i.fnc(n))return n;var t=n.split("(")[0],r=v[t],a=c(n);switch(t){case"spring":return s(n,e);case"cubicBezier":return u(p,a);case"steps":return u(f,a);default:return u(r,a)}}function g(n){try{return document.querySelectorAll(n)}catch(n){return}}function m(n,e){for(var t=n.length,r=arguments.length>=2?arguments[1]:void 0,a=[],o=0;o1&&(t-=1),t<1/6?n+6*(e-n)*t:t<.5?e:t<2/3?n+(e-n)*(2/3-t)*6:n}if(0==u)e=t=r=i;else{var f=i<.5?i*(1+u):i+u-i*u,l=2*i-f;e=s(l,f,o+1/3),t=s(l,f,o),r=s(l,f,o-1/3)}return"rgba("+255*e+","+255*t+","+255*r+","+c+")"}(n):void 0;var e,t,r,a}function C(n){var e=/[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(n);if(e)return e[1]}function P(n,e){return i.fnc(n)?n(e.target,e.id,e.total):n}function I(n,e){return n.getAttribute(e)}function D(n,e,t){if(M([t,"deg","rad","turn"],C(e)))return e;var a=r.CSS[e+t];if(!i.und(a))return a;var o=document.createElement(n.tagName),u=n.parentNode&&n.parentNode!==document?n.parentNode:document.body;u.appendChild(o),o.style.position="absolute",o.style.width=100+t;var c=100/o.offsetWidth;u.removeChild(o);var s=c*parseFloat(e);return r.CSS[e+t]=s,s}function B(n,e,t){if(e in n.style){var r=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),a=n.style[e]||getComputedStyle(n).getPropertyValue(r)||"0";return t?D(n,a,t):a}}function T(n,e){return i.dom(n)&&!i.inp(n)&&(!i.nil(I(n,e))||i.svg(n)&&n[e])?"attribute":i.dom(n)&&M(t,e)?"transform":i.dom(n)&&"transform"!==e&&B(n,e)?"css":null!=n[e]?"object":void 0}function E(n){if(i.dom(n)){for(var e,t=n.style.transform||"",r=/(\w+)\(([^)]*)\)/g,a=new Map;e=r.exec(t);)a.set(e[1],e[2]);return a}}function F(n,e,t,r){var a,u=o(e,"scale")?1:0+(o(a=e,"translate")||"perspective"===a?"px":o(a,"rotate")||o(a,"skew")?"deg":void 0),i=E(n).get(e)||u;return t&&(t.transforms.list.set(e,i),t.transforms.last=e),r?D(n,i,r):i}function A(n,e,t,r){switch(T(n,e)){case"transform":return F(n,e,r,t);case"css":return B(n,e,t);case"attribute":return I(n,e);default:return n[e]||0}}function N(n,e){var t=/^(\*=|\+=|-=)/.exec(n);if(!t)return n;var r=C(n)||0,a=parseFloat(e),o=parseFloat(n.replace(t[0],""));switch(t[0][0]){case"+":return a+o+r;case"-":return a-o+r;case"*":return a*o+r}}function S(n,e){if(i.col(n))return O(n);if(/\s/g.test(n))return n;var t=C(n),r=t?n.substr(0,n.length-t.length):n;return e?r+e:r}function L(n,e){return Math.sqrt(Math.pow(e.x-n.x,2)+Math.pow(e.y-n.y,2))}function j(n){for(var e,t=n.points,r=0,a=0;a0&&(r+=L(e,o)),e=o}return r}function q(n){if(n.getTotalLength)return n.getTotalLength();switch(n.tagName.toLowerCase()){case"circle":return o=n,2*Math.PI*I(o,"r");case"rect":return 2*I(a=n,"width")+2*I(a,"height");case"line":return L({x:I(r=n,"x1"),y:I(r,"y1")},{x:I(r,"x2"),y:I(r,"y2")});case"polyline":return j(n);case"polygon":return t=(e=n).points,j(e)+L(t.getItem(t.numberOfItems-1),t.getItem(0))}var e,t,r,a,o}function H(n,e){var t=e||{},r=t.el||function(n){for(var e=n.parentNode;i.svg(e)&&i.svg(e.parentNode);)e=e.parentNode;return e}(n),a=r.getBoundingClientRect(),o=I(r,"viewBox"),u=a.width,c=a.height,s=t.viewBox||(o?o.split(" "):[0,0,u,c]);return{el:r,viewBox:s,x:s[0]/1,y:s[1]/1,w:u,h:c,vW:s[2],vH:s[3]}}function V(n,e,t){function r(t){void 0===t&&(t=0);var r=e+t>=1?e+t:0;return n.el.getPointAtLength(r)}var a=H(n.el,n.svg),o=r(),u=r(-1),i=r(1),c=t?1:a.w/a.vW,s=t?1:a.h/a.vH;switch(n.property){case"x":return(o.x-a.x)*c;case"y":return(o.y-a.y)*s;case"angle":return 180*Math.atan2(i.y-u.y,i.x-u.x)/Math.PI}}function $(n,e){var t=/[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g,r=S(i.pth(n)?n.totalLength:n,e)+"";return{original:r,numbers:r.match(t)?r.match(t).map(Number):[0],strings:i.str(n)||e?r.split(t):[]}}function W(n){return m(n?y(i.arr(n)?n.map(b):b(n)):[],function(n,e,t){return t.indexOf(n)===e})}function X(n){var e=W(n);return e.map(function(n,t){return{target:n,id:t,total:e.length,transforms:{list:E(n)}}})}function Y(n,e){var t=x(e);if(/^spring/.test(t.easing)&&(t.duration=s(t.easing)),i.arr(n)){var r=n.length;2===r&&!i.obj(n[0])?n={value:n}:i.fnc(e.duration)||(t.duration=e.duration/r)}var a=i.arr(n)?n:[n];return a.map(function(n,t){var r=i.obj(n)&&!i.pth(n)?n:{value:n};return i.und(r.delay)&&(r.delay=t?0:e.delay),i.und(r.endDelay)&&(r.endDelay=t===a.length-1?e.endDelay:0),r}).map(function(n){return k(n,t)})}function Z(n,e){var t=[],r=e.keyframes;for(var a in r&&(e=k(function(n){for(var e=m(y(n.map(function(n){return Object.keys(n)})),function(n){return i.key(n)}).reduce(function(n,e){return n.indexOf(e)<0&&n.push(e),n},[]),t={},r=function(r){var a=e[r];t[a]=n.map(function(n){var e={};for(var t in n)i.key(t)?t==a&&(e.value=n[t]):e[t]=n[t];return e})},a=0;a0?requestAnimationFrame(e):void 0}return"undefined"!=typeof document&&document.addEventListener("visibilitychange",function(){en.suspendWhenDocumentHidden&&(nn()?n=cancelAnimationFrame(n):(K.forEach(function(n){return n._onDocumentVisibility()}),U()))}),function(){n||nn()&&en.suspendWhenDocumentHidden||!(K.length>0)||(n=requestAnimationFrame(e))}}();function nn(){return!!document&&document.hidden}function en(t){void 0===t&&(t={});var r,o=0,u=0,i=0,c=0,s=null;function f(n){var e=window.Promise&&new Promise(function(n){return s=n});return n.finished=e,e}var l,d,p,v,h,g,y,b,M=(d=w(n,l=t),p=w(e,l),v=Z(p,l),h=X(l.targets),g=_(h,v),y=R(g,p),b=J,J++,k(d,{id:b,children:[],animatables:h,animations:g,duration:y.duration,delay:y.delay,endDelay:y.endDelay}));f(M);function x(){var n=M.direction;"alternate"!==n&&(M.direction="normal"!==n?"normal":"reverse"),M.reversed=!M.reversed,r.forEach(function(n){return n.reversed=M.reversed})}function O(n){return M.reversed?M.duration-n:n}function C(){o=0,u=O(M.currentTime)*(1/en.speed)}function P(n,e){e&&e.seek(n-e.timelineOffset)}function I(n){for(var e=0,t=M.animations,r=t.length;e2||(b=Math.round(b*p)/p)),v.push(b)}var k=d.length;if(k){g=d[0];for(var O=0;O0&&(M.began=!0,D("begin")),!M.loopBegan&&M.currentTime>0&&(M.loopBegan=!0,D("loopBegin")),d<=t&&0!==M.currentTime&&I(0),(d>=l&&M.currentTime!==e||!e)&&I(e),d>t&&d=e&&(u=0,M.remaining&&!0!==M.remaining&&M.remaining--,M.remaining?(o=i,D("loopComplete"),M.loopBegan=!1,"alternate"===M.direction&&x()):(M.paused=!0,M.completed||(M.completed=!0,D("loopComplete"),D("complete"),!M.passThrough&&"Promise"in window&&(s(),f(M)))))}return M.reset=function(){var n=M.direction;M.passThrough=!1,M.currentTime=0,M.progress=0,M.paused=!0,M.began=!1,M.loopBegan=!1,M.changeBegan=!1,M.completed=!1,M.changeCompleted=!1,M.reversePlayback=!1,M.reversed="reverse"===n,M.remaining=M.loop,r=M.children;for(var e=c=r.length;e--;)M.children[e].reset();(M.reversed&&!0!==M.loop||"alternate"===n&&1===M.loop)&&M.remaining++,I(M.reversed?M.duration:0)},M._onDocumentVisibility=C,M.set=function(n,e){return z(n,e),M},M.tick=function(n){i=n,o||(o=i),B((i+(u-o))*en.speed)},M.seek=function(n){B(O(n))},M.pause=function(){M.paused=!0,C()},M.play=function(){M.paused&&(M.completed&&M.reset(),M.paused=!1,K.push(M),C(),U())},M.reverse=function(){x(),M.completed=!M.reversed,C()},M.restart=function(){M.reset(),M.play()},M.remove=function(n){rn(W(n),M)},M.reset(),M.autoplay&&M.play(),M}function tn(n,e){for(var t=e.length;t--;)M(n,e[t].animatable.target)&&e.splice(t,1)}function rn(n,e){var t=e.animations,r=e.children;tn(n,t);for(var a=r.length;a--;){var o=r[a],u=o.animations;tn(n,u),u.length||o.children.length||r.splice(a,1)}t.length||r.length||e.pause()}return en.version="3.2.1",en.speed=1,en.suspendWhenDocumentHidden=!0,en.running=K,en.remove=function(n){for(var e=W(n),t=K.length;t--;)rn(e,K[t])},en.get=A,en.set=z,en.convertPx=D,en.path=function(n,e){var t=i.str(n)?g(n)[0]:n,r=e||100;return function(n){return{property:n,el:t,svg:H(t),totalLength:q(t)*(r/100)}}},en.setDashoffset=function(n){var e=q(n);return n.setAttribute("stroke-dasharray",e),e},en.stagger=function(n,e){void 0===e&&(e={});var t=e.direction||"normal",r=e.easing?h(e.easing):null,a=e.grid,o=e.axis,u=e.from||0,c="first"===u,s="center"===u,f="last"===u,l=i.arr(n),d=l?parseFloat(n[0]):parseFloat(n),p=l?parseFloat(n[1]):0,v=C(l?n[1]:n)||0,g=e.start||0+(l?d:0),m=[],y=0;return function(n,e,i){if(c&&(u=0),s&&(u=(i-1)/2),f&&(u=i-1),!m.length){for(var h=0;h-1&&K.splice(o,1);for(var s=0;s_)for(var C=1,S=d.length;C/g,">")},graphemeSplit:function(t){var e,i=0,r=[];for(i=0;it.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}}}("undefined"!=typeof exports?exports:this),function(t){"use strict";var f=t.fabric||(t.fabric={});function d(t){this.status=t,this.points=[]}f.Intersection?f.warn("fabric.Intersection is already defined"):(f.Intersection=d,f.Intersection.prototype={constructor:d,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},f.Intersection.intersectLineLine=function(t,e,i,r){var n,s=(r.x-i.x)*(t.y-i.y)-(r.y-i.y)*(t.x-i.x),o=(e.x-t.x)*(t.y-i.y)-(e.y-t.y)*(t.x-i.x),a=(r.y-i.y)*(e.x-t.x)-(r.x-i.x)*(e.y-t.y);if(0!==a){var h=s/a,c=o/a;0<=h&&h<=1&&0<=c&&c<=1?(n=new d("Intersection")).appendPoint(new f.Point(t.x+h*(e.x-t.x),t.y+h*(e.y-t.y))):n=new d}else n=new d(0===s||0===o?"Coincident":"Parallel");return n},f.Intersection.intersectLinePolygon=function(t,e,i){var r,n,s,o,a=new d,h=i.length;for(o=0;o=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=o.offsetX,c.y-=o.offsetY,c}function m(t){return t.flipX&&!t.flipY||!t.flipX&&t.flipY}function b(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function u(t,e,i,r){var n,s=e.target,o=s._getTransformedDimensions(0,s.skewY),a=A(e,e.originX,e.originY,i,r),h=Math.abs(2*a.x)-o.x,c=s.skewX;h<2?n=0:(n=v(Math.atan2(h/s.scaleX,o.y/s.scaleY)),e.originX===f&&e.originY===p&&(n=-n),e.originX===g&&e.originY===d&&(n=-n),m(s)&&(n=-n));var l=c!==n;if(l){var u=s._getTransformedDimensions().y;s.set("skewX",n),b(s,"skewY","scaleY","y",u),O("skewing",E(t,e,i,r))}return l}function y(t,e,i,r){var n,s=e.target,o=s._getTransformedDimensions(s.skewX,0),a=A(e,e.originX,e.originY,i,r),h=Math.abs(2*a.y)-o.y,c=s.skewY;h<2?n=0:(n=v(Math.atan2(h/s.scaleY,o.x/s.scaleX)),e.originX===f&&e.originY===p&&(n=-n),e.originX===g&&e.originY===d&&(n=-n),m(s)&&(n=-n));var l=c!==n;if(l){var u=s._getTransformedDimensions().x;s.set("skewY",n),b(s,"skewX","scaleX","x",u),O("skewing",E(t,e,i,r))}return l}function _(t,e,i,r,n){n=n||{};var s,o,a,h,c,l,u=e.target,f=u.lockScalingX,d=u.lockScalingY,g=n.by,p=k(t,u),v=D(u,g,p),m=e.gestureScale;if(v)return!1;if(m)o=e.scaleX*m,a=e.scaleY*m;else{if(s=A(e,e.originX,e.originY,i,r),c="y"!==g?w(s.x):1,l="x"!==g?w(s.y):1,e.signX||(e.signX=c),e.signY||(e.signY=l),u.lockScalingFlip&&(e.signX!==c||e.signY!==l))return!1;if(h=u._getTransformedDimensions(),p&&!g){var b,y=Math.abs(s.x)+Math.abs(s.y),_=e.original,x=y/(Math.abs(h.x*_.scaleX/u.scaleX)+Math.abs(h.y*_.scaleY/u.scaleY));o=_.scaleX*x,a=_.scaleY*x}else o=Math.abs(s.x*u.scaleX/h.x),a=Math.abs(s.y*u.scaleY/h.y);P(e)&&(o*=2,a*=2),e.signX!==c&&"y"!==g&&(e.originX=T[e.originX],o*=-1,e.signX=c),e.signY!==l&&"x"!==g&&(e.originY=T[e.originY],a*=-1,e.signY=l)}var C=u.scaleX,S=u.scaleY;return g?("x"===g&&u.set("scaleX",o),"y"===g&&u.set("scaleY",a)):(!f&&u.set("scaleX",o),!d&&u.set("scaleY",a)),(b=C!==u.scaleX||S!==u.scaleY)&&O("scaling",E(t,e,i,r)),b}n.scaleCursorStyleHandler=function(t,e,i){var r=k(t,i),n="";if(0!==e.x&&0===e.y?n="x":0===e.x&&0!==e.y&&(n="y"),D(i,n,r))return"not-allowed";var s=a(i,e);return o[s]+"-resize"},n.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var n=a(i,e)%4;return s[n]+"-resize"},n.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?n.skewCursorStyleHandler(t,e,i):n.scaleCursorStyleHandler(t,e,i)},n.rotationWithSnapping=c(function(t,e,i,r){var n=e,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),c=Math.atan2(r-o.y,i-o.x),l=v(c-h+n.theta);if(0o.r2,c=this.gradientTransform?this.gradientTransform.concat():fabric.iMatrix.concat(),l=-this.offsetX,u=-this.offsetY,f=!!e.additionalTransform,d="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(a.sort(function(t,e){return t.offset-e.offset}),"objectBoundingBox"===d?(l/=t.width,u/=t.height):(l+=t.width/2,u+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(l-=t.pathOffset.x,u-=t.pathOffset.y),c[4]-=l,c[5]-=u,s='id="SVGID_'+this.id+'" gradientUnits="'+d+'"',s+=' gradientTransform="'+(f?e.additionalTransform+" ":"")+fabric.util.matrixToSVG(c)+'" ',"linear"===this.type?n=["\n']:"radial"===this.type&&(n=["\n']),"radial"===this.type){if(h)for((a=a.concat()).reverse(),i=0,r=a.length;i\n')}return n.push("linear"===this.type?"\n":"\n"),n.join("")},toLive:function(t){var e,i,r,n=fabric.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(e=t.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}})}(),function(t){"use strict";var o=t.fabric||(t.fabric={}),a=o.util.toFixed;o.Shadow?o.warn("fabric.Shadow is already defined."):(o.Shadow=o.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var e in"string"==typeof t&&(t=this._parseShadow(t)),t)this[e]=t[e];this.id=o.Object.__uid++},_parseShadow:function(t){var e=t.trim(),i=o.Shadow.reOffsetsAndBlur.exec(e)||[];return{color:(e.replace(o.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseInt(i[1],10)||0,offsetY:parseInt(i[2],10)||0,blur:parseInt(i[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var e=40,i=40,r=o.Object.NUM_FRACTION_DIGITS,n=o.util.rotateVector({x:this.offsetX,y:this.offsetY},o.util.degreesToRadians(-t.angle)),s=new o.Color(this.color);return t.width&&t.height&&(e=100*a((Math.abs(n.x)+this.blur)/t.width,r)+20,i=100*a((Math.abs(n.y)+this.blur)/t.height,r)+20),t.flipX&&(n.x*=-1),t.flipY&&(n.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var e={},i=o.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach(function(t){this[t]!==i[t]&&(e[t]=this[t])},this),e}}),o.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:px)?(?:\s?|$))?(-?\d+(?:px)?(?:\s?|$))?(\d+(?:px)?)?(?:\s?|$)(?:$|\s)/)}("undefined"!=typeof exports?exports:this),function(){"use strict";if(fabric.StaticCanvas)fabric.warn("fabric.StaticCanvas is already defined.");else{var n=fabric.util.object.extend,t=fabric.util.getElementOffset,c=fabric.util.removeFromArray,a=fabric.util.toFixed,s=fabric.util.transformPoint,o=fabric.util.invertTransform,i=fabric.util.getNodeCanvas,r=fabric.util.createCanvasElement,e=new Error("Could not initialize `canvas` element");fabric.StaticCanvas=fabric.util.createClass(fabric.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:fabric.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return 1!==fabric.devicePixelRatio&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?fabric.devicePixelRatio:1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=fabric.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=t(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(r,t,n,s){return"string"==typeof t?fabric.util.loadImage(t,function(t,e){if(t){var i=new fabric.Image(t,s);(this[r]=i).canvas=this}n&&n(t,e)},this,s&&s.crossOrigin):(s&&t.setOptions(s),(this[r]=t)&&(t.canvas=this),n&&n(t,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=r();if(!t)throw e;if(t.style||(t.style={}),void 0===t.getContext)throw e;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=fabric.util.getById(t)||this._createCanvasElement(),fabric.util.addClass(this.lowerCanvasEl,"lower-canvas"),this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,n=e.height||this.height,s='viewBox="0 0 '+this.width+" "+this.height+'" ',o=fabric.Object.NUM_FRACTION_DIGITS;e.viewBox?s='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,s='viewBox="'+a(-i[4]/i[0],o)+" "+a(-i[5]/i[3],o)+" "+a(this.width/i[0],o)+" "+a(this.height/i[3],o)+'" '),t.push("\n',"Created with Fabric.js ",fabric.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+fabric.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var s=this;return["background","overlay"].map(function(t){var e=s[t+"Color"];if(e&&e.toLive){var i=s[t+"Vpt"],r=s.viewportTransform,n={width:s.width/(i?r[0]:1),height:s.height/(i?r[3]:1)};return e.toSVG(n,{additionalTransform:i?fabric.util.matrixToSVG(r):""})}}).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",c={},l=fabric.fontPaths,u=[];for(this._objects.forEach(function t(e){u.push(e),e._objects&&e._objects.forEach(t)}),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,i,r,n=this._activeObject;if(t===n&&"activeSelection"===t.type)for(e=(r=n._objects).length;e--;)i=r[e],c(this._objects,i),this._objects.unshift(i);else c(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,i,r,n=this._activeObject;if(t===n&&"activeSelection"===t.type)for(r=n._objects,e=0;e"}}),n(fabric.StaticCanvas.prototype,fabric.Observable),n(fabric.StaticCanvas.prototype,fabric.Collection),n(fabric.StaticCanvas.prototype,fabric.DataURLExporter),n(fabric.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=r();if(!e||!e.getContext)return null;var i=e.getContext("2d");if(!i)return null;switch(t){case"setLineDash":return void 0!==i.setLineDash;default:return null}}}),fabric.StaticCanvas.prototype.toJSON=fabric.StaticCanvas.prototype.toObject,fabric.isLikelyNode&&(fabric.StaticCanvas.prototype.createPNGStream=function(){var t=i(this.lowerCanvasEl);return t&&t.createPNGStream()},fabric.StaticCanvas.prototype.createJPEGStream=function(t){var e=i(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),fabric.BaseBrush=fabric.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,_setBrushStyles:function(){var t=this.canvas.contextTop;t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,fabric.StaticCanvas.supports("setLineDash")&&t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=fabric.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new fabric.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0}}),fabric.PencilBrush=fabric.util.createClass(fabric.BaseBrush,{decimate:.4,initialize:function(t){this.canvas=t,this._points=[]},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&this._captureDrawingPath(t)&&1t[e-2].x?1:n.x===t[e-2].x?0:-1,h=n.y>t[e-2].y?1:n.y===t[e-2].y?0:-1),i.push("L ",n.x+a*r," ",n.y+h*r),i},createPath:function(t){var e=new fabric.Path(t,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeMiterLimit:this.strokeMiterLimit,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray});return this.shadow&&(this.shadow.affectStroke=!0,e.shadow=new fabric.Shadow(this.shadow)),e},decimatePoints:function(t,e){if(t.length<=2)return t;var i,r=this.canvas.getZoom(),n=Math.pow(e/r,2),s=t.length-1,o=t[0],a=[o];for(i=1;i"},getObjectScaling:function(){var t=x.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();e*=r*n,i*=r*n}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,e){var i="scaleX"===t||"scaleY"===t,r=this[t]!==e,n=!1;return i&&(e=this._constrainScale(e)),"scaleX"===t&&e<0?(this.flipX=!this.flipX,e*=-1):"scaleY"===t&&e<0?(this.flipY=!this.flipY,e*=-1):"shadow"!==t||!e||e instanceof x.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",e):e=new x.Shadow(e),this[t]=e,r&&(n=this.group&&this.group.isOnACache(),-1=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,i,r){var n=this._getCoords(i,r),s=(e=e||this._getImageLines(n),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some(function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y})||(!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t))},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every(function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)})&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,n,s=0;for(var o in e)if(!((n=e[o]).o.y=t.y&&n.d.y>=t.y||(n.o.x===n.d.x&&n.o.x>=t.x?r=n.o.x:(0,i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(t.y-0*t.x-(n.o.y-i*n.o.x))/(0-i)),r>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(t,e){var i=this.getCoords(t,e);return c.makeBoundingBoxFromPoints(i)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=n,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,n=(e=e||{}).noStyle,s=e.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,c=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",l=h&&h.absolutePositioned,u=this.stroke,f=this.fill,d=this.shadow,g=[],p=t.indexOf("COMMON_PARTS"),v=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+fabric.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),l&&g.push("\n"),g.push("\n"),i=[o,c,n?"":this.addPaintOrder()," ",v?'transform="'+v+'" ':""].join(""),t[p]=i,f&&f.toLive&&g.push(f.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),d&&g.push(d.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),l&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var n=fabric.util.object.extend,r="stateProperties";function s(e,t,i){var r={};i.forEach(function(t){r[t]=e[t]}),n(e[t],r,!0)}fabric.util.object.extend(fabric.Object.prototype,{hasStateChanged:function(t){var e="_"+(t=t||r);return Object.keys(this[e]).length\n']}}),s.Line.ATTRIBUTE_NAMES=s.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),s.Line.fromElement=function(t,e,i){i=i||{};var r=s.parseAttributes(t,s.Line.ATTRIBUTE_NAMES),n=[r.x1||0,r.y1||0,r.x2||0,r.y2||0];e(new s.Line(n,o(r,i)))},s.Line.fromObject=function(t,e){var i=r(t,!0);i.points=[t.x1,t.y1,t.x2,t.y2],s.Object._fromObject("Line",i,function(t){delete t.points,e&&e(t)},"points")})}("undefined"!=typeof exports?exports:this),function(t){"use strict";var a=t.fabric||(t.fabric={}),h=Math.PI;a.Circle?a.warn("fabric.Circle is already defined."):(a.Circle=a.util.createClass(a.Object,{type:"circle",radius:0,startAngle:0,endAngle:2*h,cacheProperties:a.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,e=(this.endAngle-this.startAngle)%(2*h);if(0===e)t=["\n'];else{var i=a.util.cos(this.startAngle)*this.radius,r=a.util.sin(this.startAngle)*this.radius,n=a.util.cos(this.endAngle)*this.radius,s=a.util.sin(this.endAngle)*this.radius,o=h\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,this.startAngle,this.endAngle,!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),a.Circle.ATTRIBUTE_NAMES=a.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),a.Circle.fromElement=function(t,e){var i,r=a.parseAttributes(t,a.Circle.ATTRIBUTE_NAMES);if(!("radius"in(i=r)&&0<=i.radius))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,e(new a.Circle(r))},a.Circle.fromObject=function(t,e){return a.Object._fromObject("Circle",t,e)})}("undefined"!=typeof exports?exports:this),function(t){"use strict";var r=t.fabric||(t.fabric={});r.Triangle?r.warn("fabric.Triangle is already defined"):(r.Triangle=r.util.createClass(r.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_renderDashedStroke:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),r.util.drawDashedLine(t,-e,i,0,-i,this.strokeDashArray),r.util.drawDashedLine(t,0,-i,e,i,this.strokeDashArray),r.util.drawDashedLine(t,e,i,-e,i,this.strokeDashArray),t.closePath()},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),r.Triangle.fromObject=function(t,e){return r.Object._fromObject("Triangle",t,e)})}("undefined"!=typeof exports?exports:this),function(t){"use strict";var r=t.fabric||(t.fabric={}),e=2*Math.PI;r.Ellipse?r.warn("fabric.Ellipse is already defined."):(r.Ellipse=r.util.createClass(r.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:r.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,e,!1),t.restore(),this._renderPaintInOrder(t)}}),r.Ellipse.ATTRIBUTE_NAMES=r.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),r.Ellipse.fromElement=function(t,e){var i=r.parseAttributes(t,r.Ellipse.ATTRIBUTE_NAMES);i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,e(new r.Ellipse(i))},r.Ellipse.fromObject=function(t,e){return r.Object._fromObject("Ellipse",t,e)})}("undefined"!=typeof exports?exports:this),function(t){"use strict";var s=t.fabric||(t.fabric={}),o=s.util.object.extend;s.Rect?s.warn("fabric.Rect is already defined"):(s.Rect=s.util.createClass(s.Object,{stateProperties:s.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:s.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+r-e,o),a&&t.bezierCurveTo(s+r-h*e,o,s+r,o+h*i,s+r,o+i),t.lineTo(s+r,o+n-i),a&&t.bezierCurveTo(s+r,o+n-h*i,s+r-h*e,o+n,s+r-e,o+n),t.lineTo(s+e,o+n),a&&t.bezierCurveTo(s+h*e,o+n,s,o+n-h*i,s,o+n-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},_renderDashedStroke:function(t){var e=-this.width/2,i=-this.height/2,r=this.width,n=this.height;t.beginPath(),s.util.drawDashedLine(t,e,i,e+r,i,this.strokeDashArray),s.util.drawDashedLine(t,e+r,i,e+r,i+n,this.strokeDashArray),s.util.drawDashedLine(t,e+r,i+n,e,i+n,this.strokeDashArray),s.util.drawDashedLine(t,e,i+n,e,i,this.strokeDashArray),t.closePath()},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),s.Rect.ATTRIBUTE_NAMES=s.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),s.Rect.fromElement=function(t,e,i){if(!t)return e(null);i=i||{};var r=s.parseAttributes(t,s.Rect.ATTRIBUTE_NAMES);r.left=r.left||0,r.top=r.top||0,r.height=r.height||0,r.width=r.width||0;var n=new s.Rect(o(i?s.util.object.clone(i):{},r));n.visible=n.visible&&0\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map(function(t){return t.slice()})})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=f.Object.NUM_FRACTION_DIGITS;return" translate("+e(-this.pathOffset.x,t)+", "+e(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,e,i=[],r=[],n=0,s=0,o=0,a=0,h=0,c=this.path.length;h"},addWithUpdate:function(t){return this._restoreObjectsState(),c.util.resetObjectTransform(this),t&&(this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},removeWithUpdate:function(t){return this._restoreObjectsState(),c.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,e){var i=this._objects.length;if(this.useSetOnGroup)for(;i--;)this._objects[i].setOnGroup(t,e);if("canvas"===t)for(;i--;)this._objects[i]._set(t,e);c.Object.prototype._set.call(this,t,e)},toObject:function(r){var n=this.includeDefaultValues,t=this._objects.map(function(t){var e=t.includeDefaultValues;t.includeDefaultValues=n;var i=t.toObject(r);return t.includeDefaultValues=e,i}),e=c.Object.prototype.toObject.call(this,r);return e.objects=t,e},toDatalessObject:function(r){var t,e=this.sourcePath;if(e)t=e;else{var n=this.includeDefaultValues;t=this._objects.map(function(t){var e=t.includeDefaultValues;t.includeDefaultValues=n;var i=t.toDatalessObject(r);return t.includeDefaultValues=e,i})}var i=c.Object.prototype.toDatalessObject.call(this,r);return i.objects=t,i},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=c.Object.prototype.shouldCache.call(this);if(t)for(var e=0,i=this._objects.length;e\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var c=this.fill;this.fill=null,t=["\t\n'],this.fill=c}return e="fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,i,r){return fabric.util.loadImage(t,function(t,e){this.setElement(t,r),this._setWidthHeight(),i&&i(this,e)},this,r&&r.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||e=t;for(var a=["highp","mediump","lowp"],h=0;h<3;h++)if(void 0,i="precision "+a[h]+" float;\nvoid main(){}",r=(e=s).createShader(e.FRAGMENT_SHADER),e.shaderSource(r,i),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)){fabric.webGlPrecision=a[h];break}}return this.isSupported=o},(fabric.WebglFilterBackend=t).prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=fabric.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(fabric.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=copyGLTo2DPutImageData);var h,c,l={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),copyGLTo2DDrawImage.call(l,this.gl,l),c=window.performance.now()-h,h=window.performance.now(),copyGLTo2DPutImageData.call(l,this.gl,l),window.performance.now()-h 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var e,i,r,n,s,o,a,h=t.imageData.data,c=h.length,l=1-this.alpha;e=(a=new f.Color(this.color).getSource())[0]*this.alpha,i=a[1]*this.alpha,r=a[2]*this.alpha;for(var u=0;u'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){t.textBaseline="alphabetic",t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;ethis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),n=fabric.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+fabric.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},c=this.canvas.getRetinaScaling(),l=this.canvas.upperCanvasEl,u=l.width/c,f=l.height/c,d=u-s,g=f-s,p=l.clientWidth/u,v=l.clientHeight/f;return h=fabric.util.transformPoint(h,a),(h=fabric.util.transformPoint(h,this.canvas.viewportTransform)).x*=p,h.y*=v,h.x<0&&(h.x=0),h.x>d&&(h.x=d),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,n=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,c=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}})}(),fabric.util.object.extend(fabric.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e=this.getLocalPointer(t),i=0,r=0,n=0,s=0,o=0,a=0,h=this._textLines.length;athis._text.length&&(a=this._text.length),a}}),fabric.util.object.extend(fabric.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=fabric.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",fabric.document.body.appendChild(this.hiddenTextarea),fabric.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),fabric.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),fabric.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),fabric.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),fabric.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),fabric.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),fabric.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),fabric.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),fabric.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(fabric.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){if(t.keyCode in this.keysMap)this[this.keysMap[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown&&(t.ctrlKey||t.metaKey)))return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),33<=t.keyCode&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,c=a.length,l=c-h,u=this.selectionStart,f=this.selectionEnd,d=u!==f;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),p=u>g.selectionStart;d?(i=this._text.slice(u,f),l+=f-u):c=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),i",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],n=[],s=t;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",fabric.util.string.escapeXml(t),""].join("")},_setSVGTextLineText:function(t,e,i,r){var n,s,o,a,h,c=this.getHeightOfLine(e),l=-1!==this.textAlign.indexOf("justify"),u="",f=0,d=this._textLines[e];r+=c*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,p=d.length-1;g<=p;g++)h=g===p||this.charSpacing,u+=d[g],o=this.__charBounds[e][g],0===f?(i+=o.kernedWidth-o.width,f+=o.width):f+=o.kernedWidth,l&&!h&&this._reSpaceAndTab.test(d[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=f,f=0)},_pushTextBgRect:function(t,e,i,r,n,s){var o=fabric.Object.NUM_FRACTION_DIGITS;t.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var n,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,c=0,l=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,f=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,n={},s=0;sthis.dynamicMinWidth&&(this.dynamicMinWidth=g-v+r),o},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var e=b.Text.prototype._splitTextIntoLines.call(this,t),i=this._wrapText(e.lines,this.width),r=new Array(i.length),n=0;n{r(72);var n=r(306).devDependencies;e.exports={corePath:"https://unpkg.com/@ffmpeg/core@".concat(n["@ffmpeg/core"].substring(1),"/dist/ffmpeg-core.js")}},663:(e,t,r)=>{function n(e,t,r,n,o,i,a){try{var c=e[i](a),s=c.value}catch(e){return void r(e)}c.done?t(s):Promise.resolve(s).then(n,o)}var o=r(72),i=function(e){return new Promise((function(t,r){var n=new FileReader;n.onload=function(){t(n.result)},n.onerror=function(e){var t=e.target.error.code;r(Error("File could not be read! Code=".concat(t)))},n.readAsArrayBuffer(e)}))};e.exports=function(){var e,t=(e=regeneratorRuntime.mark((function e(t){var r,n;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t,void 0!==t){e.next=3;break}return e.abrupt("return",new Uint8Array);case 3:if("string"!=typeof t){e.next=16;break}if(!/data:_data\/([a-zA-Z]*);base64,([^"]*)/.test(t)){e.next=8;break}r=atob(t.split(",")[1]).split("").map((function(e){return e.charCodeAt(0)})),e.next=14;break;case 8:return e.next=10,fetch(o(t));case 10:return n=e.sent,e.next=13,n.arrayBuffer();case 13:r=e.sent;case 14:e.next=20;break;case 16:if(!(t instanceof File||t instanceof Blob)){e.next=20;break}return e.next=19,i(t);case 19:r=e.sent;case 20:return e.abrupt("return",new Uint8Array(r));case 21:case"end":return e.stop()}}),e)})),function(){var t=this,r=arguments;return new Promise((function(o,i){var a=e.apply(t,r);function c(e){n(a,o,i,c,s,"next",e)}function s(e){n(a,o,i,c,s,"throw",e)}c(void 0)}))});return function(e){return t.apply(this,arguments)}}()},452:(e,t,r)=>{function n(e,t,r,n,o,i,a){try{var c=e[i](a),s=c.value}catch(e){return void r(e)}c.done?t(s):Promise.resolve(s).then(n,o)}function o(e){return function(){var t=this,r=arguments;return new Promise((function(o,i){var a=e.apply(t,r);function c(e){n(a,o,i,c,s,"next",e)}function s(e){n(a,o,i,c,s,"throw",e)}c(void 0)}))}}var i=r(72),a=r(185).log,c=function(){var e=o(regeneratorRuntime.mark((function e(t,r){var n,o,i;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a("info","fetch ".concat(t)),e.next=3,fetch(t);case 3:return e.next=5,e.sent.arrayBuffer();case 5:return n=e.sent,a("info","".concat(t," file size = ").concat(n.byteLength," bytes")),o=new Blob([n],{type:r}),i=URL.createObjectURL(o),a("info","".concat(t," blob URL = ").concat(i)),e.abrupt("return",i);case 11:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();e.exports=function(){var e=o(regeneratorRuntime.mark((function e(t){var r,n,o,s,u;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("string"==typeof(r=t.corePath)){e.next=3;break}throw Error("corePath should be a string!");case 3:return n=i(r),e.next=6,c(n,"application/javascript");case 6:return o=e.sent,e.next=9,c(n.replace("ffmpeg-core.js","ffmpeg-core.wasm"),"application/wasm");case 9:return s=e.sent,e.next=12,c(n.replace("ffmpeg-core.js","ffmpeg-core.worker.js"),"application/javascript");case 12:if(u=e.sent,"undefined"!=typeof createFFmpegCore){e.next=15;break}return e.abrupt("return",new Promise((function(e){var t=document.createElement("script");t.src=o,t.type="text/javascript",t.addEventListener("load",(function r(){t.removeEventListener("load",r),a("info","ffmpeg-core.js script loaded"),e({createFFmpegCore,corePath:o,wasmPath:s,workerPath:u})})),document.getElementsByTagName("head")[0].appendChild(t)})));case 15:return a("info","ffmpeg-core.js script is loaded already"),e.abrupt("return",Promise.resolve({createFFmpegCore,corePath:o,wasmPath:s,workerPath:u}));case 17:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()},698:(e,t,r)=>{var n=r(497),o=r(452),i=r(663);e.exports={defaultOptions:n,getCreateFFmpegCore:o,fetchFile:i}},500:e=>{e.exports={defaultArgs:["./ffmpeg","-nostdin","-y"],baseOptions:{log:!1,logger:function(){},progress:function(){},corePath:""}}},906:(e,t,r)=>{function n(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}var l=r(500),p=l.defaultArgs,h=l.baseOptions,m=r(185),g=m.setLogging,d=m.setCustomLogger,y=m.log,v=r(583),b=r(319),w=r(698),x=w.defaultOptions,j=w.getCreateFFmpegCore,E=r(306).version,O=Error("ffmpeg.wasm is not ready, make sure you have completed load().");e.exports=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=s(s(s({},h),x),e),r=t.log,o=t.logger,i=t.progress,c=f(t,["log","logger","progress"]),u=null,l=null,m=null,w=!1,F=i,L=function(e){"FFMPEG_END"===e&&null!==m&&(m(),m=null,w=!1)},P=function(e){var t=e.type,r=e.message;y(t,r),v(r,F),L(r)},k=function(){var e=a(regeneratorRuntime.mark((function e(){var t,r,n,o,i;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(y("info","load ffmpeg-core"),null!==u){e.next=17;break}return y("info","loading ffmpeg-core"),e.next=5,j(c);case 5:return t=e.sent,r=t.createFFmpegCore,n=t.corePath,o=t.workerPath,i=t.wasmPath,e.next=12,r({mainScriptUrlOrBlob:n,printErr:function(e){return P({type:"fferr",message:e})},print:function(e){return P({type:"ffout",message:e})},locateFile:function(e,t){if("undefined"!=typeof window){if(void 0!==i&&e.endsWith("ffmpeg-core.wasm"))return i;if(void 0!==o&&e.endsWith("ffmpeg-core.worker.js"))return o}return t+e}});case 12:u=e.sent,l=u.cwrap("proxy_main","number",["number","number"]),y("info","ffmpeg-core loaded"),e.next=18;break;case 17:throw Error("ffmpeg.wasm was loaded, you should not load it again, use ffmpeg.isLoaded() to check next time.");case 18:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}(),S=function(){return null!==u},A=function(){for(var e=arguments.length,t=new Array(e),r=0;r1?t-1:0),n=1;n")})).join(" "))),null===u)throw O;var o=null;try{var i;o=(i=u.FS)[e].apply(i,r)}catch(t){throw"readdir"===e?Error("ffmpeg.FS('readdir', '".concat(r[0],"') error. Check if the path exists, ex: ffmpeg.FS('readdir', '/')")):"readFile"===e?Error("ffmpeg.FS('readFile', '".concat(r[0],"') error. Check if the path exists")):Error("Oops, something went wrong in FS operation.")}return o},C=function(){if(null===u)throw O;w=!1,u.exit(1),u=null,l=null,m=null},R=function(e){F=e},T=function(e){d(e)};return g(r),d(o),y("info","use ffmpeg.wasm v".concat(E)),{setProgress:R,setLogger:T,setLogging:g,load:k,isLoaded:S,run:A,exit:C,FS:_}}},352:(e,t,r)=>{r(666);var n=r(906),o=r(698).fetchFile;e.exports={createFFmpeg:n,fetchFile:o}},185:e=>{var t=!1,r=function(){};e.exports={logging:t,setLogging:function(e){t=e},setCustomLogger:function(e){r=e},log:function(e,n){r({type:e,message:n}),t&&console.log("[".concat(e,"] ").concat(n))}}},319:e=>{e.exports=function(e,t){var r=e._malloc(t.length*Uint32Array.BYTES_PER_ELEMENT);return t.forEach((function(t,n){var o=e._malloc(t.length+1);e.writeAsciiToMemory(t,o),e.setValue(r+Uint32Array.BYTES_PER_ELEMENT*n,o,"i32")})),[t.length,r]}},583:e=>{function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);ra)&&(r=a)}else if(e.startsWith("frame")||e.startsWith("size")){var c=e.split("time=")[1].split(" ")[0],s=o(c);t({ratio:n=s/r,time:s})}else e.startsWith("video:")&&(t({ratio:1}),r=0)}},666:e=>{var t=function(e){"use strict";var t,r=Object.prototype,n=r.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",c=o.toStringTag||"@@toStringTag";function s(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,r){return e[t]=r}}function u(e,t,r,n){var o=t&&t.prototype instanceof d?t:d,i=Object.create(o.prototype),a=new k(n||[]);return i._invoke=function(e,t,r){var n=l;return function(o,i){if(n===h)throw new Error("Generator is already running");if(n===m){if("throw"===o)throw i;return A()}for(r.method=o,r.arg=i;;){var a=r.delegate;if(a){var c=F(a,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===l)throw n=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=h;var s=f(e,t,r);if("normal"===s.type){if(n=r.done?m:p,s.arg===g)continue;return{value:s.arg,done:r.done}}"throw"===s.type&&(n=m,r.method="throw",r.arg=s.arg)}}}(e,r,a),i}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var l="suspendedStart",p="suspendedYield",h="executing",m="completed",g={};function d(){}function y(){}function v(){}var b={};b[i]=function(){return this};var w=Object.getPrototypeOf,x=w&&w(w(S([])));x&&x!==r&&n.call(x,i)&&(b=x);var j=v.prototype=d.prototype=Object.create(b);function E(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function O(e,t){function r(o,i,a,c){var s=f(e[o],e,i);if("throw"!==s.type){var u=s.arg,l=u.value;return l&&"object"==typeof l&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,c)}),(function(e){r("throw",e,a,c)})):t.resolve(l).then((function(e){u.value=e,a(u)}),(function(e){return r("throw",e,a,c)}))}c(s.arg)}var o;this._invoke=function(e,n){function i(){return new t((function(t,o){r(e,n,t,o)}))}return o=o?o.then(i,i):i()}}function F(e,r){var n=e.iterator[r.method];if(n===t){if(r.delegate=null,"throw"===r.method){if(e.iterator.return&&(r.method="return",r.arg=t,F(e,r),"throw"===r.method))return g;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return g}var o=f(n,e.iterator,r.arg);if("throw"===o.type)return r.method="throw",r.arg=o.arg,r.delegate=null,g;var i=o.arg;return i?i.done?(r[e.resultName]=i.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,g):i:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function L(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function k(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(L,this),this.reset(!0)}function S(e){if(e){var r=e[i];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,a=function r(){for(;++o=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),u=n.call(a,"finallyLoc");if(s&&u){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:S(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),g}},e}(e.exports);try{regeneratorRuntime=t}catch(e){Function("r","regeneratorRuntime = r")(t)}},72:function(e,t,r){var n,o;void 0===(o="function"==typeof(n=function(){return function(){var e=arguments.length;if(0===e)throw new Error("resolveUrl requires at least one argument; got none.");var t=document.createElement("base");if(t.href=arguments[0],1===e)return t.href;var r=document.getElementsByTagName("head")[0];r.insertBefore(t,r.firstChild);for(var n,o=document.createElement("a"),i=1;i{"use strict";e.exports=JSON.parse('{"name":"@ffmpeg/ffmpeg","version":"0.10.1","description":"FFmpeg WebAssembly version","main":"src/index.js","types":"src/index.d.ts","directories":{"example":"examples"},"scripts":{"start":"node scripts/server.js","build":"rimraf dist && webpack --config scripts/webpack.config.prod.js","prepublishOnly":"npm run build","lint":"eslint src","wait":"rimraf dist && wait-on http://localhost:3000/dist/ffmpeg.dev.js","test":"npm-run-all -p -r start test:all","test:all":"npm-run-all wait test:browser:ffmpeg test:node:all","test:node":"node --experimental-wasm-threads --experimental-wasm-bulk-memory node_modules/.bin/_mocha --exit --bail --require ./scripts/test-helper.js","test:node:all":"npm run test:node -- ./tests/*.test.js","test:browser":"mocha-headless-chrome -a allow-file-access-from-files -a incognito -a no-sandbox -a disable-setuid-sandbox -a disable-logging -t 300000","test:browser:ffmpeg":"npm run test:browser -- -f ./tests/ffmpeg.test.html"},"browser":{"./src/node/index.js":"./src/browser/index.js"},"repository":{"type":"git","url":"git+https://github.com/ffmpegwasm/ffmpeg.wasm.git"},"keywords":["ffmpeg","WebAssembly","video"],"author":"Jerome Wu ","license":"MIT","bugs":{"url":"https://github.com/ffmpegwasm/ffmpeg.wasm/issues"},"engines":{"node":">=12.16.1"},"homepage":"https://github.com/ffmpegwasm/ffmpeg.wasm#readme","dependencies":{"is-url":"^1.2.4","node-fetch":"^2.6.1","regenerator-runtime":"^0.13.7","resolve-url":"^0.2.1"},"devDependencies":{"@babel/core":"^7.12.3","@babel/preset-env":"^7.12.1","@ffmpeg/core":"^0.10.0","@types/emscripten":"^1.39.4","babel-loader":"^8.1.0","chai":"^4.2.0","cors":"^2.8.5","eslint":"^7.12.1","eslint-config-airbnb-base":"^14.1.0","eslint-plugin-import":"^2.22.1","express":"^4.17.1","mocha":"^8.2.1","mocha-headless-chrome":"^2.0.3","npm-run-all":"^4.1.5","wait-on":"^5.3.0","webpack":"^5.3.2","webpack-cli":"^4.1.0","webpack-dev-middleware":"^4.0.0"}}')}},t={},function r(n){if(t[n])return t[n].exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}(352);var e,t})); +//# sourceMappingURL=ffmpeg.min.js.map \ No newline at end of file diff --git a/public/motionity/src/js/libraries/jquery.nice-select.min.js b/public/motionity/src/js/libraries/jquery.nice-select.min.js new file mode 100644 index 000000000..88eb2d6c8 --- /dev/null +++ b/public/motionity/src/js/libraries/jquery.nice-select.min.js @@ -0,0 +1,4 @@ +/* jQuery Nice Select - v1.0 + https://github.com/hernansartorio/jquery-nice-select + Made by Hernán Sartorio */ +!function(e){e.fn.niceSelect=function(t){function s(t){t.after(e("
").addClass("nice-select").addClass(t.attr("class")||"").addClass(t.attr("disabled")?"disabled":"").attr("tabindex",t.attr("disabled")?null:"0").html('
    '));var s=t.next(),n=t.find("option"),i=t.find("option:selected");s.find(".current").html(i.data("display")||i.text()),n.each(function(t){var n=e(this),i=n.data("display");s.find("ul").append(e("
  • ").attr("data-value",n.val()).attr("data-display",i||null).addClass("option"+(n.is(":selected")?" selected":"")+(n.is(":disabled")?" disabled":"")).html(n.text()))})}if("string"==typeof t)return"update"==t?this.each(function(){var t=e(this),n=e(this).next(".nice-select"),i=n.hasClass("open");n.length&&(n.remove(),s(t),i&&t.next().trigger("click"))}):"destroy"==t?(this.each(function(){var t=e(this),s=e(this).next(".nice-select");s.length&&(s.remove(),t.css("display",""))}),0==e(".nice-select").length&&e(document).off(".nice_select")):console.log('Method "'+t+'" does not exist.'),this;this.hide(),this.each(function(){var t=e(this);t.next().hasClass("nice-select")||s(t)}),e(document).off(".nice_select"),e(document).on("click.nice_select",".nice-select",function(t){var s=e(this);e(".nice-select").not(s).removeClass("open"),s.toggleClass("open"),s.hasClass("open")?(s.find(".option"),s.find(".focus").removeClass("focus"),s.find(".selected").addClass("focus")):s.focus()}),e(document).on("click.nice_select",function(t){0===e(t.target).closest(".nice-select").length&&e(".nice-select").removeClass("open").find(".option")}),e(document).on("click.nice_select",".nice-select .option:not(.disabled)",function(t){var s=e(this),n=s.closest(".nice-select");n.find(".selected").removeClass("selected"),s.addClass("selected");var i=s.data("display")||s.text();n.find(".current").text(i),n.prev("select").val(s.data("value")).trigger("change")}),e(document).on("keydown.nice_select",".nice-select",function(t){var s=e(this),n=e(s.find(".focus")||s.find(".list .option.selected"));if(32==t.keyCode||13==t.keyCode)return s.hasClass("open")?n.trigger("click"):s.trigger("click"),!1;if(40==t.keyCode){if(s.hasClass("open")){var i=n.nextAll(".option:not(.disabled)").first();i.length>0&&(s.find(".focus").removeClass("focus"),i.addClass("focus"))}else s.trigger("click");return!1}if(38==t.keyCode){if(s.hasClass("open")){var l=n.prevAll(".option:not(.disabled)").first();l.length>0&&(s.find(".focus").removeClass("focus"),l.addClass("focus"))}else s.trigger("click");return!1}if(27==t.keyCode)s.hasClass("open")&&s.trigger("click");else if(9==t.keyCode&&s.hasClass("open"))return!1});var n=document.createElement("a").style;return n.cssText="pointer-events:auto","auto"!==n.pointerEvents&&e("html").addClass("no-csspointerevents"),this}}(jQuery); \ No newline at end of file diff --git a/public/motionity/src/js/libraries/localbase.js b/public/motionity/src/js/libraries/localbase.js new file mode 100644 index 000000000..b79cb3cdb --- /dev/null +++ b/public/motionity/src/js/libraries/localbase.js @@ -0,0 +1,6035 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Localbase = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 1) { + _logger["default"].warn.call(_this, "Multiple documents (".concat(keysForDeletion.length, ") with ").concat(JSON.stringify(docSelectionCriteria), " found.")); + } + }).then(function () { + keysForDeletion.forEach(function (key, index) { + _this.lf[collectionName].removeItem(key).then(function () { + if (index === keysForDeletion.length - 1) { + resolve(_success["default"].call(_this, "".concat(keysForDeletion.length, " Document").concat(keysForDeletion.length > 1 ? 's' : '', " with ").concat(JSON.stringify(docSelectionCriteria), " deleted."))); + } + })["catch"](function (err) { + reject(_error["default"].call(_this, "Could not delete ".concat(keysForDeletion.length, " Documents in ").concat(collectionName, " Collection."))); + }); + }); + }); + }; // delete document by key + + + _this.deleteDocumentByKey = function () { + _this.lf[collectionName].getItem(docSelectionCriteria).then(function (value) { + if (value) { + _this.lf[collectionName].removeItem(docSelectionCriteria).then(function () { + resolve(_success["default"].call(_this, "Document with key ".concat(JSON.stringify(docSelectionCriteria), " deleted."))); + })["catch"](function (err) { + reject(_error["default"].call(this, "No Document found in \"".concat(collectionName, "\" Collection with key ").concat(JSON.stringify(docSelectionCriteria), ". No document was deleted."))); + }); + } else { + reject(_error["default"].call(_this, "No Document found in \"".concat(collectionName, "\" Collection with key ").concat(JSON.stringify(docSelectionCriteria), ". No document was deleted."))); + } + }); + }; + + if (_typeof(docSelectionCriteria) == 'object') { + return _this.deleteDocumentByCriteria(); + } else { + return _this.deleteDocumentByKey(); + } + }; + + if (!_this.userErrors.length) { + var currentSelectionLevel = _selectionLevel["default"].call(_this); + + if (currentSelectionLevel == 'db') { + return _this.deleteDatabase(); + } else if (currentSelectionLevel == 'collection') { + return _this.deleteCollection(); + } else if (currentSelectionLevel == 'doc') { + return _this.deleteDocument(); + } + } else { + _showUserErrors["default"].call(_this); + } + }); +} + +module.exports = exports.default; + +},{"../../api-utils/error":2,"../../api-utils/selectionLevel":4,"../../api-utils/showUserErrors":5,"../../api-utils/success":6,"../../utils/isSubset":17,"../../utils/logger":18}],9:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = get; + +var _isSubset = _interopRequireDefault(require("../../utils/isSubset")); + +var _logger = _interopRequireDefault(require("../../utils/logger")); + +var _reset = _interopRequireDefault(require("../../api-utils/reset")); + +var _selectionLevel = _interopRequireDefault(require("../../api-utils/selectionLevel")); + +var _showUserErrors = _interopRequireDefault(require("../../api-utils/showUserErrors")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function get() { + var _this = this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + keys: false + }; + + // get collection + this.getCollection = function () { + var collectionName = _this.collectionName; + var orderByProperty = _this.orderByProperty; + var orderByDirection = _this.orderByDirection; + var limitBy = _this.limitBy; + var collection = []; + return _this.lf[collectionName].iterate(function (value, key) { + var collectionItem = {}; + + if (!options.keys) { + collectionItem = value; + } else { + collectionItem = { + key: key, + data: value + }; + } + + collection.push(collectionItem); + }).then(function () { + var logMessage = "Got \"".concat(collectionName, "\" collection"); // orderBy + + if (orderByProperty) { + logMessage += ", ordered by \"".concat(orderByProperty, "\""); + + if (!options.keys) { + collection.sort(function (a, b) { + return a[orderByProperty].toString().localeCompare(b[orderByProperty].toString()); + }); + } else { + collection.sort(function (a, b) { + return a.data[orderByProperty].toString().localeCompare(b.data[orderByProperty].toString()); + }); + } + } + + if (orderByDirection == 'desc') { + logMessage += " (descending)"; + collection.reverse(); + } // limit + + + if (limitBy) { + logMessage += ", limited to ".concat(limitBy); + collection = collection.splice(0, limitBy); + } + + logMessage += ":"; + + _logger["default"].log.call(_this, logMessage, collection); + + _reset["default"].call(_this); + + return collection; + }); + }; // get document + + + this.getDocument = function () { + var collectionName = _this.collectionName; + var docSelectionCriteria = _this.docSelectionCriteria; + var collection = []; + var document = {}; // get document by criteria + + _this.getDocumentByCriteria = function () { + return _this.lf[collectionName].iterate(function (value, key) { + if ((0, _isSubset["default"])(value, docSelectionCriteria)) { + collection.push(value); + } + }).then(function () { + if (!collection.length) { + _logger["default"].error.call(_this, "Could not find Document in \"".concat(collectionName, "\" collection with criteria: ").concat(JSON.stringify(docSelectionCriteria))); + } else { + document = collection[0]; + + _logger["default"].log.call(_this, "Got Document with ".concat(JSON.stringify(docSelectionCriteria), ":"), document); + + _reset["default"].call(_this); + + return document; + } + }); + }; // get document by key + + + _this.getDocumentByKey = function () { + return _this.lf[collectionName].getItem(docSelectionCriteria).then(function (value) { + document = value; + + if (document) { + _logger["default"].log.call(_this, "Got Document with key ".concat(JSON.stringify(docSelectionCriteria), ":"), document); + } else { + _logger["default"].error.call(_this, "Could not find Document in \"".concat(collectionName, "\" collection with Key: ").concat(JSON.stringify(docSelectionCriteria))); + } + + _reset["default"].call(_this); + + return document; + })["catch"](function (err) { + _logger["default"].error.call(_this, "Could not find Document in \"".concat(collectionName, "\" collection with Key: ").concat(JSON.stringify(docSelectionCriteria))); + + _reset["default"].call(_this); + }); + }; + + if (_typeof(docSelectionCriteria) == 'object') { + return _this.getDocumentByCriteria(); + } else { + return _this.getDocumentByKey(); + } + }; // check for user errors + + + if (!(_typeof(options) == 'object' && options instanceof Array == false)) { + this.userErrors.push('Data passed to .get() must be an object. Not an array, string, number or boolean. The object must contain a "keys" property set to true or false, e.g. { keys: true }'); + } else { + if (!options.hasOwnProperty('keys')) { + this.userErrors.push('Object passed to get() method must contain a "keys" property set to boolean true or false, e.g. { keys: true }'); + } else { + if (typeof options.keys !== 'boolean') { + this.userErrors.push('Property "keys" passed into get() method must be assigned a boolean value (true or false). Not a string or integer.'); + } + } + } + + if (!this.userErrors.length) { + var currentSelectionLevel = _selectionLevel["default"].call(this); + + if (currentSelectionLevel == 'collection') { + return this.getCollection(); + } else if (currentSelectionLevel == 'doc') { + return this.getDocument(); + } + } else { + _showUserErrors["default"].call(this); + + return null; + } +} + +module.exports = exports.default; + +},{"../../api-utils/reset":3,"../../api-utils/selectionLevel":4,"../../api-utils/showUserErrors":5,"../../utils/isSubset":17,"../../utils/logger":18}],10:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = set; + +var _logger = _interopRequireDefault(require("../../utils/logger")); + +var _isSubset = _interopRequireDefault(require("../../utils/isSubset")); + +var _success = _interopRequireDefault(require("../../api-utils/success")); + +var _error = _interopRequireDefault(require("../../api-utils/error")); + +var _showUserErrors = _interopRequireDefault(require("../../api-utils/showUserErrors")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function set(newDocument) { + var _this = this; + + var collectionName = this.collectionName; + var docSelectionCriteria = this.docSelectionCriteria; + return new Promise(function (resolve, reject) { + // set document by criteria + _this.setDocumentByCriteria = function () { + var docsToSet = []; + + _this.lf[collectionName].iterate(function (value, key) { + if ((0, _isSubset["default"])(value, docSelectionCriteria)) { + docsToSet.push({ + key: key, + newDocument: newDocument + }); + } + }).then(function () { + if (!docsToSet.length) { + reject(_error["default"].call(_this, "No Documents found in ".concat(collectionName, " Collection with criteria ").concat(JSON.stringify(docSelectionCriteria), "."))); + } + + if (docsToSet.length > 1) { + _logger["default"].warn.call(_this, "Multiple documents (".concat(docsToSet.length, ") with ").concat(JSON.stringify(docSelectionCriteria), " found for setting.")); + } + }).then(function () { + docsToSet.forEach(function (docToSet, index) { + _this.lf[collectionName].setItem(docToSet.key, docToSet.newDocument).then(function (value) { + if (index === docsToSet.length - 1) { + resolve(_success["default"].call(_this, "".concat(docsToSet.length, " Document").concat(docsToSet.length > 1 ? 's' : '', " in \"").concat(collectionName, "\" collection with ").concat(JSON.stringify(docSelectionCriteria), " set to:"), newDocument)); + } + })["catch"](function (err) { + reject(_error["default"].call(_this, "Could not set ".concat(docsToSet.length, " Documents in ").concat(collectionName, " Collection."))); + }); + }); + }); + }; // set document by key + + + _this.setDocumentByKey = function () { + _this.lf[collectionName].setItem(docSelectionCriteria, newDocument).then(function (value) { + resolve(_success["default"].call(_this, "Document in \"".concat(collectionName, "\" collection with key ").concat(JSON.stringify(docSelectionCriteria), " set to:"), newDocument)); + })["catch"](function (err) { + reject(_error["default"].call(_this, "Document in \"".concat(collectionName, "\" collection with key ").concat(JSON.stringify(docSelectionCriteria), " could not be set."))); + }); + }; // check for user errors + + + if (!newDocument) { + _this.userErrors.push('No new Document object provided to set() method. Use an object e.g. { id: 1, name: "Bill", age: 47 }'); + } else if (!(_typeof(newDocument) == 'object' && newDocument instanceof Array == false)) { + _this.userErrors.push('Data passed to .set() must be an object. Not an array, string, number or boolean.'); + } + + if (!_this.userErrors.length) { + if (_typeof(docSelectionCriteria) == 'object') { + return _this.setDocumentByCriteria(); + } else { + return _this.setDocumentByKey(); + } + } else { + _showUserErrors["default"].call(_this); + } + }); +} + +module.exports = exports.default; + +},{"../../api-utils/error":2,"../../api-utils/showUserErrors":5,"../../api-utils/success":6,"../../utils/isSubset":17,"../../utils/logger":18}],11:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = update; + +var _logger = _interopRequireDefault(require("../../utils/logger")); + +var _isSubset = _interopRequireDefault(require("../../utils/isSubset")); + +var _updateObject = _interopRequireDefault(require("../../utils/updateObject")); + +var _success = _interopRequireDefault(require("../../api-utils/success")); + +var _error = _interopRequireDefault(require("../../api-utils/error")); + +var _showUserErrors = _interopRequireDefault(require("../../api-utils/showUserErrors")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function update(docUpdates) { + var _this = this; + + var collectionName = this.collectionName; + var docSelectionCriteria = this.docSelectionCriteria; + return new Promise(function (resolve, reject) { + // update document by criteria + _this.updateDocumentByCriteria = function () { + var docsToUpdate = []; + + _this.lf[collectionName].iterate(function (value, key) { + if ((0, _isSubset["default"])(value, docSelectionCriteria)) { + var newDocument = (0, _updateObject["default"])(value, docUpdates); + docsToUpdate.push({ + key: key, + newDocument: newDocument + }); + } + }).then(function () { + if (!docsToUpdate.length) { + reject(_error["default"].call(_this, "No Documents found in ".concat(collectionName, " Collection with criteria ").concat(JSON.stringify(docSelectionCriteria), "."))); + } + + if (docsToUpdate.length > 1) { + _logger["default"].warn.call(_this, "Multiple documents (".concat(docsToUpdate.length, ") with ").concat(JSON.stringify(docSelectionCriteria), " found for updating.")); + } + }).then(function () { + docsToUpdate.forEach(function (docToUpdate, index) { + _this.lf[collectionName].setItem(docToUpdate.key, docToUpdate.newDocument).then(function (value) { + if (index === docsToUpdate.length - 1) { + resolve(_success["default"].call(_this, "".concat(docsToUpdate.length, " Document").concat(docsToUpdate.length > 1 ? 's' : '', " in \"").concat(collectionName, "\" collection with ").concat(JSON.stringify(docSelectionCriteria), " updated with:"), docUpdates)); + } + })["catch"](function (err) { + reject(_error["default"].call(_this, "Could not update ".concat(docsToUpdate.length, " Documents in ").concat(collectionName, " Collection."))); + }); + }); + }); + }; // update document by key + + + _this.updateDocumentByKey = function () { + var newDocument = {}; + + _this.lf[collectionName].getItem(docSelectionCriteria).then(function (value) { + newDocument = (0, _updateObject["default"])(value, docUpdates); + + _this.lf[collectionName].setItem(docSelectionCriteria, newDocument); + + resolve(_success["default"].call(_this, "Document in \"".concat(collectionName, "\" collection with key ").concat(JSON.stringify(docSelectionCriteria), " updated to:"), newDocument)); + })["catch"](function (err) { + reject(_error["default"].call(_this, "No Document found in \"".concat(collectionName, "\" collection with key ").concat(JSON.stringify(docSelectionCriteria)))); + }); + }; // check for user errors + + + if (!docUpdates) { + _this.userErrors.push('No update object provided to update() method. Use an object e.g. { name: "William" }'); + } else if (!(_typeof(docUpdates) == 'object' && docUpdates instanceof Array == false)) { + _this.userErrors.push('Data passed to .update() must be an object. Not an array, string, number or boolean.'); + } + + if (!_this.userErrors.length) { + if (_typeof(docSelectionCriteria) == 'object') { + _this.updateDocumentByCriteria(); + } else { + _this.updateDocumentByKey(); + } + } else { + _showUserErrors["default"].call(_this); + } + }); +} + +module.exports = exports.default; + +},{"../../api-utils/error":2,"../../api-utils/showUserErrors":5,"../../api-utils/success":6,"../../utils/isSubset":17,"../../utils/logger":18,"../../utils/updateObject":19}],12:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = limit; + +function limit(limitBy) { + if (!limitBy) { + this.userErrors.push("No integer specified in limit() method."); + } else if (!Number.isInteger(limitBy)) { + this.userErrors.push("Limit parameter in limit() method must be an integer (e.g. 3) and not a float, boolean, string or object."); + } else { + this.limitBy = limitBy; + } + + return this; +} + +module.exports = exports.default; + +},{}],13:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = orderBy; + +function orderBy(property, direction) { + if (!property) { + this.userErrors.push("No field name specified in orderBy() method. Use a string e.g. 'name'"); + } else if (typeof property !== 'string') { + this.userErrors.push("First parameter in orderBy() method must be a string (a field name) e.g. 'name'"); + } else { + this.orderByProperty = property; + } + + if (direction) { + if (direction !== 'asc' && direction !== 'desc') { + this.userErrors.push("Second parameter in orderBy() method must be a string set to 'asc' or 'desc'."); + } else { + this.orderByDirection = direction; + } + } + + return this; +} + +module.exports = exports.default; + +},{}],14:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = collection; + +var _localforage = _interopRequireDefault(require("localforage")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function collection(collectionName) { + if (!collectionName) { + this.userErrors.push('No collection name specified in collection() method.'); + return this; + } else if (typeof collectionName !== 'string') { + this.userErrors.push('Collection name in collection() method must be a string and not an object, number or boolean.'); + return this; + } else { + this.collectionName = collectionName; + var dbName = this.dbName; // if we've not created a localForage instance + // for this collection, create one + + if (!(collectionName in this.lf)) { + this.lf[collectionName] = _localforage["default"].createInstance({ + driver: _localforage["default"].INDEXEDDB, + name: dbName, + storeName: collectionName + }); + } + + return this; + } +} + +module.exports = exports.default; + +},{"localforage":20}],15:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = doc; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function doc(docSelectionCriteria) { + if (!docSelectionCriteria) { + this.userErrors.push('No document criteria specified in doc() method. Use a string (with a key) or an object (with criteria) e.g. { id: 1 }'); + } else if (typeof docSelectionCriteria !== 'string' && _typeof(docSelectionCriteria) !== 'object') { + this.userErrors.push('Document criteria specified in doc() method must not be a number or boolean. Use a string (with a key) or an object (with criteria) e.g. { id: 1 }'); + } else { + this.docSelectionCriteria = docSelectionCriteria; + } + + return this; +} + +module.exports = exports.default; + +},{}],16:[function(require,module,exports){ +"use strict"; // import api methods + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _collection = _interopRequireDefault(require("./api/selectors/collection")); + +var _doc = _interopRequireDefault(require("./api/selectors/doc")); + +var _orderBy = _interopRequireDefault(require("./api/filters/orderBy")); + +var _limit = _interopRequireDefault(require("./api/filters/limit")); + +var _get = _interopRequireDefault(require("./api/actions/get")); + +var _add = _interopRequireDefault(require("./api/actions/add")); + +var _update = _interopRequireDefault(require("./api/actions/update")); + +var _set = _interopRequireDefault(require("./api/actions/set")); + +var _delete = _interopRequireDefault(require("./api/actions/delete")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// Localbase +var Localbase = function Localbase(dbName) { + _classCallCheck(this, Localbase); + + // properties + this.dbName = dbName; + this.lf = {}; // where we store our localForage instances + + this.collectionName = null; + this.orderByProperty = null; + this.orderByDirection = null; + this.limitBy = null; + this.docSelectionCriteria = null; // queues + + this.deleteCollectionQueue = { + queue: [], + running: false + }; // config + + this.config = { + debug: true + }; // user errors - e.g. wrong type or no value passed to a method + + this.userErrors = []; // api - selectors + + this.collection = _collection["default"].bind(this); + this.doc = _doc["default"].bind(this); // api - filters + + this.orderBy = _orderBy["default"].bind(this); + this.limit = _limit["default"].bind(this); // api - actions + + this.get = _get["default"].bind(this); + this.add = _add["default"].bind(this); + this.update = _update["default"].bind(this); + this.set = _set["default"].bind(this); + this["delete"] = _delete["default"].bind(this); +}; + +exports["default"] = Localbase; +module.exports = exports.default; + +},{"./api/actions/add":7,"./api/actions/delete":8,"./api/actions/get":9,"./api/actions/set":10,"./api/actions/update":11,"./api/filters/limit":12,"./api/filters/orderBy":13,"./api/selectors/collection":14,"./api/selectors/doc":15}],17:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = isSubset; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function isSubset(superObj, subObj) { + return Object.keys(subObj).every(function (ele) { + if (_typeof(subObj[ele]) == 'object') { + return isSubset(superObj[ele], subObj[ele]); + } + + return subObj[ele] === superObj[ele]; + }); +} + +module.exports = exports.default; + +},{}],18:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var logger = { + baseStyle: "\n padding: 2px 5px;\n background-color: #124F5C;\n border-radius: 4px;\n color: white; \n ", + colors: { + log: '#124F5C', + error: '#ed2939', + warn: '#f39c12' + }, + log: function log(message, secondary) { + if ("development" == 'development' && this.config.debug) { + var style = logger.baseStyle + "background-color: ".concat(logger.colors.log); + + if (secondary) { + console.log('%clocalbase', style, message, secondary); + } else { + console.log('%clocalbase', style, message); + } + } + }, + error: function error(message, secondary) { + if ("development" == 'development' && this.config.debug) { + var style = logger.baseStyle + "background-color: ".concat(logger.colors.error); + console.error('%clocalbase', style, message); + } + }, + warn: function warn(message, secondary) { + if ("development" == 'development' && this.config.debug) { + var style = logger.baseStyle + "background-color: ".concat(logger.colors.warn); + console.warn('%clocalbase', style, message); + } + } +}; +var _default = logger; +exports["default"] = _default; +module.exports = exports.default; + +},{}],19:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = updateObject; + +function updateObject(obj +/*, …*/ +) { + for (var i = 1; i < arguments.length; i++) { + for (var prop in arguments[i]) { + var val = arguments[i][prop]; // if (typeof val == "object") // this also applies to arrays or null! + // updateObject(obj[prop], val); + // else + // obj[prop] = val; + + obj[prop] = val; + } + } + + return obj; +} + +module.exports = exports.default; + +},{}],20:[function(require,module,exports){ +(function (global){ +/*! + localForage -- Offline Storage, Improved + Version 1.7.4 + https://localforage.github.io/localForage + (c) 2013-2017 Mozilla, Apache License 2.0 +*/ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o element; its readystatechange event will be fired asynchronously once it is inserted + // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. + var scriptEl = global.document.createElement('script'); + scriptEl.onreadystatechange = function () { + nextTick(); + + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function () { + setTimeout(nextTick, 0); + }; + } +} + +var draining; +var queue = []; +//named nextTick for less confusing stack traces +function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) { + oldQueue[i](); + } + len = queue.length; + } + draining = false; +} + +module.exports = immediate; +function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],2:[function(_dereq_,module,exports){ +'use strict'; +var immediate = _dereq_(1); + +/* istanbul ignore next */ +function INTERNAL() {} + +var handlers = {}; + +var REJECTED = ['REJECTED']; +var FULFILLED = ['FULFILLED']; +var PENDING = ['PENDING']; + +module.exports = Promise; + +function Promise(resolver) { + if (typeof resolver !== 'function') { + throw new TypeError('resolver must be a function'); + } + this.state = PENDING; + this.queue = []; + this.outcome = void 0; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } +} + +Promise.prototype["catch"] = function (onRejected) { + return this.then(null, onRejected); +}; +Promise.prototype.then = function (onFulfilled, onRejected) { + if (typeof onFulfilled !== 'function' && this.state === FULFILLED || + typeof onRejected !== 'function' && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } + + return promise; +}; +function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === 'function') { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === 'function') { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } +} +QueueItem.prototype.callFulfilled = function (value) { + handlers.resolve(this.promise, value); +}; +QueueItem.prototype.otherCallFulfilled = function (value) { + unwrap(this.promise, this.onFulfilled, value); +}; +QueueItem.prototype.callRejected = function (value) { + handlers.reject(this.promise, value); +}; +QueueItem.prototype.otherCallRejected = function (value) { + unwrap(this.promise, this.onRejected, value); +}; + +function unwrap(promise, func, value) { + immediate(function () { + var returnValue; + try { + returnValue = func(value); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError('Cannot resolve promise with itself')); + } else { + handlers.resolve(promise, returnValue); + } + }); +} + +handlers.resolve = function (self, value) { + var result = tryCatch(getThen, value); + if (result.status === 'error') { + return handlers.reject(self, result.value); + } + var thenable = result.value; + + if (thenable) { + safelyResolveThenable(self, thenable); + } else { + self.state = FULFILLED; + self.outcome = value; + var i = -1; + var len = self.queue.length; + while (++i < len) { + self.queue[i].callFulfilled(value); + } + } + return self; +}; +handlers.reject = function (self, error) { + self.state = REJECTED; + self.outcome = error; + var i = -1; + var len = self.queue.length; + while (++i < len) { + self.queue[i].callRejected(error); + } + return self; +}; + +function getThen(obj) { + // Make sure we only access the accessor once as required by the spec + var then = obj && obj.then; + if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') { + return function appyThen() { + then.apply(obj, arguments); + }; + } +} + +function safelyResolveThenable(self, thenable) { + // Either fulfill, reject or reject with error + var called = false; + function onError(value) { + if (called) { + return; + } + called = true; + handlers.reject(self, value); + } + + function onSuccess(value) { + if (called) { + return; + } + called = true; + handlers.resolve(self, value); + } + + function tryToUnwrap() { + thenable(onSuccess, onError); + } + + var result = tryCatch(tryToUnwrap); + if (result.status === 'error') { + onError(result.value); + } +} + +function tryCatch(func, value) { + var out = {}; + try { + out.value = func(value); + out.status = 'success'; + } catch (e) { + out.status = 'error'; + out.value = e; + } + return out; +} + +Promise.resolve = resolve; +function resolve(value) { + if (value instanceof this) { + return value; + } + return handlers.resolve(new this(INTERNAL), value); +} + +Promise.reject = reject; +function reject(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); +} + +Promise.all = all; +function all(iterable) { + var self = this; + if (Object.prototype.toString.call(iterable) !== '[object Array]') { + return this.reject(new TypeError('must be an array')); + } + + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + + var values = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value, i) { + self.resolve(value).then(resolveFromAll, function (error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values[i] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values); + } + } + } +} + +Promise.race = race; +function race(iterable) { + var self = this; + if (Object.prototype.toString.call(iterable) !== '[object Array]') { + return this.reject(new TypeError('must be an array')); + } + + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + + var i = -1; + var promise = new this(INTERNAL); + + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value) { + self.resolve(value).then(function (response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function (error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } +} + +},{"1":1}],3:[function(_dereq_,module,exports){ +(function (global){ +'use strict'; +if (typeof global.Promise !== 'function') { + global.Promise = _dereq_(2); +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"2":2}],4:[function(_dereq_,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function getIDB() { + /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */ + try { + if (typeof indexedDB !== 'undefined') { + return indexedDB; + } + if (typeof webkitIndexedDB !== 'undefined') { + return webkitIndexedDB; + } + if (typeof mozIndexedDB !== 'undefined') { + return mozIndexedDB; + } + if (typeof OIndexedDB !== 'undefined') { + return OIndexedDB; + } + if (typeof msIndexedDB !== 'undefined') { + return msIndexedDB; + } + } catch (e) { + return; + } +} + +var idb = getIDB(); + +function isIndexedDBValid() { + try { + // Initialize IndexedDB; fall back to vendor-prefixed versions + // if needed. + if (!idb || !idb.open) { + return false; + } + // We mimic PouchDB here; + // + // We test for openDatabase because IE Mobile identifies itself + // as Safari. Oh the lulz... + var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform); + + var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1; + + // Safari <10.1 does not meet our requirements for IDB support + // (see: https://github.com/pouchdb/pouchdb/issues/5572). + // Safari 10.1 shipped with fetch, we can use that to detect it. + // Note: this creates issues with `window.fetch` polyfills and + // overrides; see: + // https://github.com/localForage/localForage/issues/856 + return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' && + // some outdated implementations of IDB that appear on Samsung + // and HTC Android devices <4.4 are missing IDBKeyRange + // See: https://github.com/mozilla/localForage/issues/128 + // See: https://github.com/mozilla/localForage/issues/272 + typeof IDBKeyRange !== 'undefined'; + } catch (e) { + return false; + } +} + +// Abstracts constructing a Blob object, so it also works in older +// browsers that don't support the native Blob constructor. (i.e. +// old QtWebKit versions, at least). +// Abstracts constructing a Blob object, so it also works in older +// browsers that don't support the native Blob constructor. (i.e. +// old QtWebKit versions, at least). +function createBlob(parts, properties) { + /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e) { + if (e.name !== 'TypeError') { + throw e; + } + var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder; + var builder = new Builder(); + for (var i = 0; i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } +} + +// This is CommonJS because lie is an external dependency, so Rollup +// can just ignore it. +if (typeof Promise === 'undefined') { + // In the "nopromises" build this will just throw if you don't have + // a global promise object, but it would throw anyway later. + _dereq_(3); +} +var Promise$1 = Promise; + +function executeCallback(promise, callback) { + if (callback) { + promise.then(function (result) { + callback(null, result); + }, function (error) { + callback(error); + }); + } +} + +function executeTwoCallbacks(promise, callback, errorCallback) { + if (typeof callback === 'function') { + promise.then(callback); + } + + if (typeof errorCallback === 'function') { + promise["catch"](errorCallback); + } +} + +function normalizeKey(key) { + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + return key; +} + +function getCallback() { + if (arguments.length && typeof arguments[arguments.length - 1] === 'function') { + return arguments[arguments.length - 1]; + } +} + +// Some code originally from async_storage.js in +// [Gaia](https://github.com/mozilla-b2g/gaia). + +var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; +var supportsBlobs = void 0; +var dbContexts = {}; +var toString = Object.prototype.toString; + +// Transaction Modes +var READ_ONLY = 'readonly'; +var READ_WRITE = 'readwrite'; + +// Transform a binary string to an array buffer, because otherwise +// weird stuff happens when you try to work with the binary string directly. +// It is known. +// From http://stackoverflow.com/questions/14967647/ (continues on next line) +// encode-decode-image-with-base64-breaks-image (2013-04-21) +function _binStringToArrayBuffer(bin) { + var length = bin.length; + var buf = new ArrayBuffer(length); + var arr = new Uint8Array(buf); + for (var i = 0; i < length; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; +} + +// +// Blobs are not supported in all versions of IndexedDB, notably +// Chrome <37 and Android <5. In those versions, storing a blob will throw. +// +// Various other blob bugs exist in Chrome v37-42 (inclusive). +// Detecting them is expensive and confusing to users, and Chrome 37-42 +// is at very low usage worldwide, so we do a hacky userAgent check instead. +// +// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120 +// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 +// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 +// +// Code borrowed from PouchDB. See: +// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js +// +function _checkBlobSupportWithoutCaching(idb) { + return new Promise$1(function (resolve) { + var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE); + var blob = createBlob(['']); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); + + txn.onabort = function (e) { + // If the transaction aborts now its due to not being able to + // write to the database, likely due to the disk being full + e.preventDefault(); + e.stopPropagation(); + resolve(false); + }; + + txn.oncomplete = function () { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + // MS Edge pretends to be Chrome 42: + // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx + resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); + }; + })["catch"](function () { + return false; // error, so assume unsupported + }); +} + +function _checkBlobSupport(idb) { + if (typeof supportsBlobs === 'boolean') { + return Promise$1.resolve(supportsBlobs); + } + return _checkBlobSupportWithoutCaching(idb).then(function (value) { + supportsBlobs = value; + return supportsBlobs; + }); +} + +function _deferReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + + // Create a deferred object representing the current database operation. + var deferredOperation = {}; + + deferredOperation.promise = new Promise$1(function (resolve, reject) { + deferredOperation.resolve = resolve; + deferredOperation.reject = reject; + }); + + // Enqueue the deferred operation. + dbContext.deferredOperations.push(deferredOperation); + + // Chain its promise to the database readiness. + if (!dbContext.dbReady) { + dbContext.dbReady = deferredOperation.promise; + } else { + dbContext.dbReady = dbContext.dbReady.then(function () { + return deferredOperation.promise; + }); + } +} + +function _advanceReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + + // Dequeue a deferred operation. + var deferredOperation = dbContext.deferredOperations.pop(); + + // Resolve its promise (which is part of the database readiness + // chain of promises). + if (deferredOperation) { + deferredOperation.resolve(); + return deferredOperation.promise; + } +} + +function _rejectReadiness(dbInfo, err) { + var dbContext = dbContexts[dbInfo.name]; + + // Dequeue a deferred operation. + var deferredOperation = dbContext.deferredOperations.pop(); + + // Reject its promise (which is part of the database readiness + // chain of promises). + if (deferredOperation) { + deferredOperation.reject(err); + return deferredOperation.promise; + } +} + +function _getConnection(dbInfo, upgradeNeeded) { + return new Promise$1(function (resolve, reject) { + dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext(); + + if (dbInfo.db) { + if (upgradeNeeded) { + _deferReadiness(dbInfo); + dbInfo.db.close(); + } else { + return resolve(dbInfo.db); + } + } + + var dbArgs = [dbInfo.name]; + + if (upgradeNeeded) { + dbArgs.push(dbInfo.version); + } + + var openreq = idb.open.apply(idb, dbArgs); + + if (upgradeNeeded) { + openreq.onupgradeneeded = function (e) { + var db = openreq.result; + try { + db.createObjectStore(dbInfo.storeName); + if (e.oldVersion <= 1) { + // Added when support for blob shims was added + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + } + } catch (ex) { + if (ex.name === 'ConstraintError') { + console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); + } else { + throw ex; + } + } + }; + } + + openreq.onerror = function (e) { + e.preventDefault(); + reject(openreq.error); + }; + + openreq.onsuccess = function () { + resolve(openreq.result); + _advanceReadiness(dbInfo); + }; + }); +} + +function _getOriginalConnection(dbInfo) { + return _getConnection(dbInfo, false); +} + +function _getUpgradedConnection(dbInfo) { + return _getConnection(dbInfo, true); +} + +function _isUpgradeNeeded(dbInfo, defaultVersion) { + if (!dbInfo.db) { + return true; + } + + var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); + var isDowngrade = dbInfo.version < dbInfo.db.version; + var isUpgrade = dbInfo.version > dbInfo.db.version; + + if (isDowngrade) { + // If the version is not the default one + // then warn for impossible downgrade. + if (dbInfo.version !== defaultVersion) { + console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); + } + // Align the versions to prevent errors. + dbInfo.version = dbInfo.db.version; + } + + if (isUpgrade || isNewStore) { + // If the store is new then increment the version (if needed). + // This will trigger an "upgradeneeded" event which is required + // for creating a store. + if (isNewStore) { + var incVersion = dbInfo.db.version + 1; + if (incVersion > dbInfo.version) { + dbInfo.version = incVersion; + } + } + + return true; + } + + return false; +} + +// encode a blob for indexeddb engines that don't support blobs +function _encodeBlob(blob) { + return new Promise$1(function (resolve, reject) { + var reader = new FileReader(); + reader.onerror = reject; + reader.onloadend = function (e) { + var base64 = btoa(e.target.result || ''); + resolve({ + __local_forage_encoded_blob: true, + data: base64, + type: blob.type + }); + }; + reader.readAsBinaryString(blob); + }); +} + +// decode an encoded blob +function _decodeBlob(encodedBlob) { + var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); + return createBlob([arrayBuff], { type: encodedBlob.type }); +} + +// is this one of our fancy encoded blobs? +function _isEncodedBlob(value) { + return value && value.__local_forage_encoded_blob; +} + +// Specialize the default `ready()` function by making it dependent +// on the current database operations. Thus, the driver will be actually +// ready when it's been initialized (default) *and* there are no pending +// operations on the database (initiated by some other instances). +function _fullyReady(callback) { + var self = this; + + var promise = self._initReady().then(function () { + var dbContext = dbContexts[self._dbInfo.name]; + + if (dbContext && dbContext.dbReady) { + return dbContext.dbReady; + } + }); + + executeTwoCallbacks(promise, callback, callback); + return promise; +} + +// Try to establish a new db connection to replace the +// current one which is broken (i.e. experiencing +// InvalidStateError while creating a transaction). +function _tryReconnect(dbInfo) { + _deferReadiness(dbInfo); + + var dbContext = dbContexts[dbInfo.name]; + var forages = dbContext.forages; + + for (var i = 0; i < forages.length; i++) { + var forage = forages[i]; + if (forage._dbInfo.db) { + forage._dbInfo.db.close(); + forage._dbInfo.db = null; + } + } + dbInfo.db = null; + + return _getOriginalConnection(dbInfo).then(function (db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo)) { + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function (db) { + // store the latest db reference + // in case the db was upgraded + dbInfo.db = dbContext.db = db; + for (var i = 0; i < forages.length; i++) { + forages[i]._dbInfo.db = db; + } + })["catch"](function (err) { + _rejectReadiness(dbInfo, err); + throw err; + }); +} + +// FF doesn't like Promises (micro-tasks) and IDDB store operations, +// so we have to do it with callbacks +function createTransaction(dbInfo, mode, callback, retries) { + if (retries === undefined) { + retries = 1; + } + + try { + var tx = dbInfo.db.transaction(dbInfo.storeName, mode); + callback(null, tx); + } catch (err) { + if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) { + return Promise$1.resolve().then(function () { + if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) { + // increase the db version, to create the new ObjectStore + if (dbInfo.db) { + dbInfo.version = dbInfo.db.version + 1; + } + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + }).then(function () { + return _tryReconnect(dbInfo).then(function () { + createTransaction(dbInfo, mode, callback, retries - 1); + }); + })["catch"](callback); + } + + callback(err); + } +} + +function createDbContext() { + return { + // Running localForages sharing a database. + forages: [], + // Shared database. + db: null, + // Database readiness (promise). + dbReady: null, + // Deferred operations on the database. + deferredOperations: [] + }; +} + +// Open the IndexedDB database (automatically creates one if one didn't +// previously exist), using any options set in the config. +function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + // Get the current context of the database; + var dbContext = dbContexts[dbInfo.name]; + + // ...or create a new context. + if (!dbContext) { + dbContext = createDbContext(); + // Register the new context in the global container. + dbContexts[dbInfo.name] = dbContext; + } + + // Register itself as a running localForage in the current context. + dbContext.forages.push(self); + + // Replace the default `ready()` function with the specialized one. + if (!self._initReady) { + self._initReady = self.ready; + self.ready = _fullyReady; + } + + // Create an array of initialization states of the related localForages. + var initPromises = []; + + function ignoreErrors() { + // Don't handle errors here, + // just makes sure related localForages aren't pending. + return Promise$1.resolve(); + } + + for (var j = 0; j < dbContext.forages.length; j++) { + var forage = dbContext.forages[j]; + if (forage !== self) { + // Don't wait for itself... + initPromises.push(forage._initReady()["catch"](ignoreErrors)); + } + } + + // Take a snapshot of the related localForages. + var forages = dbContext.forages.slice(0); + + // Initialize the connection process only when + // all the related localForages aren't pending. + return Promise$1.all(initPromises).then(function () { + dbInfo.db = dbContext.db; + // Get the connection or open a new one without upgrade. + return _getOriginalConnection(dbInfo); + }).then(function (db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function (db) { + dbInfo.db = dbContext.db = db; + self._dbInfo = dbInfo; + // Share the final connection amongst related localForages. + for (var k = 0; k < forages.length; k++) { + var forage = forages[k]; + if (forage !== self) { + // Self is already up-to-date. + forage._dbInfo.db = dbInfo.db; + forage._dbInfo.version = dbInfo.version; + } + } + }); +} + +function getItem(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.get(key); + + req.onsuccess = function () { + var value = req.result; + if (value === undefined) { + value = null; + } + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + resolve(value); + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Iterate over all items stored in database. +function iterate(iterator, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.openCursor(); + var iterationNumber = 1; + + req.onsuccess = function () { + var cursor = req.result; + + if (cursor) { + var value = cursor.value; + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + var result = iterator(value, cursor.key, iterationNumber++); + + // when the iterator callback returns any + // (non-`undefined`) value, then we stop + // the iteration immediately + if (result !== void 0) { + resolve(result); + } else { + cursor["continue"](); + } + } else { + resolve(); + } + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + + return promise; +} + +function setItem(key, value, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + var dbInfo; + self.ready().then(function () { + dbInfo = self._dbInfo; + if (toString.call(value) === '[object Blob]') { + return _checkBlobSupport(dbInfo.db).then(function (blobSupport) { + if (blobSupport) { + return value; + } + return _encodeBlob(value); + }); + } + return value; + }).then(function (value) { + createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + + // The reason we don't _save_ null is because IE 10 does + // not support saving the `null` type in IndexedDB. How + // ironic, given the bug below! + // See: https://github.com/mozilla/localForage/issues/161 + if (value === null) { + value = undefined; + } + + var req = store.put(value, key); + + transaction.oncomplete = function () { + // Cast to undefined so the value passed to + // callback/promise is the same as what one would get out + // of `getItem()` later. This leads to some weirdness + // (setItem('foo', undefined) will return `null`), but + // it's not my fault localStorage is our baseline and that + // it's weird. + if (value === undefined) { + value = null; + } + + resolve(value); + }; + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function removeItem(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + // We use a Grunt task to make this safe for IE and some + // versions of Android (including those used by Cordova). + // Normally IE won't like `.delete()` and will insist on + // using `['delete']()`, but we have a build step that + // fixes this for us now. + var req = store["delete"](key); + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onerror = function () { + reject(req.error); + }; + + // The request will be also be aborted if we've exceeded our storage + // space. + transaction.onabort = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function clear(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.clear(); + + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function length(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.count(); + + req.onsuccess = function () { + resolve(req.result); + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function key(n, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + if (n < 0) { + resolve(null); + + return; + } + + self.ready().then(function () { + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var advanced = false; + var req = store.openKeyCursor(); + + req.onsuccess = function () { + var cursor = req.result; + if (!cursor) { + // this means there weren't enough keys + resolve(null); + + return; + } + + if (n === 0) { + // We have the first key, return it if that's what they + // wanted. + resolve(cursor.key); + } else { + if (!advanced) { + // Otherwise, ask the cursor to skip ahead n + // records. + advanced = true; + cursor.advance(n); + } else { + // When we get here, we've got the nth key. + resolve(cursor.key); + } + } + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function keys(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.openKeyCursor(); + var keys = []; + + req.onsuccess = function () { + var cursor = req.result; + + if (!cursor) { + resolve(keys); + return; + } + + keys.push(cursor.key); + cursor["continue"](); + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function dropInstance(options, callback) { + callback = getCallback.apply(this, arguments); + + var currentConfig = this.config(); + options = typeof options !== 'function' && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + + var self = this; + var promise; + if (!options.name) { + promise = Promise$1.reject('Invalid arguments'); + } else { + var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db; + + var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) { + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + dbContext.db = db; + for (var i = 0; i < forages.length; i++) { + forages[i]._dbInfo.db = db; + } + return db; + }); + + if (!options.storeName) { + promise = dbPromise.then(function (db) { + _deferReadiness(options); + + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + + db.close(); + for (var i = 0; i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + } + + var dropDBPromise = new Promise$1(function (resolve, reject) { + var req = idb.deleteDatabase(options.name); + + req.onerror = req.onblocked = function (err) { + var db = req.result; + if (db) { + db.close(); + } + reject(err); + }; + + req.onsuccess = function () { + var db = req.result; + if (db) { + db.close(); + } + resolve(db); + }; + }); + + return dropDBPromise.then(function (db) { + dbContext.db = db; + for (var i = 0; i < forages.length; i++) { + var _forage = forages[i]; + _advanceReadiness(_forage._dbInfo); + } + })["catch"](function (err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {}); + throw err; + }); + }); + } else { + promise = dbPromise.then(function (db) { + if (!db.objectStoreNames.contains(options.storeName)) { + return; + } + + var newVersion = db.version + 1; + + _deferReadiness(options); + + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + + db.close(); + for (var i = 0; i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + forage._dbInfo.version = newVersion; + } + + var dropObjectPromise = new Promise$1(function (resolve, reject) { + var req = idb.open(options.name, newVersion); + + req.onerror = function (err) { + var db = req.result; + db.close(); + reject(err); + }; + + req.onupgradeneeded = function () { + var db = req.result; + db.deleteObjectStore(options.storeName); + }; + + req.onsuccess = function () { + var db = req.result; + db.close(); + resolve(db); + }; + }); + + return dropObjectPromise.then(function (db) { + dbContext.db = db; + for (var j = 0; j < forages.length; j++) { + var _forage2 = forages[j]; + _forage2._dbInfo.db = db; + _advanceReadiness(_forage2._dbInfo); + } + })["catch"](function (err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {}); + throw err; + }); + }); + } + } + + executeCallback(promise, callback); + return promise; +} + +var asyncStorage = { + _driver: 'asyncStorage', + _initStorage: _initStorage, + _support: isIndexedDBValid(), + iterate: iterate, + getItem: getItem, + setItem: setItem, + removeItem: removeItem, + clear: clear, + length: length, + key: key, + keys: keys, + dropInstance: dropInstance +}; + +function isWebSQLValid() { + return typeof openDatabase === 'function'; +} + +// Sadly, the best way to save binary data in WebSQL/localStorage is serializing +// it to Base64, so this is how we store it to prevent very strange errors with less +// verbose ways of binary <-> string data storage. +var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +var BLOB_TYPE_PREFIX = '~~local_forage_type~'; +var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; + +var SERIALIZED_MARKER = '__lfsc__:'; +var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; + +// OMG the serializations! +var TYPE_ARRAYBUFFER = 'arbf'; +var TYPE_BLOB = 'blob'; +var TYPE_INT8ARRAY = 'si08'; +var TYPE_UINT8ARRAY = 'ui08'; +var TYPE_UINT8CLAMPEDARRAY = 'uic8'; +var TYPE_INT16ARRAY = 'si16'; +var TYPE_INT32ARRAY = 'si32'; +var TYPE_UINT16ARRAY = 'ur16'; +var TYPE_UINT32ARRAY = 'ui32'; +var TYPE_FLOAT32ARRAY = 'fl32'; +var TYPE_FLOAT64ARRAY = 'fl64'; +var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; + +var toString$1 = Object.prototype.toString; + +function stringToBuffer(serializedString) { + // Fill the string into a ArrayBuffer. + var bufferLength = serializedString.length * 0.75; + var len = serializedString.length; + var i; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + + if (serializedString[serializedString.length - 1] === '=') { + bufferLength--; + if (serializedString[serializedString.length - 2] === '=') { + bufferLength--; + } + } + + var buffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(buffer); + + for (i = 0; i < len; i += 4) { + encoded1 = BASE_CHARS.indexOf(serializedString[i]); + encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); + encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); + encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); + + /*jslint bitwise: true */ + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return buffer; +} + +// Converts a buffer to a string to store, serialized, in the backend +// storage library. +function bufferToString(buffer) { + // base64-arraybuffer + var bytes = new Uint8Array(buffer); + var base64String = ''; + var i; + + for (i = 0; i < bytes.length; i += 3) { + /*jslint bitwise: true */ + base64String += BASE_CHARS[bytes[i] >> 2]; + base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; + base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; + base64String += BASE_CHARS[bytes[i + 2] & 63]; + } + + if (bytes.length % 3 === 2) { + base64String = base64String.substring(0, base64String.length - 1) + '='; + } else if (bytes.length % 3 === 1) { + base64String = base64String.substring(0, base64String.length - 2) + '=='; + } + + return base64String; +} + +// Serialize a value, afterwards executing a callback (which usually +// instructs the `setItem()` callback/promise to be executed). This is how +// we store binary data with localStorage. +function serialize(value, callback) { + var valueType = ''; + if (value) { + valueType = toString$1.call(value); + } + + // Cannot use `value instanceof ArrayBuffer` or such here, as these + // checks fail when running the tests using casper.js... + // + // TODO: See why those tests fail and use a better solution. + if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) { + // Convert binary arrays to a string and prefix the string with + // a special marker. + var buffer; + var marker = SERIALIZED_MARKER; + + if (value instanceof ArrayBuffer) { + buffer = value; + marker += TYPE_ARRAYBUFFER; + } else { + buffer = value.buffer; + + if (valueType === '[object Int8Array]') { + marker += TYPE_INT8ARRAY; + } else if (valueType === '[object Uint8Array]') { + marker += TYPE_UINT8ARRAY; + } else if (valueType === '[object Uint8ClampedArray]') { + marker += TYPE_UINT8CLAMPEDARRAY; + } else if (valueType === '[object Int16Array]') { + marker += TYPE_INT16ARRAY; + } else if (valueType === '[object Uint16Array]') { + marker += TYPE_UINT16ARRAY; + } else if (valueType === '[object Int32Array]') { + marker += TYPE_INT32ARRAY; + } else if (valueType === '[object Uint32Array]') { + marker += TYPE_UINT32ARRAY; + } else if (valueType === '[object Float32Array]') { + marker += TYPE_FLOAT32ARRAY; + } else if (valueType === '[object Float64Array]') { + marker += TYPE_FLOAT64ARRAY; + } else { + callback(new Error('Failed to get type for BinaryArray')); + } + } + + callback(marker + bufferToString(buffer)); + } else if (valueType === '[object Blob]') { + // Conver the blob to a binaryArray and then to a string. + var fileReader = new FileReader(); + + fileReader.onload = function () { + // Backwards-compatible prefix for the blob type. + var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); + + callback(SERIALIZED_MARKER + TYPE_BLOB + str); + }; + + fileReader.readAsArrayBuffer(value); + } else { + try { + callback(JSON.stringify(value)); + } catch (e) { + console.error("Couldn't convert value into a JSON string: ", value); + + callback(null, e); + } + } +} + +// Deserialize data we've inserted into a value column/field. We place +// special markers into our strings to mark them as encoded; this isn't +// as nice as a meta field, but it's the only sane thing we can do whilst +// keeping localStorage support intact. +// +// Oftentimes this will just deserialize JSON content, but if we have a +// special marker (SERIALIZED_MARKER, defined above), we will extract +// some kind of arraybuffer/binary data/typed array out of the string. +function deserialize(value) { + // If we haven't marked this string as being specially serialized (i.e. + // something other than serialized JSON), we can just return it and be + // done with it. + if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { + return JSON.parse(value); + } + + // The following code deals with deserializing some kind of Blob or + // TypedArray. First we separate out the type of data we're dealing + // with from the data itself. + var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); + var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); + + var blobType; + // Backwards-compatible blob type serialization strategy. + // DBs created with older versions of localForage will simply not have the blob type. + if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { + var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); + blobType = matcher[1]; + serializedString = serializedString.substring(matcher[0].length); + } + var buffer = stringToBuffer(serializedString); + + // Return the right type based on the code/type set during + // serialization. + switch (type) { + case TYPE_ARRAYBUFFER: + return buffer; + case TYPE_BLOB: + return createBlob([buffer], { type: blobType }); + case TYPE_INT8ARRAY: + return new Int8Array(buffer); + case TYPE_UINT8ARRAY: + return new Uint8Array(buffer); + case TYPE_UINT8CLAMPEDARRAY: + return new Uint8ClampedArray(buffer); + case TYPE_INT16ARRAY: + return new Int16Array(buffer); + case TYPE_UINT16ARRAY: + return new Uint16Array(buffer); + case TYPE_INT32ARRAY: + return new Int32Array(buffer); + case TYPE_UINT32ARRAY: + return new Uint32Array(buffer); + case TYPE_FLOAT32ARRAY: + return new Float32Array(buffer); + case TYPE_FLOAT64ARRAY: + return new Float64Array(buffer); + default: + throw new Error('Unkown type: ' + type); + } +} + +var localforageSerializer = { + serialize: serialize, + deserialize: deserialize, + stringToBuffer: stringToBuffer, + bufferToString: bufferToString +}; + +/* + * Includes code from: + * + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + */ + +function createDbTable(t, dbInfo, callback, errorCallback) { + t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback); +} + +// Open the WebSQL database (automatically creates one if one didn't +// previously exist), using any options set in the config. +function _initStorage$1(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; + } + } + + var dbInfoPromise = new Promise$1(function (resolve, reject) { + // Open the database; the openDatabase API will automatically + // create it for us if it doesn't exist. + try { + dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); + } catch (e) { + return reject(e); + } + + // Create our key/value table if it doesn't exist. + dbInfo.db.transaction(function (t) { + createDbTable(t, dbInfo, function () { + self._dbInfo = dbInfo; + resolve(); + }, function (t, error) { + reject(error); + }); + }, reject); + }); + + dbInfo.serializer = localforageSerializer; + return dbInfoPromise; +} + +function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) { + t.executeSql(sqlStatement, args, callback, function (t, error) { + if (error.code === error.SYNTAX_ERR) { + t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) { + if (!results.rows.length) { + // if the table is missing (was deleted) + // re-create it table and retry + createDbTable(t, dbInfo, function () { + t.executeSql(sqlStatement, args, callback, errorCallback); + }, errorCallback); + } else { + errorCallback(t, error); + } + }, errorCallback); + } else { + errorCallback(t, error); + } + }, errorCallback); +} + +function getItem$1(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { + var result = results.rows.length ? results.rows.item(0).value : null; + + // Check to see if this is serialized content we need to + // unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + resolve(result); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function iterate$1(iterator, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { + var rows = results.rows; + var length = rows.length; + + for (var i = 0; i < length; i++) { + var item = rows.item(i); + var result = item.value; + + // Check to see if this is serialized content + // we need to unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + result = iterator(result, item.key, i + 1); + + // void(0) prevents problems with redefinition + // of `undefined`. + if (result !== void 0) { + resolve(result); + return; + } + } + + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function _setItem(key, value, callback, retriesLeft) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + // The localStorage API doesn't return undefined values in an + // "expected" way, so undefined is always cast to null in all + // drivers. See: https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function (value, error) { + if (error) { + reject(error); + } else { + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () { + resolve(originalValue); + }, function (t, error) { + reject(error); + }); + }, function (sqlError) { + // The transaction failed; check + // to see if it's a quota error. + if (sqlError.code === sqlError.QUOTA_ERR) { + // We reject the callback outright for now, but + // it's worth trying to re-run the transaction. + // Even if the user accepts the prompt to use + // more storage on Safari, this error will + // be called. + // + // Try to re-run the transaction. + if (retriesLeft > 0) { + resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1])); + return; + } + reject(sqlError); + } + }); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function setItem$1(key, value, callback) { + return _setItem.apply(this, [key, value, callback, 1]); +} + +function removeItem$1(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Deletes every item in the table. +// TODO: Find out if this resets the AUTO_INCREMENT number. +function clear$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () { + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Does a simple `COUNT(key)` to get the number of items stored in +// localForage. +function length$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + // Ahhh, SQL makes this one soooooo easy. + tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { + var result = results.rows.item(0).c; + resolve(result); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Return the key located at key index X; essentially gets the key from a +// `WHERE id = ?`. This is the most efficient way I can think to implement +// this rarely-used (in my experience) part of the API, but it can seem +// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so +// the ID of each key will change every time it's updated. Perhaps a stored +// procedure for the `setItem()` SQL would solve this problem? +// TODO: Don't change ID on `setItem()`. +function key$1(n, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { + var result = results.rows.length ? results.rows.item(0).key : null; + resolve(result); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function keys$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { + var keys = []; + + for (var i = 0; i < results.rows.length; i++) { + keys.push(results.rows.item(i).key); + } + + resolve(keys); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// https://www.w3.org/TR/webdatabase/#databases +// > There is no way to enumerate or delete the databases available for an origin from this API. +function getAllStoreNames(db) { + return new Promise$1(function (resolve, reject) { + db.transaction(function (t) { + t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) { + var storeNames = []; + + for (var i = 0; i < results.rows.length; i++) { + storeNames.push(results.rows.item(i).name); + } + + resolve({ + db: db, + storeNames: storeNames + }); + }, function (t, error) { + reject(error); + }); + }, function (sqlError) { + reject(sqlError); + }); + }); +} + +function dropInstance$1(options, callback) { + callback = getCallback.apply(this, arguments); + + var currentConfig = this.config(); + options = typeof options !== 'function' && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + + var self = this; + var promise; + if (!options.name) { + promise = Promise$1.reject('Invalid arguments'); + } else { + promise = new Promise$1(function (resolve) { + var db; + if (options.name === currentConfig.name) { + // use the db reference of the current instance + db = self._dbInfo.db; + } else { + db = openDatabase(options.name, '', '', 0); + } + + if (!options.storeName) { + // drop all database tables + resolve(getAllStoreNames(db)); + } else { + resolve({ + db: db, + storeNames: [options.storeName] + }); + } + }).then(function (operationInfo) { + return new Promise$1(function (resolve, reject) { + operationInfo.db.transaction(function (t) { + function dropTable(storeName) { + return new Promise$1(function (resolve, reject) { + t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () { + resolve(); + }, function (t, error) { + reject(error); + }); + }); + } + + var operations = []; + for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) { + operations.push(dropTable(operationInfo.storeNames[i])); + } + + Promise$1.all(operations).then(function () { + resolve(); + })["catch"](function (e) { + reject(e); + }); + }, function (sqlError) { + reject(sqlError); + }); + }); + }); + } + + executeCallback(promise, callback); + return promise; +} + +var webSQLStorage = { + _driver: 'webSQLStorage', + _initStorage: _initStorage$1, + _support: isWebSQLValid(), + iterate: iterate$1, + getItem: getItem$1, + setItem: setItem$1, + removeItem: removeItem$1, + clear: clear$1, + length: length$1, + key: key$1, + keys: keys$1, + dropInstance: dropInstance$1 +}; + +function isLocalStorageValid() { + try { + return typeof localStorage !== 'undefined' && 'setItem' in localStorage && + // in IE8 typeof localStorage.setItem === 'object' + !!localStorage.setItem; + } catch (e) { + return false; + } +} + +function _getKeyPrefix(options, defaultConfig) { + var keyPrefix = options.name + '/'; + + if (options.storeName !== defaultConfig.storeName) { + keyPrefix += options.storeName + '/'; + } + return keyPrefix; +} + +// Check if localStorage throws when saving an item +function checkIfLocalStorageThrows() { + var localStorageTestKey = '_localforage_support_test'; + + try { + localStorage.setItem(localStorageTestKey, true); + localStorage.removeItem(localStorageTestKey); + + return false; + } catch (e) { + return true; + } +} + +// Check if localStorage is usable and allows to save an item +// This method checks if localStorage is usable in Safari Private Browsing +// mode, or in any other case where the available quota for localStorage +// is 0 and there wasn't any saved items yet. +function _isLocalStorageUsable() { + return !checkIfLocalStorageThrows() || localStorage.length > 0; +} + +// Config the localStorage backend, using options set in the config. +function _initStorage$2(options) { + var self = this; + var dbInfo = {}; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig); + + if (!_isLocalStorageUsable()) { + return Promise$1.reject(); + } + + self._dbInfo = dbInfo; + dbInfo.serializer = localforageSerializer; + + return Promise$1.resolve(); +} + +// Remove all keys from the datastore, effectively destroying all data in +// the app's key/value store! +function clear$2(callback) { + var self = this; + var promise = self.ready().then(function () { + var keyPrefix = self._dbInfo.keyPrefix; + + for (var i = localStorage.length - 1; i >= 0; i--) { + var key = localStorage.key(i); + + if (key.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key); + } + } + }); + + executeCallback(promise, callback); + return promise; +} + +// Retrieve an item from the store. Unlike the original async_storage +// library in Gaia, we don't modify return values at all. If a key's value +// is `undefined`, we pass that value to the callback function. +function getItem$2(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var result = localStorage.getItem(dbInfo.keyPrefix + key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the key + // is likely undefined and we'll pass it straight to the + // callback. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; +} + +// Iterate over all items in the store. +function iterate$2(iterator, callback) { + var self = this; + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var keyPrefix = dbInfo.keyPrefix; + var keyPrefixLength = keyPrefix.length; + var length = localStorage.length; + + // We use a dedicated iterator instead of the `i` variable below + // so other keys we fetch in localStorage aren't counted in + // the `iterationNumber` argument passed to the `iterate()` + // callback. + // + // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 + var iterationNumber = 1; + + for (var i = 0; i < length; i++) { + var key = localStorage.key(i); + if (key.indexOf(keyPrefix) !== 0) { + continue; + } + var value = localStorage.getItem(key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the + // key is likely undefined and we'll pass it straight + // to the iterator. + if (value) { + value = dbInfo.serializer.deserialize(value); + } + + value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); + + if (value !== void 0) { + return value; + } + } + }); + + executeCallback(promise, callback); + return promise; +} + +// Same as localStorage's key() method, except takes a callback. +function key$2(n, callback) { + var self = this; + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var result; + try { + result = localStorage.key(n); + } catch (error) { + result = null; + } + + // Remove the prefix from the key, if a key is found. + if (result) { + result = result.substring(dbInfo.keyPrefix.length); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; +} + +function keys$2(callback) { + var self = this; + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var length = localStorage.length; + var keys = []; + + for (var i = 0; i < length; i++) { + var itemKey = localStorage.key(i); + if (itemKey.indexOf(dbInfo.keyPrefix) === 0) { + keys.push(itemKey.substring(dbInfo.keyPrefix.length)); + } + } + + return keys; + }); + + executeCallback(promise, callback); + return promise; +} + +// Supply the number of keys in the datastore to the callback function. +function length$2(callback) { + var self = this; + var promise = self.keys().then(function (keys) { + return keys.length; + }); + + executeCallback(promise, callback); + return promise; +} + +// Remove an item from the store, nice and simple. +function removeItem$2(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + localStorage.removeItem(dbInfo.keyPrefix + key); + }); + + executeCallback(promise, callback); + return promise; +} + +// Set a key's value and run an optional callback once the value is set. +// Unlike Gaia's implementation, the callback function is passed the value, +// in case you want to operate on that value only after you're sure it +// saved, or something like that. +function setItem$2(key, value, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = self.ready().then(function () { + // Convert undefined values to null. + // https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + return new Promise$1(function (resolve, reject) { + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function (value, error) { + if (error) { + reject(error); + } else { + try { + localStorage.setItem(dbInfo.keyPrefix + key, value); + resolve(originalValue); + } catch (e) { + // localStorage capacity exceeded. + // TODO: Make this a specific error/event. + if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { + reject(e); + } + reject(e); + } + } + }); + }); + }); + + executeCallback(promise, callback); + return promise; +} + +function dropInstance$2(options, callback) { + callback = getCallback.apply(this, arguments); + + options = typeof options !== 'function' && options || {}; + if (!options.name) { + var currentConfig = this.config(); + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + + var self = this; + var promise; + if (!options.name) { + promise = Promise$1.reject('Invalid arguments'); + } else { + promise = new Promise$1(function (resolve) { + if (!options.storeName) { + resolve(options.name + '/'); + } else { + resolve(_getKeyPrefix(options, self._defaultConfig)); + } + }).then(function (keyPrefix) { + for (var i = localStorage.length - 1; i >= 0; i--) { + var key = localStorage.key(i); + + if (key.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key); + } + } + }); + } + + executeCallback(promise, callback); + return promise; +} + +var localStorageWrapper = { + _driver: 'localStorageWrapper', + _initStorage: _initStorage$2, + _support: isLocalStorageValid(), + iterate: iterate$2, + getItem: getItem$2, + setItem: setItem$2, + removeItem: removeItem$2, + clear: clear$2, + length: length$2, + key: key$2, + keys: keys$2, + dropInstance: dropInstance$2 +}; + +var sameValue = function sameValue(x, y) { + return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y); +}; + +var includes = function includes(array, searchElement) { + var len = array.length; + var i = 0; + while (i < len) { + if (sameValue(array[i], searchElement)) { + return true; + } + i++; + } + + return false; +}; + +var isArray = Array.isArray || function (arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; +}; + +// Drivers are stored here when `defineDriver()` is called. +// They are shared across all instances of localForage. +var DefinedDrivers = {}; + +var DriverSupport = {}; + +var DefaultDrivers = { + INDEXEDDB: asyncStorage, + WEBSQL: webSQLStorage, + LOCALSTORAGE: localStorageWrapper +}; + +var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver]; + +var OptionalDriverMethods = ['dropInstance']; + +var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods); + +var DefaultConfig = { + description: '', + driver: DefaultDriverOrder.slice(), + name: 'localforage', + // Default DB size is _JUST UNDER_ 5MB, as it's the highest size + // we can use without a prompt. + size: 4980736, + storeName: 'keyvaluepairs', + version: 1.0 +}; + +function callWhenReady(localForageInstance, libraryMethod) { + localForageInstance[libraryMethod] = function () { + var _args = arguments; + return localForageInstance.ready().then(function () { + return localForageInstance[libraryMethod].apply(localForageInstance, _args); + }); + }; +} + +function extend() { + for (var i = 1; i < arguments.length; i++) { + var arg = arguments[i]; + + if (arg) { + for (var _key in arg) { + if (arg.hasOwnProperty(_key)) { + if (isArray(arg[_key])) { + arguments[0][_key] = arg[_key].slice(); + } else { + arguments[0][_key] = arg[_key]; + } + } + } + } + } + + return arguments[0]; +} + +var LocalForage = function () { + function LocalForage(options) { + _classCallCheck(this, LocalForage); + + for (var driverTypeKey in DefaultDrivers) { + if (DefaultDrivers.hasOwnProperty(driverTypeKey)) { + var driver = DefaultDrivers[driverTypeKey]; + var driverName = driver._driver; + this[driverTypeKey] = driverName; + + if (!DefinedDrivers[driverName]) { + // we don't need to wait for the promise, + // since the default drivers can be defined + // in a blocking manner + this.defineDriver(driver); + } + } + } + + this._defaultConfig = extend({}, DefaultConfig); + this._config = extend({}, this._defaultConfig, options); + this._driverSet = null; + this._initDriver = null; + this._ready = false; + this._dbInfo = null; + + this._wrapLibraryMethodsWithReady(); + this.setDriver(this._config.driver)["catch"](function () {}); + } + + // Set any config values for localForage; can be called anytime before + // the first API call (e.g. `getItem`, `setItem`). + // We loop through options so we don't overwrite existing config + // values. + + + LocalForage.prototype.config = function config(options) { + // If the options argument is an object, we use it to set values. + // Otherwise, we return either a specified config value or all + // config values. + if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { + // If localforage is ready and fully initialized, we can't set + // any new configuration values. Instead, we return an error. + if (this._ready) { + return new Error("Can't call config() after localforage " + 'has been used.'); + } + + for (var i in options) { + if (i === 'storeName') { + options[i] = options[i].replace(/\W/g, '_'); + } + + if (i === 'version' && typeof options[i] !== 'number') { + return new Error('Database version must be a number.'); + } + + this._config[i] = options[i]; + } + + // after all config options are set and + // the driver option is used, try setting it + if ('driver' in options && options.driver) { + return this.setDriver(this._config.driver); + } + + return true; + } else if (typeof options === 'string') { + return this._config[options]; + } else { + return this._config; + } + }; + + // Used to define a custom driver, shared across all instances of + // localForage. + + + LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { + var promise = new Promise$1(function (resolve, reject) { + try { + var driverName = driverObject._driver; + var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); + + // A driver name should be defined and not overlap with the + // library-defined, default drivers. + if (!driverObject._driver) { + reject(complianceError); + return; + } + + var driverMethods = LibraryMethods.concat('_initStorage'); + for (var i = 0, len = driverMethods.length; i < len; i++) { + var driverMethodName = driverMethods[i]; + + // when the property is there, + // it should be a method even when optional + var isRequired = !includes(OptionalDriverMethods, driverMethodName); + if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') { + reject(complianceError); + return; + } + } + + var configureMissingMethods = function configureMissingMethods() { + var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) { + return function () { + var error = new Error('Method ' + methodName + ' is not implemented by the current driver'); + var promise = Promise$1.reject(error); + executeCallback(promise, arguments[arguments.length - 1]); + return promise; + }; + }; + + for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) { + var optionalDriverMethod = OptionalDriverMethods[_i]; + if (!driverObject[optionalDriverMethod]) { + driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod); + } + } + }; + + configureMissingMethods(); + + var setDriverSupport = function setDriverSupport(support) { + if (DefinedDrivers[driverName]) { + console.info('Redefining LocalForage driver: ' + driverName); + } + DefinedDrivers[driverName] = driverObject; + DriverSupport[driverName] = support; + // don't use a then, so that we can define + // drivers that have simple _support methods + // in a blocking manner + resolve(); + }; + + if ('_support' in driverObject) { + if (driverObject._support && typeof driverObject._support === 'function') { + driverObject._support().then(setDriverSupport, reject); + } else { + setDriverSupport(!!driverObject._support); + } + } else { + setDriverSupport(true); + } + } catch (e) { + reject(e); + } + }); + + executeTwoCallbacks(promise, callback, errorCallback); + return promise; + }; + + LocalForage.prototype.driver = function driver() { + return this._driver || null; + }; + + LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { + var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.')); + + executeTwoCallbacks(getDriverPromise, callback, errorCallback); + return getDriverPromise; + }; + + LocalForage.prototype.getSerializer = function getSerializer(callback) { + var serializerPromise = Promise$1.resolve(localforageSerializer); + executeTwoCallbacks(serializerPromise, callback); + return serializerPromise; + }; + + LocalForage.prototype.ready = function ready(callback) { + var self = this; + + var promise = self._driverSet.then(function () { + if (self._ready === null) { + self._ready = self._initDriver(); + } + + return self._ready; + }); + + executeTwoCallbacks(promise, callback, callback); + return promise; + }; + + LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { + var self = this; + + if (!isArray(drivers)) { + drivers = [drivers]; + } + + var supportedDrivers = this._getSupportedDrivers(drivers); + + function setDriverToConfig() { + self._config.driver = self.driver(); + } + + function extendSelfWithDriver(driver) { + self._extend(driver); + setDriverToConfig(); + + self._ready = self._initStorage(self._config); + return self._ready; + } + + function initDriver(supportedDrivers) { + return function () { + var currentDriverIndex = 0; + + function driverPromiseLoop() { + while (currentDriverIndex < supportedDrivers.length) { + var driverName = supportedDrivers[currentDriverIndex]; + currentDriverIndex++; + + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop); + } + + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise$1.reject(error); + return self._driverSet; + } + + return driverPromiseLoop(); + }; + } + + // There might be a driver initialization in progress + // so wait for it to finish in order to avoid a possible + // race condition to set _dbInfo + var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () { + return Promise$1.resolve(); + }) : Promise$1.resolve(); + + this._driverSet = oldDriverSetDone.then(function () { + var driverName = supportedDrivers[0]; + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName).then(function (driver) { + self._driver = driver._driver; + setDriverToConfig(); + self._wrapLibraryMethodsWithReady(); + self._initDriver = initDriver(supportedDrivers); + }); + })["catch"](function () { + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise$1.reject(error); + return self._driverSet; + }); + + executeTwoCallbacks(this._driverSet, callback, errorCallback); + return this._driverSet; + }; + + LocalForage.prototype.supports = function supports(driverName) { + return !!DriverSupport[driverName]; + }; + + LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { + extend(this, libraryMethodsAndProperties); + }; + + LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { + var supportedDrivers = []; + for (var i = 0, len = drivers.length; i < len; i++) { + var driverName = drivers[i]; + if (this.supports(driverName)) { + supportedDrivers.push(driverName); + } + } + return supportedDrivers; + }; + + LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { + // Add a stub for each driver API method that delays the call to the + // corresponding driver method until localForage is ready. These stubs + // will be replaced by the driver methods as soon as the driver is + // loaded, so there is no performance impact. + for (var i = 0, len = LibraryMethods.length; i < len; i++) { + callWhenReady(this, LibraryMethods[i]); + } + }; + + LocalForage.prototype.createInstance = function createInstance(options) { + return new LocalForage(options); + }; + + return LocalForage; +}(); + +// The actual localForage object that we expose as a module or via a +// global. It's extended by pulling in one of our other libraries. + + +var localforage_js = new LocalForage(); + +module.exports = localforage_js; + +},{"3":3}]},{},[4])(4) +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],21:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var uuid = require('uuid'); + +module.exports = { + generate: function() { + var unordered = uuid.v1(); + return unordered.substr(14, 4) + unordered.substr(9, 4) + unordered.substr(0, 8) + unordered.substr(19, 4) + unordered.substr(24, unordered.length); + }, + + toBinary16: function(orderedUuid) { + return new Buffer(orderedUuid, 'hex'); + }, + + fromBinary16: function(binaryOrderedUuid) { + return binaryOrderedUuid.toString('hex'); + } +}; + +}).call(this,require("buffer").Buffer) +},{"buffer":28,"uuid":22}],22:[function(require,module,exports){ +var v1 = require('./v1'); +var v4 = require('./v4'); + +var uuid = v4; +uuid.v1 = v1; +uuid.v4 = v4; + +module.exports = uuid; + +},{"./v1":25,"./v4":26}],23:[function(require,module,exports){ +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +var byteToHex = []; +for (var i = 0; i < 256; ++i) { + byteToHex[i] = (i + 0x100).toString(16).substr(1); +} + +function bytesToUuid(buf, offset) { + var i = offset || 0; + var bth = byteToHex; + // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 + return ([ + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]] + ]).join(''); +} + +module.exports = bytesToUuid; + +},{}],24:[function(require,module,exports){ +// Unique ID creation requires a high quality random # generator. In the +// browser this is a little complicated due to unknown quality of Math.random() +// and inconsistent support for the `crypto` API. We do the best we can via +// feature-detection + +// getRandomValues needs to be invoked in a context where "this" is a Crypto +// implementation. Also, find the complete implementation of crypto on IE11. +var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) || + (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto)); + +if (getRandomValues) { + // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto + var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef + + module.exports = function whatwgRNG() { + getRandomValues(rnds8); + return rnds8; + }; +} else { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var rnds = new Array(16); + + module.exports = function mathRNG() { + for (var i = 0, r; i < 16; i++) { + if ((i & 0x03) === 0) r = Math.random() * 0x100000000; + rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; + } + + return rnds; + }; +} + +},{}],25:[function(require,module,exports){ +var rng = require('./lib/rng'); +var bytesToUuid = require('./lib/bytesToUuid'); + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +var _nodeId; +var _clockseq; + +// Previous uuid creation time +var _lastMSecs = 0; +var _lastNSecs = 0; + +// See https://github.com/uuidjs/uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; + + options = options || {}; + var node = options.node || _nodeId; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + + // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + if (node == null || clockseq == null) { + var seedBytes = rng(); + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [ + seedBytes[0] | 0x01, + seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] + ]; + } + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } + + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } + + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; + + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; + + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf ? buf : bytesToUuid(b); +} + +module.exports = v1; + +},{"./lib/bytesToUuid":23,"./lib/rng":24}],26:[function(require,module,exports){ +var rng = require('./lib/rng'); +var bytesToUuid = require('./lib/bytesToUuid'); + +function v4(options, buf, offset) { + var i = buf && offset || 0; + + if (typeof(options) == 'string') { + buf = options === 'binary' ? new Array(16) : null; + options = null; + } + options = options || {}; + + var rnds = options.random || (options.rng || rng)(); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ++ii) { + buf[i + ii] = rnds[ii]; + } + } + + return buf || bytesToUuid(rnds); +} + +module.exports = v4; + +},{"./lib/bytesToUuid":23,"./lib/rng":24}],27:[function(require,module,exports){ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + +},{}],28:[function(require,module,exports){ +(function (Buffer){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species != null && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayLike(value) + } + + if (value == null) { + throw TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + buf = Buffer.from(buf) + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +}).call(this,require("buffer").Buffer) +},{"base64-js":27,"buffer":28,"ieee754":29}],29:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}]},{},[1])(1) +}); diff --git a/public/motionity/src/js/libraries/pickr.min.js b/public/motionity/src/js/libraries/pickr.min.js new file mode 100644 index 000000000..eed0a8f47 --- /dev/null +++ b/public/motionity/src/js/libraries/pickr.min.js @@ -0,0 +1,5 @@ +/*! Pickr 1.7.2 MIT | https://github.com/Simonwep/pickr */ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Pickr=e():t.Pickr=e()}(window,(function(){return function(t){var e={};function o(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,o),i.l=!0,i.exports}return o.m=t,o.c=e,o.d=function(t,e,n){o.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},o.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},o.t=function(t,e){if(1&e&&(t=o(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)o.d(n,i,function(e){return t[e]}.bind(null,i));return n},o.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return o.d(e,"a",e),e},o.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},o.p="",o(o.s=1)}([function(t){t.exports=JSON.parse('{"a":"1.7.2"}')},function(t,e,o){"use strict";o.r(e);var n={};function i(t,e,o,n,i={}){e instanceof HTMLCollection||e instanceof NodeList?e=Array.from(e):Array.isArray(e)||(e=[e]),Array.isArray(o)||(o=[o]);for(const r of e)for(const e of o)r[t](e,n,{capture:!1,...i});return Array.prototype.slice.call(arguments,1)}o.r(n),o.d(n,"on",(function(){return r})),o.d(n,"off",(function(){return s})),o.d(n,"createElementFromString",(function(){return a})),o.d(n,"createFromTemplate",(function(){return c})),o.d(n,"eventPath",(function(){return l})),o.d(n,"resolveElement",(function(){return p})),o.d(n,"adjustableInputNumbers",(function(){return u}));const r=i.bind(null,"addEventListener"),s=i.bind(null,"removeEventListener");function a(t){const e=document.createElement("div");return e.innerHTML=t.trim(),e.firstElementChild}function c(t){const e=(t,e)=>{const o=t.getAttribute(e);return t.removeAttribute(e),o},o=(t,n={})=>{const i=e(t,":obj"),r=e(t,":ref"),s=i?n[i]={}:n;r&&(n[r]=t);for(const n of Array.from(t.children)){const t=e(n,":arr"),i=o(n,t?{}:s);t&&(s[t]||(s[t]=[])).push(Object.keys(i).length?i:n)}return n};return o(a(t))}function l(t){let e=t.path||t.composedPath&&t.composedPath();if(e)return e;let o=t.target.parentElement;for(e=[t.target,o];o=o.parentElement;)e.push(o);return e.push(document,window),e}function p(t){return t instanceof Element?t:"string"==typeof t?t.split(/>>/g).reduce((t,e,o,n)=>(t=t.querySelector(e),ot)){function o(o){const n=[.001,.01,.1][Number(o.shiftKey||2*o.ctrlKey)]*(o.deltaY<0?1:-1);let i=0,r=t.selectionStart;t.value=t.value.replace(/[\d.]+/g,(t,o)=>o<=r&&o+t.length>=r?(r=o,e(Number(t),n,i)):(i++,t)),t.focus(),t.setSelectionRange(r,r),o.preventDefault(),t.dispatchEvent(new Event("input"))}r(t,"focus",()=>r(window,"wheel",o,{passive:!1})),r(t,"blur",()=>s(window,"wheel",o))}var h=o(0);const{min:d,max:f,floor:m,round:v}=Math;function b(t,e,o){e/=100,o/=100;const n=m(t=t/360*6),i=t-n,r=o*(1-e),s=o*(1-i*e),a=o*(1-(1-i)*e),c=n%6;return[255*[o,s,r,r,a,o][c],255*[a,o,o,s,r,r][c],255*[r,r,a,o,o,s][c]]}function g(t,e,o){const n=(2-(e/=100))*(o/=100)/2;return 0!==n&&(e=1===n?0:n<.5?e*o/(2*n):e*o/(2-2*n)),[t,100*e,100*n]}function y(t,e,o){const n=d(t/=255,e/=255,o/=255),i=f(t,e,o),r=i-n;let s,a;if(0===r)s=a=0;else{a=r/i;const n=((i-t)/6+r/2)/r,c=((i-e)/6+r/2)/r,l=((i-o)/6+r/2)/r;t===i?s=l-c:e===i?s=1/3+n-l:o===i&&(s=2/3+c-n),s<0?s+=1:s>1&&(s-=1)}return[360*s,100*a,100*i]}function _(t,e,o,n){return e/=100,o/=100,[...y(255*(1-d(1,(t/=100)*(1-(n/=100))+n)),255*(1-d(1,e*(1-n)+n)),255*(1-d(1,o*(1-n)+n)))]}function w(t,e,o){e/=100;const n=2*(e*=(o/=100)<.5?o:1-o)/(o+e)*100,i=100*(o+e);return[t,isNaN(n)?0:n,i]}function A(t){return y(...t.match(/.{2}/g).map(t=>parseInt(t,16)))}function C(t){t=t.match(/^[a-zA-Z]+$/)?function(t){if("black"===t.toLowerCase())return"#000";const e=document.createElement("canvas").getContext("2d");return e.fillStyle=t,"#000"===e.fillStyle?null:e.fillStyle}(t):t;const e={cmyk:/^cmyk[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)/i,rgba:/^((rgba)|rgb)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hsla:/^((hsla)|hsl)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hsva:/^((hsva)|hsv)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hexa:/^#?(([\dA-Fa-f]{3,4})|([\dA-Fa-f]{6})|([\dA-Fa-f]{8}))$/i},o=t=>t.map(t=>/^(|\d+)\.\d+|\d+$/.test(t)?Number(t):void 0);let n;t:for(const i in e){if(!(n=e[i].exec(t)))continue;const r=t=>!!n[2]==("number"==typeof t);switch(i){case"cmyk":{const[,t,e,r,s]=o(n);if(t>100||e>100||r>100||s>100)break t;return{values:_(t,e,r,s),type:i}}case"rgba":{const[,,,t,e,s,a]=o(n);if(t>255||e>255||s>255||a<0||a>1||!r(a))break t;return{values:[...y(t,e,s),a],a:a,type:i}}case"hexa":{let[,t]=n;4!==t.length&&3!==t.length||(t=t.split("").map(t=>t+t).join(""));const e=t.substring(0,6);let o=t.substring(6);return o=o?parseInt(o,16)/255:void 0,{values:[...A(e),o],a:o,type:i}}case"hsla":{const[,,,t,e,s,a]=o(n);if(t>360||e>100||s>100||a<0||a>1||!r(a))break t;return{values:[...w(t,e,s),a],a:a,type:i}}case"hsva":{const[,,,t,e,s,a]=o(n);if(t>360||e>100||s>100||a<0||a>1||!r(a))break t;return{values:[t,e,s,a],a:a,type:i}}}}return{values:null,type:null}}function k(t=0,e=0,o=0,n=1){const i=(t,e)=>(o=-1)=>e(~o?t.map(t=>Number(t.toFixed(o))):t),r={h:t,s:e,v:o,a:n,toHSVA(){const t=[r.h,r.s,r.v,r.a];return t.toString=i(t,t=>"hsva(".concat(t[0],", ").concat(t[1],"%, ").concat(t[2],"%, ").concat(r.a,")")),t},toHSLA(){const t=[...g(r.h,r.s,r.v),r.a];return t.toString=i(t,t=>"hsla(".concat(t[0],", ").concat(t[1],"%, ").concat(t[2],"%, ").concat(r.a,")")),t},toRGBA(){const t=[...b(r.h,r.s,r.v),r.a];return t.toString=i(t,t=>"rgba(".concat(t[0],", ").concat(t[1],", ").concat(t[2],", ").concat(r.a,")")),t},toCMYK(){const t=function(t,e,o){const n=b(t,e,o),i=n[0]/255,r=n[1]/255,s=n[2]/255,a=d(1-i,1-r,1-s);return[100*(1===a?0:(1-i-a)/(1-a)),100*(1===a?0:(1-r-a)/(1-a)),100*(1===a?0:(1-s-a)/(1-a)),100*a]}(r.h,r.s,r.v);return t.toString=i(t,t=>"cmyk(".concat(t[0],"%, ").concat(t[1],"%, ").concat(t[2],"%, ").concat(t[3],"%)")),t},toHEXA(){const t=function(t,e,o){return b(t,e,o).map(t=>v(t).toString(16).padStart(2,"0"))}(r.h,r.s,r.v),e=r.a>=1?"":Number((255*r.a).toFixed(0)).toString(16).toUpperCase().padStart(2,"0");return e&&t.push(e),t.toString=()=>"#".concat(t.join("").toUpperCase()),t},clone:()=>k(r.h,r.s,r.v,r.a)};return r}const S=t=>Math.max(Math.min(t,1),0);function O(t){const e={options:Object.assign({lock:null,onchange:()=>0,onstop:()=>0},t),_keyboard(t){const{options:o}=e,{type:n,key:i}=t;if(document.activeElement===o.wrapper){const{lock:o}=e.options,r="ArrowUp"===i,s="ArrowRight"===i,a="ArrowDown"===i,c="ArrowLeft"===i;if("keydown"===n&&(r||s||a||c)){let n=0,i=0;"v"===o?n=r||s?1:-1:"h"===o?n=r||s?-1:1:(i=r?-1:a?1:0,n=c?-1:s?1:0),e.update(S(e.cache.x+.01*n),S(e.cache.y+.01*i)),t.preventDefault()}else i.startsWith("Arrow")&&(e.options.onstop(),t.preventDefault())}},_tapstart(t){r(document,["mouseup","touchend","touchcancel"],e._tapstop),r(document,["mousemove","touchmove"],e._tapmove),t.cancelable&&t.preventDefault(),e._tapmove(t)},_tapmove(t){const{options:o,cache:n}=e,{lock:i,element:r,wrapper:s}=o,a=s.getBoundingClientRect();let c=0,l=0;if(t){const e=t&&t.touches&&t.touches[0];c=t?(e||t).clientX:0,l=t?(e||t).clientY:0,ca.left+a.width&&(c=a.left+a.width),la.top+a.height&&(l=a.top+a.height),c-=a.left,l-=a.top}else n&&(c=n.x*a.width,l=n.y*a.height);"h"!==i&&(r.style.left="calc(".concat(c/a.width*100,"% - ").concat(r.offsetWidth/2,"px)")),"v"!==i&&(r.style.top="calc(".concat(l/a.height*100,"% - ").concat(r.offsetHeight/2,"px)")),e.cache={x:c/a.width,y:l/a.height};const p=S(c/a.width),u=S(l/a.height);switch(i){case"v":return o.onchange(p);case"h":return o.onchange(u);default:return o.onchange(p,u)}},_tapstop(){e.options.onstop(),s(document,["mouseup","touchend","touchcancel"],e._tapstop),s(document,["mousemove","touchmove"],e._tapmove)},trigger(){e._tapmove()},update(t=0,o=0){const{left:n,top:i,width:r,height:s}=e.options.wrapper.getBoundingClientRect();"h"===e.options.lock&&(o=t),e._tapmove({clientX:n+r*t,clientY:i+s*o})},destroy(){const{options:t,_tapstart:o,_keyboard:n}=e;s(document,["keydown","keyup"],n),s([t.wrapper,t.element],"mousedown",o),s([t.wrapper,t.element],"touchstart",o,{passive:!1})}},{options:o,_tapstart:n,_keyboard:i}=e;return r([o.wrapper,o.element],"mousedown",n),r([o.wrapper,o.element],"touchstart",n,{passive:!1}),r(document,["keydown","keyup"],i),e}function E(t={}){t=Object.assign({onchange:()=>0,className:"",elements:[]},t);const e=r(t.elements,"click",e=>{t.elements.forEach(o=>o.classList[e.target===o?"add":"remove"](t.className)),t.onchange(e)});return{destroy:()=>s(...e)}} +/*! NanoPop 1.3.0 MIT | https://github.com/Simonwep/nanopop */ +let x=(()=>{class t{constructor(e,o,{positionFlipOrder:n=t.defaultPositionFlipOrder,variantFlipOrder:i=t.defaultVariantFlipOrder,container:r=document.documentElement.getBoundingClientRect(),forceApplyOnFailure:s=!1,margin:a=8,position:c="bottom-start"}={}){this.o={positionFlipOrder:n,variantFlipOrder:i,reference:e,popper:o,position:c,container:r,forceApplyOnFailure:s,margin:a}}update(t=this.o,e=!1){const{container:o,reference:n,popper:i,margin:r,position:s,forceApplyOnFailure:a,variantFlipOrder:c,positionFlipOrder:l}=this.o={...this.o,...t};i.style.left="0",i.style.top="0";const p=n.getBoundingClientRect(),u=i.getBoundingClientRect(),h={t:p.top-u.height-r,b:p.bottom+r,r:p.right+r,l:p.left-u.width-r},d={vm:-u.width/2+(p.left+p.width/2),vs:p.left,ve:p.left+p.width-u.width,hs:p.bottom-p.height,he:p.bottom-u.height,hm:p.bottom-p.height/2-u.height/2},[f,m="middle"]=s.split("-"),v=l[f],b=c[m],{top:g,left:y,bottom:_,right:w}=o;for(const t of v){const o="t"===t||"b"===t,n=h[t],[r,s]=o?["top","left"]:["left","top"],[a,c]=o?[u.height,u.width]:[u.width,u.height],[l,p]=o?[_,w]:[w,_],[f,m]=o?[g,y]:[y,g];if(e||!(nl))for(const a of b){const l=d[(o?"v":"h")+a];if(e||!(lp))return i.style[s]=l-u[s]+"px",i.style[r]=n-u[r]+"px",t+a}}return a?this.update(void 0,!0):null}}return t.version="1.3.0",t.defaultVariantFlipOrder={start:"sme",middle:"mse",end:"ems"},t.defaultPositionFlipOrder={top:"tbrl",right:"rltb",bottom:"btrl",left:"lrbt"},t})();function L(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}class B{constructor(t){L(this,"_initializingActive",!0),L(this,"_recalc",!0),L(this,"_nanopop",null),L(this,"_root",null),L(this,"_color",k()),L(this,"_lastColor",k()),L(this,"_swatchColors",[]),L(this,"_eventListener",{init:[],save:[],hide:[],show:[],clear:[],change:[],changestop:[],cancel:[],swatchselect:[]}),this.options=t=Object.assign({...B.DEFAULT_OPTIONS},t);const{swatches:e,components:o,theme:n,sliders:i,lockOpacity:r,padding:s}=t;["nano","monolith"].includes(n)&&!i&&(t.sliders="h"),o.interaction||(o.interaction={});const{preview:a,opacity:c,hue:l,palette:p}=o;o.opacity=!r&&c,o.palette=p||a||c||l,this._preBuild(),this._buildComponents(),this._bindEvents(),this._finalBuild(),e&&e.length&&e.forEach(t=>this.addSwatch(t));const{button:u,app:h}=this._root;this._nanopop=new x(u,h,{margin:s}),u.setAttribute("role","button"),u.setAttribute("aria-label",this._t("btn:toggle"));const d=this;requestAnimationFrame((function e(){if(!h.offsetWidth)return requestAnimationFrame(e);d.setColor(t.default),d._rePositioningPicker(),t.defaultRepresentation&&(d._representation=t.defaultRepresentation,d.setColorRepresentation(d._representation)),t.showAlways&&d.show(),d._initializingActive=!1,d._emit("init")}))}_preBuild(){const{options:t}=this;for(const e of["el","container"])t[e]=p(t[e]);this._root=(t=>{const{components:e,useAsButton:o,inline:n,appClass:i,theme:r,lockOpacity:s}=t.options,a=t=>t?"":'style="display:none" hidden',l=e=>t._t(e),p=c('\n
    \n\n '.concat(o?"":'','\n\n
    \n
    \n
    \n \n
    \n
    \n\n
    \n
    \n
    \n
    \n\n
    \n
    \n
    \n
    \n\n
    \n
    \n
    \n
    \n
    \n\n
    \n\n
    \n \n\n \n \n \n \n \n\n \n \n \n
    \n
    \n
    \n ')),u=p.interaction;return u.options.find(t=>!t.hidden&&!t.classList.add("active")),u.type=()=>u.options.find(t=>t.classList.contains("active")),p})(this),t.useAsButton&&(this._root.button=t.el),t.container.appendChild(this._root.root)}_finalBuild(){const t=this.options,e=this._root;if(t.container.removeChild(e.root),t.inline){const o=t.el.parentElement;t.el.nextSibling?o.insertBefore(e.app,t.el.nextSibling):o.appendChild(e.app)}else t.container.appendChild(e.app);t.useAsButton?t.inline&&t.el.remove():t.el.parentNode.replaceChild(e.root,t.el),t.disabled&&this.disable(),t.comparison||(e.button.style.transition="none",t.useAsButton||(e.preview.lastColor.style.transition="none")),this.hide()}_buildComponents(){const t=this,e=this.options.components,o=(t.options.sliders||"v").repeat(2),[n,i]=o.match(/^[vh]+$/g)?o:[],r=()=>this._color||(this._color=this._lastColor.clone()),s={palette:O({element:t._root.palette.picker,wrapper:t._root.palette.palette,onstop:()=>t._emit("changestop",t),onchange(o,n){if(!e.palette)return;const i=r(),{_root:s,options:a}=t,{lastColor:c,currentColor:l}=s.preview;t._recalc&&(i.s=100*o,i.v=100-100*n,i.v<0&&(i.v=0),t._updateOutput());const p=i.toRGBA().toString(0);this.element.style.background=p,this.wrapper.style.background="\n linear-gradient(to top, rgba(0, 0, 0, ".concat(i.a,"), transparent),\n linear-gradient(to left, hsla(").concat(i.h,", 100%, 50%, ").concat(i.a,"), rgba(255, 255, 255, ").concat(i.a,"))\n "),a.comparison?a.useAsButton||t._lastColor||(c.style.color=p):(s.button.style.color=p,s.button.classList.remove("clear"));const u=i.toHEXA().toString();for(const{el:e,color:o}of t._swatchColors)e.classList[u===o.toHEXA().toString()?"add":"remove"]("pcr-active");l.style.color=p}}),hue:O({lock:"v"===i?"h":"v",element:t._root.hue.picker,wrapper:t._root.hue.slider,onstop:()=>t._emit("changestop",t),onchange(o){if(!e.hue||!e.palette)return;const n=r();t._recalc&&(n.h=360*o),this.element.style.backgroundColor="hsl(".concat(n.h,", 100%, 50%)"),s.palette.trigger()}}),opacity:O({lock:"v"===n?"h":"v",element:t._root.opacity.picker,wrapper:t._root.opacity.slider,onstop:()=>t._emit("changestop",t),onchange(o){if(!e.opacity||!e.palette)return;const n=r();t._recalc&&(n.a=Math.round(100*o)/100),this.element.style.background="rgba(0, 0, 0, ".concat(n.a,")"),s.palette.trigger()}}),selectable:E({elements:t._root.interaction.options,className:"active",onchange(e){t._representation=e.target.getAttribute("data-type").toUpperCase(),t._recalc&&t._updateOutput()}})};this._components=s}_bindEvents(){const{_root:t,options:e}=this,o=[r(t.interaction.clear,"click",()=>this._clearColor()),r([t.interaction.cancel,t.preview.lastColor],"click",()=>{this._emit("cancel",this),this.setHSVA(...(this._lastColor||this._color).toHSVA(),!0)}),r(t.interaction.save,"click",()=>{!this.applyColor()&&!e.showAlways&&this.hide()}),r(t.interaction.result,["keyup","input"],t=>{this.setColor(t.target.value,!0)&&!this._initializingActive&&this._emit("change",this._color),t.stopImmediatePropagation()}),r(t.interaction.result,["focus","blur"],t=>{this._recalc="blur"===t.type,this._recalc&&this._updateOutput()}),r([t.palette.palette,t.palette.picker,t.hue.slider,t.hue.picker,t.opacity.slider,t.opacity.picker],["mousedown","touchstart"],()=>this._recalc=!0,{passive:!0})];if(!e.showAlways){const n=e.closeWithKey;o.push(r(t.button,"click",()=>this.isOpen()?this.hide():this.show()),r(document,"keyup",t=>this.isOpen()&&(t.key===n||t.code===n)&&this.hide()),r(document,["touchstart","mousedown"],e=>{this.isOpen()&&!l(e).some(e=>e===t.app||e===t.button)&&this.hide()},{capture:!0}))}if(e.adjustableNumbers){const e={rgba:[255,255,255,1],hsva:[360,100,100,1],hsla:[360,100,100,1],cmyk:[100,100,100,100]};u(t.interaction.result,(t,o,n)=>{const i=e[this.getColorRepresentation().toLowerCase()];if(i){const e=i[n],r=t+(e>=100?1e3*o:o);return r<=0?0:Number((r{n.isOpen()&&(e.closeOnScroll&&n.hide(),null===t?(t=setTimeout(()=>t=null,100),requestAnimationFrame((function e(){null!==t&&requestAnimationFrame(e)}))):(clearTimeout(t),t=setTimeout(()=>t=null,100)))},{capture:!0}))}this._eventBindings=o}_rePositioningPicker(){const{options:t}=this;if(!t.inline){if(!this._nanopop.update({container:document.body.getBoundingClientRect(),position:t.position,forceApplyOnFailure:!this._recalc})){const t=this._root.app,e=t.getBoundingClientRect();t.style.top="".concat((window.innerHeight-e.height)/2,"px"),t.style.left="".concat((window.innerWidth-e.width)/2,"px")}}}_updateOutput(){const{_root:t,_color:e,options:o}=this;if(t.interaction.type()){const n="to".concat(t.interaction.type().getAttribute("data-type"));t.interaction.result.value="function"==typeof e[n]?e[n]().toString(o.outputPrecision):""}!this._initializingActive&&this._recalc&&this._emit("change",e)}_clearColor(t=!1){const{_root:e,options:o}=this;o.useAsButton||(e.button.style.color="rgba(0, 0, 0, 0.15)"),e.button.classList.add("clear"),o.showAlways||this.hide(),this._lastColor=null,this._initializingActive||t||(this._emit("save",null),this._emit("clear",this))}_parseLocalColor(t){const{values:e,type:o,a:n}=C(t),{lockOpacity:i}=this.options,r=void 0!==n&&1!==n;return e&&3===e.length&&(e[3]=void 0),{values:!e||i&&r?null:e,type:o}}_t(t){return this.options.i18n[t]||B.I18N_DEFAULTS[t]}_emit(t,...e){this._eventListener[t].forEach(t=>t(...e,this))}on(t,e){return this._eventListener[t].push(e),this}off(t,e){const o=this._eventListener[t]||[],n=o.indexOf(e);return~n&&o.splice(n,1),this}addSwatch(t){const{values:e}=this._parseLocalColor(t);if(e){const{_swatchColors:t,_root:o}=this,n=k(...e),i=a('