diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..35fdfaa --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "cSpell.words": [ + "Evented" + ] +} \ No newline at end of file diff --git a/LICENSE b/LICENSE deleted file mode 100644 index f266b53..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 Leandro - -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/README.md b/README.md index 0425698..eb82443 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,162 @@ # ember-theme-changer -This README outlines the details of collaborating on this Ember addon. +This Ember-Addon will help you to switch CSS style files on runtime. + +For example, let's say you want to support multiple themes in your app and each of the theme styles is defined in its own CSS file (I'll show you how easy is to accomplish this on Ember). Ember-theme-changer addon provides an easy mechanism to change themes and subscribe to theme changes in your different components to handle those styles that you couldn't define using stylesheet. + + ## Installation -* `git clone ` this repository -* `cd ember-theme-changer` -* `npm install` -* `bower install` +`ember install ember-theme-changer` + + +## Configuration + +In our example we want to support Dark and Light themes. To accomplish it you must define Ember-Changer available themes in your `config/environment.js` file: + +``` +/* jshint node: true */ +module.exports = function(environment) { + var ENV = { + /* ... */ + theme: { + themes: [ 'light', 'dark'], // MANDATORY + defaultTheme: 'dark', // OPTIONAL + eventName: 'name of the event to be trigger when the theme changes', // OPTIONAL + cookieName: 'name of cookie used to save the current theme value' // OPTIONAL + } + }; + return ENV; +}; +``` + +## Defining themes on Ember. + +There are many mechanism to define themes in your application. In the following example I'll be defining style variables but you can use any mechanism that works better for you. Also, I'll be using Sass preprocessor, but the same solution applies with Less: + +### 1st) Writing multiple theme files + +``` +// app.scss + +// In your app.scss file you can define styles that are dependent on the current theme, or import external styles too +@import "ember-modal-dialog/ember-modal-structure"; +@import "ember-modal-dialog/ember-modal-appearance"; + +body { + width: 100% +} +``` + +``` +// main.scss + +// here is where you define styles that depends on the current theme. All the theme dependent values are referenced with variables. eg: +body { + background-color: $bodyBackgroundColor; +} +``` + +``` +// dark.scss + +// 1) define all the variables you need +$bodyBackgroundColor: '#fff'; +... + +// 2) Import your style fle where the variables will be consumed. +@import 'main'; +``` + +And do the same for the rest of the themes. eg: +``` +// light.scss + +// 1) Define variables +$bodyBackgroundColor: '#000'; +... +// 2) import style file +@import 'main'; +``` + +### 2nd) Generating theme files. +By default, Ember only generates 1 css file based on your app.scss content (or app.less, app.css depending in your your style preprocessor), in this case we want to generate 2 extra files (dark.css & light.css). This is accomplish easily by telling Ember about the extra output files in the `ember-cli-build.js` file: + +``` +// ember-cli-build.js + outputPaths: { + app: { + css: { + 'light': '/assets/light.css', + 'dark': '/assets/dark.css' + } + } + }, +``` +As a result, ember will generate 3 css files (app.css, light.css & dark.css). + +For more info, please read the official Ember-CLI doc: https://ember-cli.com/user-guide/#configuring-output-paths + + + +## Usage + +All interaction with the addon is though the `themeChanger` service. + +### Change themes + +You can circle through the themes invoking the service `toggleTheme` method, or set an specific value with the `theme` property. + + +``` +// your_component.js: + +themeChanger: service(), +.... + +action: { + switchTheme() { + this.get('themeSwitcher').toggleTheme(); + }, + setDarkTheme() { + this.get('themeSwitcher').set('theme', 'dark'); + } +} +``` + +### Theme-change Event + +In some situation you could have some styles defined outside of the CSS boundaries, this addon provides an event you can subscribe to detect changes int he current theme allowing you to execute any code. + -## Running +``` +// your_component.js: +themeChanger: service(), +chartColor, +.... -* `ember serve` -* Visit your app at [http://localhost:4200](http://localhost:4200). + didReceiveAttrs() { + this._super(...arguments); -## Running Tests + // subscribe to the theme changes event + this.get('themeChanger').onThemeChanged((theme) => { -* `npm test` (Runs `ember try:each` to test your addon against multiple Ember versions) -* `ember test` -* `ember test --server` + // your code to handle theme changes: + if (theme === 'light') { + this.set('chartColor', 'black'); + } else { + this.set('chartColor', 'white'); + } + ... + }); -## Building + }, -* `ember build` -For more information on using ember-cli, visit [https://ember-cli.com/](https://ember-cli.com/). + // Its important to unsubscribe to the event when your component will be destroyed + willDestroyElement() { + this.get('themeChanger').offThemeChanged(); + this._super(...arguments); + } +``` \ No newline at end of file diff --git a/addon/.gitkeep b/addon/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/addon/services/theme-changer.js b/addon/services/theme-changer.js new file mode 100644 index 0000000..56dfb1f --- /dev/null +++ b/addon/services/theme-changer.js @@ -0,0 +1,157 @@ +import Ember from 'ember'; + +const { + Service, + Evented, + warn, + isEmpty, + isArray, + getOwner, + computed, + inject: { service } +} = Ember; + +const LINK_TAG_ID = 'ember-theme-changer-stylesheet'; + +export default Service.extend(Evented, { + + cookies: service(), + _themeName: null, + defaultTheme: null, + cookieName: 'ember-theme-changer__current-theme', + eventName: 'ember-theme-changer__theme-changed', + themes: [], + + // @private + init() { + this._super(...arguments); + let owner = getOwner(this); + let ENV = owner.factoryFor('config:environment').class; + + let defaultTheme = null; + if (!ENV.theme) { + warn('Ember-theme-changer did not find a theme configuration.\neg: themes: { themes: [\'theme1\', \'theme2\',...] }.', false, + { id: 'ember-theme-changer.theme' }); + } else { + + if (ENV.theme.themes == null) { + warn('Ember-theme-changer did not find themes in your environment file.\neg: themes: { themes: [\'theme1\', \'theme2\',...] }.', + false, + { id: 'ember-theme-changer.themes' }); + } else if (isEmpty(ENV.theme.themes)) { + warn('Ember-theme-changer requires themes to be defined. Please add an array of supported themes in your Environment file.\neg: themes: { themes: [\'theme1\', \'theme2\',...] }.', false, + { id: 'ember-theme-changer.themes.empty' }); + } else if (!isArray(ENV.theme.themes)) { + warn('Ember-theme-changer requires the themes configuration to be an array. Please add an array of supported themes in your Environment file.\neg: themes: { themes: [\'theme1\', \'theme2\',...] }.', + false, + { id: 'ember-theme-changer.themes.array' }); + } else { + this.set('themes', ENV.theme.themes); + defaultTheme = (ENV.theme || {}).defaultTheme; + if (defaultTheme == null) { + defaultTheme = ENV.theme.themes.get('firstObject'); + warn(`ember-theme-changer did not find a default theme; falling back to "${defaultTheme}".`, + false, { + id: 'ember-theme.changer.default-theme' + }); + } else { + if (!ENV.theme.themes.includes(defaultTheme)) { + const firstTheme = ENV.theme.themes.get('firstObject'); + warn(`ember-theme-changer, default theme \'${defaultTheme}\' is not listed as part of the themes list: \'${ENV.theme.themes}\'. Defaulting to \'${firstTheme}\'.`, + false, { + id: 'ember-theme.changer.invalid-default-theme' + }); + defaultTheme = firstTheme; + } + } + this.set('defaultTheme', defaultTheme); + + // let { cookieName, eventName } = this.getProperties('cookieName', 'eventName'); + if (!isEmpty(ENV.theme.cookieName)) { + this.set('cookieName', ENV.theme.cookieName); + } + if (!isEmpty(ENV.theme.eventName)) { + this.set('eventName', ENV.theme.eventName); + } + + } + } + }, + + // @private + _generateStyleTag() { + + const headTag = document.head; + const linkTag = document.createElement('link'); + linkTag.id = LINK_TAG_ID; + linkTag.rel = 'stylesheet'; + + const { cookies, cookieName, defaultTheme } = this.getProperties('cookies', 'cookieName', 'defaultTheme'); + let themeValue = cookies.read(cookieName) || defaultTheme; + + if (!isEmpty(themeValue)) { + linkTag.href = '/assets/' + themeValue + '.css'; + this.trigger('theme-changed', themeValue); + } + + headTag.appendChild(linkTag); + }, + + // @public + onThemeChanged(callback) { + const eventName = this.get('eventName'); + this.on(eventName, callback); + }, + + // @public + offThemeChanged() { + const eventName = this.get('eventName'); + this.off(eventName); + }, + + // @public + toggleTheme() { + const { themes, theme } = this.getProperties('themes', 'theme'); + const currentIndex = themes.indexOf(theme); + let newTheme = null; + if (currentIndex === theme.length - 1) { + newTheme = themes.get(0); + } else { + newTheme = themes.get(currentIndex+1); + } + + this.set('theme', newTheme); + }, + + // @public + theme: computed({ + get() { + const { cookies, cookieName } = this.getProperties('cookies', 'cookieName'); + let themeValue = cookies.read(cookieName); + if (isEmpty(themeValue)) { + themeValue = this.get('defaultTheme'); + + if (!isEmpty(themeValue)) { + // no theme saved. Using and saving default theme: + cookies.write(cookieName, themeValue, { path: '/', expires: 'Fri, 31 Dec 9999 23:59:59 GMT' }); + const eventName = this.get('eventName'); + this.trigger(eventName, themeValue); + } + } + return themeValue; + }, + set(key, value) { + const { cookies, cookieName, eventName } = this.getProperties('cookies', 'cookieName', 'eventName'); + + // 1- Update the theme value in the cookie + cookies.write(cookieName, value, { path: '/', expires: 'Fri, 31 Dec 9999 23:59:59 GMT' }); + // 2- Uploading the new style + document.getElementById(LINK_TAG_ID).setAttribute("href", '/assets/' + value + '.css'); + // 3- Triggering theme-change notification + this.trigger(eventName, value); + + return value; + } + }) + +}); diff --git a/app/.gitkeep b/app/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/app/instance-initializers/theme-init.js b/app/instance-initializers/theme-init.js new file mode 100644 index 0000000..9ce4bf6 --- /dev/null +++ b/app/instance-initializers/theme-init.js @@ -0,0 +1,9 @@ +export function initialize(applicationInstance) { + let themes = applicationInstance.lookup('service:theme-changer'); + themes._generateStyleTag(); +} + +export default { + name: 'ember-theme-changer-init', + initialize: initialize +}; \ No newline at end of file diff --git a/app/services/theme-changer.js b/app/services/theme-changer.js new file mode 100644 index 0000000..dfad2e1 --- /dev/null +++ b/app/services/theme-changer.js @@ -0,0 +1,3 @@ +import ThemeChanger from 'ember-theme-changer/services/theme-changer'; + +export default ThemeChanger; \ No newline at end of file diff --git a/index.js b/index.js index 3cc4f57..da4fad2 100644 --- a/index.js +++ b/index.js @@ -2,5 +2,8 @@ 'use strict'; module.exports = { - name: 'ember-theme-changer' + name: 'ember-theme-changer', + isDevelopingAddon() { + return false; + } }; diff --git a/jsconfig.json b/jsconfig.json new file mode 100644 index 0000000..f408cac --- /dev/null +++ b/jsconfig.json @@ -0,0 +1 @@ +{"compilerOptions":{"target":"es6","experimentalDecorators":true},"exclude":["node_modules","bower_components","tmp","vendor",".git","dist"]} \ No newline at end of file diff --git a/package.json b/package.json index df4b7f8..6913318 100644 --- a/package.json +++ b/package.json @@ -1,17 +1,20 @@ { "name": "ember-theme-changer", - "version": "0.0.0", - "description": "The default blueprint for ember-cli addons.", + "version": "0.0.3", + "description": "Easy way to change themes by swapping CSS files.", "keywords": [ - "ember-addon" + "ember-addon", + "css", + "theme", + "style" ], "license": "MIT", - "author": "", + "author": "Leandro Diato", "directories": { "doc": "doc", "test": "tests" }, - "repository": "", + "repository": "https://github.com/leadiato/ember-theme-changer", "scripts": { "build": "ember build", "start": "ember server", @@ -22,7 +25,6 @@ }, "devDependencies": { "broccoli-asset-rev": "^2.4.5", - "ember-ajax": "^2.4.1", "ember-cli": "2.12.0", "ember-cli-dependency-checker": "^1.3.0", "ember-cli-eslint": "^3.0.0", @@ -38,13 +40,10 @@ "ember-load-initializers": "^0.6.0", "ember-resolver": "^2.0.3", "ember-source": "~2.12.0", - "ember-welcome-page": "^2.0.2", - "loader.js": "^4.2.3" + "loader.js": "^4.2.3", + "ember-cookies": "0.0.13" }, "engines": { "node": ">= 4" - }, - "ember-addon": { - "configPath": "tests/dummy/config" } }