Best JavaScript code snippet using storybook-root
lifecycle.js
Source:lifecycle.js
1/* @flow */2import config from '../config'3import Watcher from '../observer/watcher'4import { mark, measure } from '../util/perf'5import { createEmptyVNode } from '../vdom/vnode'6import { updateComponentListeners } from './events'7import { resolveSlots } from './render-helpers/resolve-slots'8import { toggleObserving } from '../observer/index'9import { pushTarget, popTarget } from '../observer/dep'10import {11 warn,12 noop,13 remove,14 emptyObject,15 validateProp,16 invokeWithErrorHandling17} from '../util/index'18export let activeInstance: any = null19export let isUpdatingChildComponent: boolean = false20export function setActiveInstance(vm: Component) {21 const prevActiveInstance = activeInstance22 activeInstance = vm23 return () => {24 activeInstance = prevActiveInstance25 }26}27export function initLifecycle (vm: Component) {28 const options = vm.$options29 // locate first non-abstract parent30 let parent = options.parent31 if (parent && !options.abstract) {32 while (parent.$options.abstract && parent.$parent) {33 parent = parent.$parent34 }35 parent.$children.push(vm)36 }37 vm.$parent = parent38 vm.$root = parent ? parent.$root : vm39 vm.$children = []40 vm.$refs = {}41 vm._watcher = null42 vm._inactive = null43 vm._directInactive = false44 vm._isMounted = false45 vm._isDestroyed = false46 vm._isBeingDestroyed = false47}48export function lifecycleMixin (Vue: Class<Component>) {49 Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {50 const vm: Component = this51 const prevEl = vm.$el52 const prevVnode = vm._vnode53 const restoreActiveInstance = setActiveInstance(vm)54 vm._vnode = vnode55 // Vue.prototype.__patch__ is injected in entry points56 // based on the rendering backend used.57 if (!prevVnode) {58 // initial render59 vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)60 } else {61 // updates62 vm.$el = vm.__patch__(prevVnode, vnode)63 }64 restoreActiveInstance()65 // update __vue__ reference66 if (prevEl) {67 prevEl.__vue__ = null68 }69 if (vm.$el) {70 vm.$el.__vue__ = vm71 }72 // if parent is an HOC, update its $el as well73 if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {74 vm.$parent.$el = vm.$el75 }76 // updated hook is called by the scheduler to ensure that children are77 // updated in a parent's updated hook.78 }79 Vue.prototype.$forceUpdate = function () {80 const vm: Component = this81 if (vm._watcher) {82 vm._watcher.update()83 }84 }85 Vue.prototype.$destroy = function () {86 const vm: Component = this87 if (vm._isBeingDestroyed) {88 return89 }90 callHook(vm, 'beforeDestroy')91 vm._isBeingDestroyed = true92 // remove self from parent93 const parent = vm.$parent94 if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {95 remove(parent.$children, vm)96 }97 // teardown watchers98 if (vm._watcher) {99 vm._watcher.teardown()100 }101 let i = vm._watchers.length102 while (i--) {103 vm._watchers[i].teardown()104 }105 // remove reference from data ob106 // frozen object may not have observer.107 if (vm._data.__ob__) {108 vm._data.__ob__.vmCount--109 }110 // call the last hook...111 vm._isDestroyed = true112 // invoke destroy hooks on current rendered tree113 vm.__patch__(vm._vnode, null)114 // fire destroyed hook115 callHook(vm, 'destroyed')116 // turn off all instance listeners.117 vm.$off()118 // remove __vue__ reference119 if (vm.$el) {120 vm.$el.__vue__ = null121 }122 // release circular reference (#6759)123 if (vm.$vnode) {124 vm.$vnode.parent = null125 }126 }127}128export function mountComponent (129 vm: Component,130 el: ?Element,131 hydrating?: boolean132): Component {133 vm.$el = el134 if (!vm.$options.render) {135 vm.$options.render = createEmptyVNode136 if (process.env.NODE_ENV !== 'production') {137 /* istanbul ignore if */138 if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||139 vm.$options.el || el) {140 warn(141 'You are using the runtime-only build of Vue where the template ' +142 'compiler is not available. Either pre-compile the templates into ' +143 'render functions, or use the compiler-included build.',144 vm145 )146 } else {147 warn(148 'Failed to mount component: template or render function not defined.',149 vm150 )151 }152 }153 }154 callHook(vm, 'beforeMount')155 let updateComponent156 /* istanbul ignore if */157 if (process.env.NODE_ENV !== 'production' && config.performance && mark) {158 updateComponent = () => {159 const name = vm._name160 const id = vm._uid161 const startTag = `vue-perf-start:${id}`162 const endTag = `vue-perf-end:${id}`163 mark(startTag)164 const vnode = vm._render()165 mark(endTag)166 measure(`vue ${name} render`, startTag, endTag)167 mark(startTag)168 vm._update(vnode, hydrating)169 mark(endTag)170 measure(`vue ${name} patch`, startTag, endTag)171 }172 } else {173 updateComponent = () => {174 vm._update(vm._render(), hydrating)175 }176 }177 // we set this to vm._watcher inside the watcher's constructor178 // since the watcher's initial patch may call $forceUpdate (e.g. inside child179 // component's mounted hook), which relies on vm._watcher being already defined180 new Watcher(vm, updateComponent, noop, {181 before () {182 if (vm._isMounted && !vm._isDestroyed) {183 callHook(vm, 'beforeUpdate')184 }185 }186 }, true /* isRenderWatcher */)187 hydrating = false188 // manually mounted instance, call mounted on self189 // mounted is called for render-created child components in its inserted hook190 if (vm.$vnode == null) {191 vm._isMounted = true192 callHook(vm, 'mounted')193 }194 return vm195}196export function updateChildComponent (197 vm: Component,198 propsData: ?Object,199 listeners: ?Object,200 parentVnode: MountedComponentVNode,201 renderChildren: ?Array<VNode>202) {203 if (process.env.NODE_ENV !== 'production') {204 isUpdatingChildComponent = true205 }206 // determine whether component has slot children207 // we need to do this before overwriting $options._renderChildren.208 // check if there are dynamic scopedSlots (hand-written or compiled but with209 // dynamic slot names). Static scoped slots compiled from template has the210 // "$stable" marker.211 const newScopedSlots = parentVnode.data.scopedSlots212 const oldScopedSlots = vm.$scopedSlots213 const hasDynamicScopedSlot = !!(214 (newScopedSlots && !newScopedSlots.$stable) ||215 (oldScopedSlots !== emptyObject && !oldScopedSlots.$stable) ||216 (newScopedSlots && vm.$scopedSlots.$key !== newScopedSlots.$key) ||217 (!newScopedSlots && vm.$scopedSlots.$key)218 )219 // Any static slot children from the parent may have changed during parent's220 // update. Dynamic scoped slots may also have changed. In such cases, a forced221 // update is necessary to ensure correctness.222 const needsForceUpdate = !!(223 renderChildren || // has new static slots224 vm.$options._renderChildren || // has old static slots225 hasDynamicScopedSlot226 )227 vm.$options._parentVnode = parentVnode228 vm.$vnode = parentVnode // update vm's placeholder node without re-render229 if (vm._vnode) { // update child tree's parent230 vm._vnode.parent = parentVnode231 }232 vm.$options._renderChildren = renderChildren233 // update $attrs and $listeners hash234 // these are also reactive so they may trigger child update if the child235 // used them during render236 vm.$attrs = parentVnode.data.attrs || emptyObject237 vm.$listeners = listeners || emptyObject238 // update props239 if (propsData && vm.$options.props) {240 toggleObserving(false)241 const props = vm._props242 const propKeys = vm.$options._propKeys || []243 for (let i = 0; i < propKeys.length; i++) {244 const key = propKeys[i]245 const propOptions: any = vm.$options.props // wtf flow?246 props[key] = validateProp(key, propOptions, propsData, vm)247 }248 toggleObserving(true)249 // keep a copy of raw propsData250 vm.$options.propsData = propsData251 }252 // update listeners253 listeners = listeners || emptyObject254 const oldListeners = vm.$options._parentListeners255 vm.$options._parentListeners = listeners256 updateComponentListeners(vm, listeners, oldListeners)257 // resolve slots + force update if has children258 if (needsForceUpdate) {259 vm.$slots = resolveSlots(renderChildren, parentVnode.context)260 vm.$forceUpdate()261 }262 if (process.env.NODE_ENV !== 'production') {263 isUpdatingChildComponent = false264 }265}266function isInInactiveTree (vm) {267 while (vm && (vm = vm.$parent)) {268 if (vm._inactive) return true269 }270 return false271}272export function activateChildComponent (vm: Component, direct?: boolean) {273 if (direct) {274 vm._directInactive = false275 if (isInInactiveTree(vm)) {276 return277 }278 } else if (vm._directInactive) {279 return280 }281 if (vm._inactive || vm._inactive === null) {282 vm._inactive = false283 for (let i = 0; i < vm.$children.length; i++) {284 activateChildComponent(vm.$children[i])285 }286 callHook(vm, 'activated')287 }288}289export function deactivateChildComponent (vm: Component, direct?: boolean) {290 if (direct) {291 vm._directInactive = true292 if (isInInactiveTree(vm)) {293 return294 }295 }296 if (!vm._inactive) {297 vm._inactive = true298 for (let i = 0; i < vm.$children.length; i++) {299 deactivateChildComponent(vm.$children[i])300 }301 callHook(vm, 'deactivated')302 }303}304export function callHook (vm: Component, hook: string) {305 // #7573 disable dep collection when invoking lifecycle hooks306 pushTarget()307 const handlers = vm.$options[hook]308 const info = `${hook} hook`309 if (handlers) {310 for (let i = 0, j = handlers.length; i < j; i++) {311 invokeWithErrorHandling(handlers[i], vm, null, vm, info)312 }313 }314 if (vm._hasHookEvent) {315 vm.$emit('hook:' + hook)316 }317 popTarget()...
form.js
Source:form.js
1'use strict';2/**3 * @ngdoc function4 * @name uixApp.controller:FormCtrl5 * @description6 * # FormCtrl7 * Controller of the uixApp8 */9angular.module('uixApp')10 .controller('FormCtrl', function ($scope, $rootScope, APP, resourceManager, exMsg, $state, $stateParams, $http, $translate, fieldService, lookupService, schemaService, authService, $uibModalStack) {11 var vm = this;12 $scope.vmRef = vm;13 vm.model = {};14 vm.modelName = null;15 vm.recordId = null;16 vm.record = {};17 vm.action = { editMode: false, loading: true, saving: false, creating: false, updating: false, deleting: false };18 vm.formly = { model: {}, fields: [], options: {formState: {readOnly: true}}, form: {} };19 vm.initRoute = initRoute;20 vm.loadRecord = loadRecord;21 vm.sanitizeRecord = sanitizeRecord;22 vm.setRecord = setRecord;23 vm.lookupData = lookupData;24 vm.close = close;25 vm.create = create;26 vm.edit = edit;27 vm.isViewMode = isViewMode;28 vm.isEditMode = isEditMode;29 vm.cancelEdit = cancelEdit;30 vm.uploads = uploads;31 vm.update = update;32 vm.save = save;33 vm.delete = deleteRecord;34 vm.error = error;35 vm.hasAccess = authService.hasAccess;36 vm.hasCreateAccess = function () {37 return authService.hasCreateAccess(vm.model.name);38 }39 vm.hasShowAccess = function () {40 return authService.hasShowAccess(vm.model.name);41 }42 vm.hasUpdateAccess = function () {43 return authService.hasUpdateAccess(vm.model.name);44 }45 vm.hasDeleteAccess = function () {46 return authService.hasDeleteAccess(vm.model.name);47 }48 $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {49 if (!$scope.state.isShow) return;50 51 var actionsConfig = [];52 var mainActionConfig = {};53 if (vm.hasCreateAccess()) {54 mainActionConfig = {55 icon: 'fa fa-plus',56 label: 'New ' + vm.model.name,57 handler: vm.new58 };59 }60 // Add back button61 actionsConfig.push({62 icon: 'fa fa-chevron-left',63 label: 'Back',64 handler: function () { $state.go('^'); }65 });66 $rootScope.$broadcast('fab:load-actions', vm.model.name, actionsConfig, mainActionConfig);67 });68 $scope.$on('uix:reload-record', function(evt, modelName, record) {69 if (modelName === vm.model.name && record.id === vm.record.id) {70 vm.loadRecord(vm.record.id);71 }72 });73 function initRoute (routeName, options) {74 options = options || {};75 options.loadRecord = (options.loadRecord === undefined)? true : options.loadRecord;76 vm.modelName = options.name || resourceManager.getName(routeName);77 window[vm.modelName + 'FormCtrl'] = vm;78 vm.model = resourceManager.register(vm.modelName, APP.apiPrefix + routeName + '/:id');79 vm.formly.fields = fieldService.get(vm.model.key);80 81 lookupService.load(vm.model.key, options.lookups, true).then(function () {82 vm.setRecord();83 $rootScope.$broadcast('uix:form-ready', vm.model.name, vm, $scope);84 });85 if (options.loadRecord && $stateParams.id) {86 vm.recordId = $stateParams.id;87 } else if(options.recordId) {88 vm.recordId = options.recordId;89 } else if ($rootScope[vm.model.key + '_id']) {90 vm.recordId = $rootScope[vm.model.key + '_id'];91 $rootScope[vm.model.key + '_id'] = null;92 }93 94 if (vm.recordId) {95 vm.loadRecord(vm.recordId);96 } else {97 vm.formly.options.formState.readOnly = false;98 }99 }100 function loadRecord (recordId) {101 if(!recordId) { return; }102 vm.action.loading = true;103 var data = { id: recordId };104 resourceManager.get(vm.model.name, data)105 .then(function (data) {106 vm.record = data;107 vm.formly.model = angular.copy(vm.record);108 vm.sanitizeRecord();109 $rootScope.$broadcast('uix:record-loaded', vm.model.name, vm.record, $scope);110 vm.action.loading = false;111 vm.formly.options.formState.readOnly = true;112 })113 .catch(function (error) {114 vm.error(error);115 vm.action.loading = false;116 });117 };118 function sanitizeRecord () {119 _.each(vm.record, function (value, key) {120 if (value === null) {121 vm.record[key] = '';122 }123 });124 }125 function setRecord () {126 if (!vm.record.id && $stateParams.q) {127 _.each(vm.splitQ($stateParams.q), function (v, k) {128 vm.record[k] = v;129 });130 $rootScope.$broadcast('uix:record-set', vm.model.name, vm.record, $scope);131 }132 };133 function lookupData(lookupName) {134 return lookupService.get(lookupName);135 }136 function close () {137 vm.record = {};138 if ($uibModalStack.getTop()) {139 $scope.$dismiss();140 }141 $state.go('^');142 };143 function create () {144 vm.action.saving = true;145 vm.action.creating = true;146 var data = {};147 data[vm.model.key] = vm.formly.model;148 149 resourceManager.create(vm.model.name, data)150 .then(function (data) {151 // vm.formly.model.id = data.id;152 vm.record = data;153 vm.formly.model = angular.copy(vm.record);154 $rootScope.$broadcast('uix:record-created', vm.model.name, data, $scope);155 exMsg.success(vm.model.title + ' created successfully');156 157 vm.close();158 })159 .catch(function (error) {160 vm.error(error);161 })162 .finally(function () {163 vm.action.saving = false;164 vm.action.creating = false;165 });166 };167 function edit () {168 vm.formly.options.formState.readOnly = false;169 vm.action.editMode = true;170 };171 function isViewMode () {172 return vm.formly.options.formState.readOnly;173 }174 function isEditMode () {175 return !vm.formly.options.formState.readOnly;176 }177 function cancelEdit () {178 vm.formly.model = angular.copy(vm.record);179 vm.formly.options.formState.readOnly = true;180 vm.action.editMode = false;181 };182 function uploads () {183 $state.go('^.uploads', $stateParams);184 };185 function update () {186 if(!vm.record.id) { return; }187 vm.action.saving = true;188 vm.action.updating = true;189 var data = { id: vm.record.id };190 data[vm.model.key] = vm.formly.model;191 192 resourceManager.update(vm.model.name, data)193 .then(function (data) {194 vm.record = data;195 vm.formly.model = angular.copy(vm.record);196 $rootScope.$broadcast('uix:record-updated', vm.model.name, data, $scope);197 exMsg.success(vm.model.title + ' updated successfully');198 vm.close();199 })200 .catch(function (error) {201 vm.error(error);202 })203 .finally(function () {204 vm.action.saving = false;205 vm.action.updating = false;206 });207 };208 function save () {209 PNotify.removeAll();210 vm.formly.form.$setSubmitted(true);211 if (!vm.formly.form.$valid) {212 return;213 }214 if(vm.record.id) {215 vm.update();216 } else {217 vm.create();218 }219 };220 function deleteRecord () {221 vm.action.deleting = true;222 var msg = "Are you sure you want to delete this " + vm.model.title + "?";223 exMsg.confirm(msg, "Confirm Delete").then(function () {224 var data = { id: vm.record.id };225 data[vm.model.key] = vm.record;226 resourceManager.delete(vm.model.name, data)227 .then(function (data) {228 $rootScope.$broadcast('uix:record-deleted', vm.model.name, vm.record, $scope);229 exMsg.success(vm.model.title + " deleted successfully");230 vm.close();231 })232 .catch(function (error) {233 vm.error(error);234 }).finally(function () {235 vm.action.deleting = false;236 });237 }).catch(function () {238 vm.action.deleting = false;239 });240 };241 function error (error) {242 error = error || {};243 error.message && exMsg.error(error.message, error.type || 'Error');244 error.messages && exMsg.errorSummary(error.messages);245 }...
demo.controller.js
Source:demo.controller.js
1(function() {2 'use strict';3 4 angular5 .module('demo')6 .controller('DemoController', DemoController);7 8 DemoController.$inject = ['$q', '$http', '$sce', '$timeout'];9 10 function DemoController($q, $http, $sce, $timeout) {11 var vm = this;12 vm.demos = [];13 vm.updateDelay = 800;14 vm.currentTimeout = null;15 vm.loading = false;16 vm.waiting = false;17 vm.diffName = '';18 vm.currentDemo = null;19 vm.debugOutput = {};20 vm.matchThreshold = 80;21 vm.overrides = [];22 vm.legislativeOverride = null;23 vm.tableDiffNumber = 1;24 vm.tableDiffing = true;25 vm.editorOptions = {};26 vm.ckEditorEnabled = true;27 vm.trustHtml = trustHtml;28 vm.reset = reset;29 vm.update = update;30 vm.swapText = swapText;31 vm.diffDemo = diffDemo;32 vm.diffOverride = diffOverride;33 vm.diffTableDemo = diffTableDemo;34 vm.updateDemo = updateDemo;35 vm.saveNewDemo = saveNewDemo;36 vm.toggleCkEditor = toggleCkEditor;37 activate();38 function activate() {39 var promises = [loadDemos(), loadOverrides()];40 return $q.all(promises).then(function() {41 });42 }43 function trustHtml(text) {44 return typeof text !== 'undefined' ? $sce.trustAsHtml(text) : '';45 }46 function toggleCkEditor() {47 vm.ckEditorEnabled = !vm.ckEditorEnabled;48 }49 function reset() {50 vm.oldText = '';51 vm.newText = '';52 vm.diff = '';53 vm.loading = false;54 vm.waiting = false;55 vm.currentDemo = null;56 vm.legislativeOverride = null;57 if (vm.currentTimeout) {58 $timeout.cancel(vm.currentTimeout);59 }60 }61 function update() {62 if (vm.currentTimeout) {63 $timeout.cancel(vm.currentTimeout);64 }65 vm.currentTimeout = $timeout(function () {66 getDiff();67 }, vm.updateDelay);68 vm.diff = null;69 vm.waiting = true;70 }71 function swapText() {72 var oldText = vm.oldText;73 vm.oldText = vm.newText;74 vm.newText = oldText;75 getDiff();76 }77 function diffDemo(index) {78 if (typeof index === 'undefined') {79 index = 0;80 }81 vm.oldText = vm.demos[index]['old'];82 vm.newText = vm.demos[index]['new'];83 getDiff();84 vm.currentDemo = vm.demos[index];85 vm.legislativeOverride = vm.demos[index].hasOwnProperty('legislativeOverride') ? vm.demos[index]['legislativeOverride'] : null;86 }87 function diffOverride(override, index) {88 vm.oldText = override.old;89 vm.newText = override.new;90 vm.legislativeOverride = override.override;91 getDiff();92 vm.currentDemo = override;93 if (!vm.currentDemo.name) {94 vm.currentDemo.name = 'Override Demo ' + (index + 1);95 }96 vm.currentDemo.isOverride = true;97 }98 function diffTableDemo(index) {99 loadTableDiff(index)100 .then(function(response) {101 vm.oldText = response.data.old;102 vm.newText = response.data.new;103 vm.legislativeOverride = null;104 getDiff();105 vm.currentDemo = null;106 })107 .catch(function(e) {108 console.log(e);109 });110 }111 function updateDemo() {112 vm.currentDemo.old = vm.oldText;113 vm.currentDemo.new = vm.newText;114 return $http.post('save_demo.php', vm.currentDemo)115 .then(function (response) {116 return response;117 });118 }119 function saveNewDemo() {120 var newIndex = vm.demos.length + 1;121 if (vm.diffName.length === 0) {122 vm.diffName = 'DEMO ' + newIndex;123 }124 var newDemo = {'old': vm.oldText, 'new': vm.newText, 'name': vm.diffName, 'legislativeOverride': vm.legislativeOverride};125 vm.demos.push(newDemo);126 return $http.post('save_demo.php', newDemo)127 .then(function (response) {128 vm.currentDemo = newDemo;129 return vm.currentDemo;130 });131 }132 function loadTableDiff(index) {133 return $http({134 url: 'load_table_diff.php',135 method: 'POST',136 data: {index: index},137 header: {'Content-Type': 'application/json; charset=UTF-8'}138 });139 }140 function getDiff() {141 vm.waiting = false;142 vm.loading = true;143 vm.diff = null;144 $http.post('index.php', {145 oldText: vm.oldText,146 newText: vm.newText,147 matchThreshold: vm.matchThreshold,148 tableDiffing: vm.tableDiffing149 })150 .then(function (response) {151 vm.diff = response.data.hasOwnProperty('diff') ? response.data.diff : response.data;152 vm.loading = false;153 addDebugOutput(response.data.debug);154 })155 .catch(function (response) {156 console.error('Gists error', response.status, response.data);157 });158 }159 function loadDemos() {160 $http.get('demos.json')161 .success(function (data) {162 vm.demos = data;163 });164 }165 function loadOverrides() {166 return $http.get('diff.json')167 .then(function (response) {168 vm.overrides = response.data;169 return vm.overrides;170 });171 }172 function addDebugOutput(data) {173 angular.forEach(data, function(value, key) {174 data[key] = {175 messages: value,176 isCollapsed: true177 };178 });179 vm.debugOutput = data;180 }181 }...
plans.client.controller.js
Source:plans.client.controller.js
1(function () {2 'use strict';3 // Plans controller4 angular5 .module('plans')6 .controller('PlansController', PlansController);7 PlansController.$inject = ['$scope', '$state', '$stateParams', '$http', 'Authentication', 'toasty', 'planResolve', 'Userslist', 'DomainsService', 'AppsService', 'ReleasesService', 'TasksService'];8 function PlansController ($scope, $state, $stateParams, $http, Authentication, toasty, plan, Userslist, DomainsService, AppsService, ReleasesService, TasksService) {9 var vm = this;10 vm.authentication = Authentication;11 vm.plan = plan;12 vm.tasks = (vm.plan._id ? TasksService.query({ planId: vm.plan._id }) : []);13 vm.dateformat = 'MMM dd, yyyy';14 vm.startExecution = startExecution;15 vm.taskCompleted = taskCompleted;16 if($state.current.name === 'plans.edit' || 'plans.create'){17 vm.plan.status = (vm.plan.status ? vm.plan.status : 'Draft');18 vm.plan.autolock = new Date(vm.plan.autolock || Date.now());19 vm.plan.initStart = (vm.plan.initStart ? new Date(vm.plan.initStart) : '');20 vm.plan.initEnd = (vm.plan.initEnd ? new Date(vm.plan.initEnd) : '');21 vm.plan.updatedStart = (vm.plan.updatedStart ? new Date(vm.plan.updatedStart) : '');22 vm.plan.updatedEnd = (vm.plan.updatedEnd ? new Date(vm.plan.updatedEnd) : '');23 vm.error = null;24 vm.form = {};25 vm.remove = remove;26 vm.save = save;27 vm.options = {};28 vm.options.task = {};29 vm.options.task.category = ['Deploy', 'Routing', 'Certification', 'Infrastructure'];30 vm.dnd = {};31 vm.cancelform = cancelform;32 vm.options.category = ['Routing', 'Release', 'Adhoc', 'Template'];33 vm.options.dcs = ['QTS', 'COIT', 'FRYE', 'VA', 'TX'];34 vm.options.status = ['Draft', 'Final', 'Started', 'Completed', 'Canceled'];35 vm.userslist = Userslist.query();36 vm.domainslist = DomainsService.query();37 vm.appslist = AppsService.query();38 vm.releaseslist = ReleasesService.query();39 }40 //Calculate start and end times for tasks41 if(vm.plan._id){42 vm.addnewtask = addnewtask;43 vm.tasks.$promise.then(function(){44 for(var i = 0; i < vm.tasks.length; i++){45 if(vm.tasks[i].status === 'Draft' || 'Approved' || 'Canceled'){46 if(i===0){47 vm.tasks[i].updatedStart = new Date(vm.plan.actualStart || vm.plan.updatedStart || vm.plan.initStart);48 vm.tasks[i].updatedEnd = new Date(vm.tasks[i].updatedStart.getTime() + (vm.tasks[i].duration*60000));49 } else {50 vm.tasks[i].updatedStart = vm.tasks[i-1].updatedEnd;51 vm.tasks[i].updatedEnd = new Date(vm.tasks[i].updatedStart.getTime() + (vm.tasks[i].duration*60000));52 }53 } else if(vm.tasks[i].status === 'Started'){54 vm.tasks[i].updatedEnd = new Date(vm.tasks[i].actualStart.getTime() + (vm.tasks[i].duration*60000));55 }56 }57 });58 }59 // Remove existing Plan60 function remove() {61 if (confirm('Are you sure you want to delete?')) {62 vm.plan.$remove(function (){63 $state.go('plans.list');64 toasty.success({65 title: 'Deleted!',66 msg: vm.plan.name + ' has been deleted!',67 theme: 'bootstrap'68 });69 });70 }71 }72 function cancelform() {73 if($state.current.name === 'plans.edit'){74 $state.go('plans.view', { planId: vm.plan._id });75 } else {76 $state.go('plans.list');77 }78 }79 function addnewtask() {80 vm.tasks.push({ name:'', duration: 0, category: '', parent: vm.plan._id });81 }82 //Start execution function83 function startExecution() {84 vm.plan.status = vm.options.status[2];85 vm.tasks[0].status = 'Started';86 vm.plan.actualStart = Date.now();87 vm.tasks[0].actualStart = vm.plan.actualStart;88 var req = {89 method: 'PUT',90 url: 'api/plans/'+vm.plan._id+'/tasks/'+vm.tasks[0]._id,91 data: vm.tasks[0]92 };93 $http(req).then(function(){94 vm.plan.$update(function(){95 toasty.success({96 title: 'Startup completed!',97 theme: 'bootstrap'98 });99 }, function(res){100 toasty.error({101 title: 'Error on Startup!',102 msg: res.data.message,103 theme: 'bootstrap'104 });105 });106 }, function(){});107 }108 //Task completed function109 function taskCompleted(taskId){110 }111 // Save Plan112 function save(isValid) {113 if (!isValid) {114 $scope.$broadcast('show-errors-check-validity', 'vm.form.planForm');115 return false;116 }117 // TODO: move create/update logic to service118 if (vm.plan._id) {119 //Call bulk update api to update sortorder and any other changes from the form on update120 for(var i = 0; i < vm.tasks.length; i++){121 vm.tasks[i].sortOrder = i;122 }123 var req = {124 method: 'PUT',125 url: 'api/plans/'+vm.plan._id+'/tasks',126 data: vm.tasks127 };128 $http(req).then(function(){129 vm.plan.$update(successCallback, errorCallback);130 }, errorCallback);131 } else {132 vm.plan.$save(successCallback, errorCallback);133 }134 function successCallback(res) {135 $state.go('plans.view', {136 planId: res._id137 });138 toasty.success({139 title: 'Save successful!',140 msg: vm.plan.name + ' has been saved!',141 theme: 'bootstrap'142 });143 }144 function errorCallback(res) {145 vm.error = res.data.message;146 toasty.error({147 title: 'Save error!',148 msg: vm.eror,149 theme: 'bootstrap'150 });151 }152 }153 }...
manual-inserir.controller.js
Source:manual-inserir.controller.js
1(function () {2 'use strict';3 angular4 .module('app.manual')5 .controller('ManualCadastrarController', ManualCadastrarController);6 7 ManualCadastrarController.$inject = ['$state', 'manualServices', 'empresaService'];8 function ManualCadastrarController($state, manualServices, empresaService){9 var vm = this;10 11 vm.empresa = {};12 vm.empresaId = '';13 vm.item = {}; 14 vm.item.respostaList = [];15 vm.listaEmpresas = [];16 vm.operacao = 'Cadastrar';17 vm.busy = false;18 19 //collapsed20 vm.isCollapsed1 = true;21 vm.isCollapsed2 = true;22 vm.isCollapsed3 = true;23 vm.isCollapsed4 = true;24 vm.isCollapsed41 = true;25 vm.isCollapsed42 = true;26 vm.isCollapsed421 = true;27 vm.isCollapsed422 = true;28 vm.isCollapsed423 = true;29 vm.isCollapsed424 = true;30 vm.isCollapsed425 = true; 31 vm.isCollapsed426 = true;32 vm.isCollapsed427 = true;33 vm.isCollapsed428 = true;34 vm.isCollapsed429 = true;35 vm.isCollapsed4210 = true;36 vm.isCollapsed4211 = true;37 vm.isCollapsed4212 = true;38 vm.isCollapsed4213 = true;39 vm.isCollapsed45 = true;40 vm.isCollapsed46 = true;41 vm.isCollapsed47 = true;42 vm.isCollapsed471 = true43 vm.isCollapsed472 = true44 vm.isCollapsed473 = true45 vm.isCollapsed48 = true;46 vm.isCollapsed481 = true47 vm.isCollapsed482 = true48 vm.isCollapsed49 = true;49 vm.isCollapsed410 = true;50 vm.isCollapsed411 = true;51 vm.isCollapsed412 = true;52 vm.isCollapsed413 = true;53 vm.isCollapsed414 = true;54 vm.isCollapsed415 = true;55 vm.isCollapsed416 = true;56 vm.isCollapsed417 = true;57 vm.isCollapsed418 = true;58 59 vm.inicieManual = inicieManual;60 vm.salvar = salvar;61 vm.cancelar = cancelar;62 vm.podeVisualizar = podeVisualizar;63 vm.setTooltip = setTooltip;64 65 function inicieManual(){ 66 for(var i = 0; i <= 88; i++){67 var resposta = {};68 resposta.texto = '';69 resposta.numeroResposta = i + 1;70 vm.item.respostaList.push(resposta);71 }72 vm.item.revisao = 1;73 vm.item.empresaID = vm.empresa.id; 74 setEmpresa();75 }76 77 function podeVisualizar(){78 return (vm.empresaId && vm.operacao === 'Cadastrar') || vm.operacao === 'Editar';79 }80 81 function salvar(form){82 if(!vm.empresa){83 toastr.warning('Para salvar o manual selecione uma empresa.');84 return;85 }86 87 if(form.$valid && vm.empresa ) { 88 if (vm.busy)89 return;90 vm.busy = true;91 manualServices.cadastrar(vm.item).then(function(response){92 toastr.success('Manual salvo com sucesso!');93 $state.go('^.listar'); 94 }).finally(function () {95 vm.busy = false;96 });97 }98 }99 100 function setEmpresa(){101 if(vm.empresa){102 vm.item.respostaList[4].texto = vm.empresa.razaoSocial;103 vm.item.respostaList[5].texto = vm.empresa.nomeFantasia;104 vm.item.respostaList[8].texto = vm.empresa.cnpj;105 }106 } 107 108 function setTooltip(expande){109 if(expande)110 return 'Expandir';111 return 'Esconder';112 }113 114 function cancelar (){115 $state.go('^.listar');116 }117 }...
Using AI Code Generation
1import { vm } from 'storybook-root';2import { vm } from 'storybook-root';3import { vm } from 'storybook-root';4import { vm } from 'storybook-root';5import { vm } from 'storybook-root';6import { vm } from 'storybook-root';7import { vm } from 'storybook-root';8import { vm } from 'storybook-root';9import { vm } from 'storybook-root';10import { vm } from 'storybook-root';11import { vm } from 'storybook-root';12import { vm } from 'storybook-root';13import { vm } from 'storybook-root';14import { vm } from 'storybook-root';15import { vm } from 'storybook-root';16import { vm } from 'storybook-root';17vm(path);
Using AI Code Generation
1import { vm } from 'storybook-addon-vue-info/lib'2import { mount } from '@vue/test-utils'3import MyComponent from './MyComponent.vue'4describe('MyComponent.vue', () => {5 it('renders props.msg when passed', () => {6 const wrapper = mount(MyComponent, {7 propsData: { msg }8 })9 expect(wrapper.text()).toMatch(msg)10 })11})12import 'storybook-addon-vue-info/register'13import { addDecorator } from '@storybook/vue'14import { withInfo } from 'storybook-addon-vue-info'15addDecorator(withInfo)16import { addDecorator } from '@storybook/vue'17import { withInfo } from 'storybook-addon-vue-info'18addDecorator(19 withInfo({20 })21import { storiesOf } from '@storybook/vue'22import { withInfo } from 'storybook-addon-vue-info'23import MyComponent from './MyComponent.vue'24storiesOf('MyComponent', module)25 .add(26 withInfo({27 })(() => ({28 components: { MyComponent },29 data() {30 return {31 }32 },33 }))34import { storiesOf } from '@storybook/vue'35import {
Using AI Code Generation
1import { storiesOf } from '@storybook/react';2import { withKnobs, text, select } from '@storybook/addon-knobs';3import React from 'react';4import { Button } from '../components/Button';5const stories = storiesOf('Button', module);6stories.addDecorator(withKnobs);7stories.add('with text', () => (8 onClick={action('clicked')}9 primary={select('primary', ['primary', 'secondary'], 'primary')}10 {text('text', 'Hello Button')}11));
Using AI Code Generation
1const vm = require('vm');2const path = require('path');3const fs = require('fs');4const pathToWebpackConfig = path.resolve(5);6const pathToConfig = path.resolve(__dirname, '../.storybook/preview.js');7const webpackConfig = require(pathToWebpackConfig);8const config = require(pathToConfig);9const webpackConfigEnv = { mode: 'development' };10const webpackConfigResult = webpackConfig(webpackConfigEnv);11const moduleExports = webpackConfigResult.module.exports;12const moduleExportsString = moduleExports.toString();13const moduleExportsFn = vm.runInThisContext(14 `(function (module, exports, require, __dirname, __filename, global, process) { ${moduleExportsString} })`15);16const moduleExportsResult = moduleExportsFn(17 {},18 {},19);20const configExports = config.module.exports;21const configExportsString = configExports.toString();22const configExportsFn = vm.runInThisContext(23 `(function (module, exports, require, __dirname, __filename, global, process) { ${configExportsString} })`24);25const configExportsResult = configExportsFn(26 {},27 {},28);29const vm = require('vm');30const path = require('path');31const fs = require('fs');32const pathToWebpackConfig = path.resolve(33);34const pathToConfig = path.resolve(__dirname, '../.storybook/preview.js');35const webpackConfig = require(pathToWebpackConfig);36const config = require(pathToConfig);37const webpackConfigEnv = { mode: 'development' };38const webpackConfigResult = webpackConfig(webpackConfigEnv);39const moduleExports = webpackConfigResult.module.exports;40const moduleExportsString = moduleExports.toString();41const moduleExportsFn = vm.runInThisContext(42 `(function (module, exports, require, __dirname, __filename, global, process) { ${moduleExportsString} })`43);44const moduleExportsResult = moduleExportsFn(45 {},46 {},47);
Using AI Code Generation
1const vm = require("vm");2const fs = require("fs");3const path = require("path");4const { getStorybook } = require("@storybook/react");5const storySource = fs.readFileSync(6 path.join(__dirname, story.fileName),7);8const context = vm.createContext({ module: {}, exports: {} });9vm.runInContext(storySource, context);10const storyFn = context.module.exports.default;11const storyElement = storyFn(context);12console.log(storyElement);13const vm = require("vm");14const fs = require("fs");15const path = require("path");16const { getStorybook } = require("@storybook/react");17const storySource = fs.readFileSync(18 path.join(__dirname, story.fileName),19);20const context = vm.createContext({ module: {}, exports: {} });21vm.runInContext(storySource, context);22const storyFn = context.module.exports.default;23const storyElement = storyFn(context);24console.log(storyElement);25const vm = require("vm");26const fs = require("fs");27const path = require("path");28const { getStorybook } = require("@storybook/react");29const storySource = fs.readFileSync(30 path.join(__dirname, story.fileName),31);
Using AI Code Generation
1var vm = require('vm');2var sandbox = { storybookRoot: '' };3vm.createContext(sandbox);4vm.runInContext('storybookRoot = __dirname', sandbox);5var storybookRoot = sandbox.storybookRoot;6var storybookRoot = process.cwd();7var storybookRoot = global.__dirname;8var storybookRoot = require.main.paths[0].split('node_modules')[0];9var path = require('path');10var storybookRoot = path.resolve(__dirname, '../..');11var fs = require('fs');12var storybookRoot = fs.realpathSync('.');13var path = require('path');14var storybookRoot = path.resolve(__dirname, '..');15var fs = require('fs');16var storybookRoot = fs.realpathSync('.');17var path = require('path');18var storybookRoot = path.resolve(__dirname, '..');19var fs = require('fs');20var storybookRoot = fs.realpathSync('.');21var path = require('path');22var storybookRoot = path.resolve(__dirname, '..');23var fs = require('fs');24var storybookRoot = fs.realpathSync('.');25var path = require('path');26var storybookRoot = path.resolve(__dirname, '..');27var fs = require('fs');28var storybookRoot = fs.realpathSync('.');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!