issue
dict | pr
dict | pr_details
dict |
---|---|---|
{
"body": "### Version\r\n2.5.16\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/lykahb/9grbbt4b/](https://jsfiddle.net/lykahb/9grbbt4b/)\r\n\r\n### Steps to reproduce\r\n1. Create a functional component that returns several root nodes\r\n2. Use it with is binding, like `<div is='my-component'>` with no siblings around it\r\n3. Render the template\r\n\r\n### What is expected?\r\nRenders correctly\r\n\r\n### What is actually happening?\r\nRenders a string \"undefined\" with no console errors\r\n\r\n---\r\nIt is interesting that it may render successfully depending on the siblings around it. There are several examples in the link.\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Works using `component` instead of `div` though 🤔 ",
"created_at": "2018-04-28T19:38:01Z"
}
],
"number": 8101,
"title": "Functional component fails depending on the siblings around it"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\n**Other information:**\r\nfix #8101 .",
"number": 8114,
"review_comments": [],
"title": "fix(compiler): maybeComponent should return true when \"is\" attribute exists"
} | {
"commits": [
{
"message": "fix: beforeUpdate should be called before render and allow state mutation\n\nfix #7481"
},
{
"message": "perf: avoid unnecessary re-renders when computed property value did not change\n\nclose #7767"
},
{
"message": "fix(ssr): fix SSR for async functional components\n\nfix #7784"
},
{
"message": "fix conflicts"
},
{
"message": "Merge remote-tracking branch 'upstream/dev' into dev"
},
{
"message": "Merge remote-tracking branch 'upstream/dev' into dev"
},
{
"message": "Merge remote-tracking branch 'upstream/dev' into dev"
},
{
"message": "Merge remote-tracking branch 'upstream/dev' into dev"
},
{
"message": "fix(compiler): maybeComponent should aware of \"is\" attribute"
},
{
"message": "add test case"
}
],
"files": [
{
"diff": "@@ -26,7 +26,7 @@ export class CodegenState {\n this.dataGenFns = pluckModuleFunction(options.modules, 'genData')\n this.directives = extend(extend({}, baseDirectives), options.directives)\n const isReservedTag = options.isReservedTag || no\n- this.maybeComponent = (el: ASTElement) => !isReservedTag(el.tag)\n+ this.maybeComponent = (el: ASTElement) => !(isReservedTag(el.tag) && !el.component)\n this.onceId = 0\n this.staticRenderFns = []\n }",
"filename": "src/compiler/codegen/index.js",
"status": "modified"
},
{
"diff": "@@ -524,6 +524,11 @@ describe('codegen', () => {\n '<div :is=\"component1\"></div>',\n `with(this){return _c(component1,{tag:\"div\"})}`\n )\n+ // maybe a component and normalize type should be 1\n+ assertCodegen(\n+ '<div><div is=\"component1\"></div></div>',\n+ `with(this){return _c('div',[_c(\"component1\",{tag:\"div\"})],1)}`\n+ )\n })\n \n it('generate component with inline-template', () => {",
"filename": "test/unit/modules/compiler/codegen.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.16\r\n\r\n### Reproduction link\r\n[https://codepen.io/katedo17/pen/rdXMbp](https://codepen.io/katedo17/pen/rdXMbp)\r\n\r\n### Steps to reproduce\r\nEnter \"3\" in the input field, and click the link \"Test Btn 2\". \r\n\r\n### What is expected?\r\nIt should only trigger the on click event that was configured for the \"Test Btn 2\".\r\n\r\n### What is actually happening?\r\nIt triggers the function binded to \"Test Btn 1\" and then trigger the \"Test Btn 2\". \r\n\r\n---\r\nThis only happens when I use v-if in the parent element of the link. But if I use v-show, it doesn't have the issue.\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "As a note, you should not use both, v-on and onclick (Vue cannot detect the later)\r\nYou can workaround this by adding a `key` to one or both of the `a` elements",
"created_at": "2018-04-16T11:13:56Z"
},
{
"body": "Noted. The onclick attribute is just to test the issue. My use case is, the link with v-on:click.once is supposed to call to the server, while the other one supposed to redirect to another page with no JS involved. But I was having an issue because when I click the link to redirect, it is actually doing a call to the server. \r\n\r\nThanks for the help. It works by adding \"key\" attribute. ",
"created_at": "2018-04-16T11:41:33Z"
},
{
"body": "If you want to prevent the default action of an event, please use `.prevent` modifier.",
"created_at": "2018-04-16T13:58:08Z"
},
{
"body": "It seems that `once listener` was not properly destroyed",
"created_at": "2018-04-16T17:04:20Z"
},
{
"body": "I'm not a English native speaker, I'll do my best to describe it. The reason for this problem is element reuse,\r\nThe existing elements are usually reused for the efficiency of rendering. So if you want make the function like you want , you need to add a key to the 'input'. key must be unique value. ",
"created_at": "2018-05-25T07:45:30Z"
}
],
"number": 8032,
"title": "bound event with once gets reused in v-if/else condition"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n#8032\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n",
"number": 8036,
"review_comments": [],
"title": "fix: correctly remove once listener with v-if"
} | {
"commits": [
{
"message": "fix: correctly remove once listener with v-if"
}
],
"files": [
{
"diff": "@@ -21,25 +21,31 @@ export function initEvents (vm: Component) {\n \n let target: any\n \n-function add (event, fn, once) {\n- if (once) {\n- target.$once(event, fn)\n- } else {\n- target.$on(event, fn)\n- }\n+function add (event, fn) {\n+ target.$on(event, fn)\n }\n \n function remove (event, fn) {\n target.$off(event, fn)\n }\n \n+function createOnceHandler (event, fn) {\n+ const _target = target\n+ return function onceHandler () {\n+ const res = fn.apply(null, arguments)\n+ if (res !== null) {\n+ _target.$off(event, onceHandler)\n+ }\n+ }\n+}\n+\n export function updateComponentListeners (\n vm: Component,\n listeners: Object,\n oldListeners: ?Object\n ) {\n target = vm\n- updateListeners(listeners, oldListeners || {}, add, remove, vm)\n+ updateListeners(listeners, oldListeners || {}, add, remove, createOnceHandler, vm)\n target = undefined\n }\n ",
"filename": "src/core/instance/events.js",
"status": "modified"
},
{
"diff": "@@ -1,7 +1,13 @@\n /* @flow */\n \n import { warn } from 'core/util/index'\n-import { cached, isUndef, isPlainObject } from 'shared/util'\n+\n+import {\n+ cached,\n+ isUndef,\n+ isTrue,\n+ isPlainObject\n+} from 'shared/util'\n \n const normalizeEvent = cached((name: string): {\n name: string,\n@@ -47,6 +53,7 @@ export function updateListeners (\n oldOn: Object,\n add: Function,\n remove: Function,\n+ createOnceHandler: Function,\n vm: Component\n ) {\n let name, def, cur, old, event\n@@ -68,7 +75,10 @@ export function updateListeners (\n if (isUndef(cur.fns)) {\n cur = on[name] = createFnInvoker(cur)\n }\n- add(event.name, cur, event.once, event.capture, event.passive, event.params)\n+ if (isTrue(event.once)) {\n+ cur = on[name] = createOnceHandler(event.name, cur, event.capture)\n+ }\n+ add(event.name, cur, event.capture, event.passive, event.params)\n } else if (cur !== old) {\n old.fns = cur\n on[name] = old",
"filename": "src/core/vdom/helpers/update-listeners.js",
"status": "modified"
},
{
"diff": "@@ -28,7 +28,7 @@ function normalizeEvents (on) {\n \n let target: any\n \n-function createOnceHandler (handler, event, capture) {\n+function createOnceHandler (event, handler, capture) {\n const _target = target // save current target element in closure\n return function onceHandler () {\n const res = handler.apply(null, arguments)\n@@ -41,12 +41,10 @@ function createOnceHandler (handler, event, capture) {\n function add (\n event: string,\n handler: Function,\n- once: boolean,\n capture: boolean,\n passive: boolean\n ) {\n handler = withMacroTask(handler)\n- if (once) handler = createOnceHandler(handler, event, capture)\n target.addEventListener(\n event,\n handler,\n@@ -77,7 +75,7 @@ function updateDOMListeners (oldVnode: VNodeWithData, vnode: VNodeWithData) {\n const oldOn = oldVnode.data.on || {}\n target = vnode.elm\n normalizeEvents(on)\n- updateListeners(on, oldOn, add, remove, vnode.context)\n+ updateListeners(on, oldOn, add, remove, createOnceHandler, vnode.context)\n target = undefined\n }\n ",
"filename": "src/platforms/web/runtime/modules/events.js",
"status": "modified"
},
{
"diff": "@@ -4,10 +4,19 @@ import { updateListeners } from 'core/vdom/helpers/update-listeners'\n \n let target: any\n \n+function createOnceHandler (event, handler, capture) {\n+ const _target = target // save current target element in closure\n+ return function onceHandler () {\n+ const res = handler.apply(null, arguments)\n+ if (res !== null) {\n+ remove(event, onceHandler, capture, _target)\n+ }\n+ }\n+}\n+\n function add (\n event: string,\n handler: Function,\n- once: boolean,\n capture: boolean,\n passive?: boolean,\n params?: Array<any>\n@@ -16,18 +25,6 @@ function add (\n console.log('Weex do not support event in bubble phase.')\n return\n }\n- if (once) {\n- const oldHandler = handler\n- const _target = target // save current target element in closure\n- handler = function (ev) {\n- const res = arguments.length === 1\n- ? oldHandler(ev)\n- : oldHandler.apply(null, arguments)\n- if (res !== null) {\n- remove(event, null, null, _target)\n- }\n- }\n- }\n target.addEvent(event, handler, params)\n }\n \n@@ -47,7 +44,7 @@ function updateDOMListeners (oldVnode: VNodeWithData, vnode: VNodeWithData) {\n const on = vnode.data.on || {}\n const oldOn = oldVnode.data.on || {}\n target = vnode.elm\n- updateListeners(on, oldOn, add, remove, vnode.context)\n+ updateListeners(on, oldOn, add, remove, createOnceHandler, vnode.context)\n target = undefined\n }\n ",
"filename": "src/platforms/weex/runtime/modules/events.js",
"status": "modified"
},
{
"diff": "@@ -895,4 +895,31 @@ describe('Directive v-on', () => {\n }).$mount()\n expect(`v-on without argument expects an Object value`).toHaveBeenWarned()\n })\n+\n+ it('should correctly remove once listener', done => {\n+ const vm = new Vue({\n+ template: `\n+ <div>\n+ <span v-if=\"ok\" @click.once=\"foo\">\n+ a\n+ </span>\n+ <span v-else a=\"a\">\n+ b\n+ </span>\n+ </div>\n+ `,\n+ data: {\n+ ok: true\n+ },\n+ methods: {\n+ foo: spy\n+ }\n+ }).$mount()\n+\n+ vm.ok = false\n+ waitForUpdate(() => {\n+ triggerEvent(vm.$el.childNodes[0], 'click')\n+ expect(spy.calls.count()).toBe(0)\n+ }).then(done)\n+ })\n })",
"filename": "test/unit/features/directives/on.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.16\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/chrisvfritz/845Lee66/](https://jsfiddle.net/chrisvfritz/845Lee66/)\r\n\r\n### Steps to reproduce\r\n1. Open the fiddle\r\n2. Click the \"Toggle\" button\r\n3. Watch the `move` transition trigger on enter\r\n\r\n### What is expected?\r\nJust like with `v-if`, move transitions should not be triggered on enter (note that it is already _not_ triggered on leave). \r\n\r\n### What is actually happening?\r\nI haven't checked in the source yet, but I'm guessing that since elements with `display: none` still technically have coordinates:\r\n\r\n```\r\nDOMRect { x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 }\r\n```\r\n\r\nThe `move` transition is triggered on enter. I'm not sure why it wouldn't also occur on leave though. \r\n\r\n---\r\nThis may be connected to [#5800](https://github.com/vuejs/vue/issues/5800). Also, special thanks to @rachelnabors for finding this bug!\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Woohoo! I managed to break something!",
"created_at": "2018-03-22T18:39:57Z"
},
{
"body": "Can I give this issue a try?",
"created_at": "2018-03-23T23:16:52Z"
},
{
"body": "@vctt94 Of cause, welcome 😃",
"created_at": "2018-03-26T03:50:55Z"
},
{
"body": " this coordinate is using getBoundingClientRect method to get value.\r\ngetBoundingClientRect method is value 0 when display: none \r\n\r\nHow about change of line 8424 of vue.js\r\nc$1.elm.style.display = 'block';\r\nc$1.data.pos = c$1.elm.getBoundingClientRect();\r\n\r\nThe value can be taken\r\n\r\n",
"created_at": "2018-03-27T10:52:20Z"
},
{
"body": "hey @wlkuro, I believe you are right, and that is the cause. But we are not supposed to make changes on dist files. It is a self generated file, but the change you suggested does work. ",
"created_at": "2018-03-27T13:25:50Z"
},
{
"body": "@wlkuro @vctt94 I think a better solution is not to add `v-move` on element and and not to execute `_enterCb` just like `v-if`.",
"created_at": "2018-03-27T14:37:13Z"
},
{
"body": "I see, what exactly this _enterCb does? ",
"created_at": "2018-03-27T14:59:13Z"
},
{
"body": "@vctt94 sorry for not seeing your pr 😭\r\n[`_enterCb`](https://github.com/vuejs/vue/blob/dev/src/platforms/web/runtime/modules/transition.js#L115) should be executed when enter transition was finished or move transition was triggered. \r\nbut I think it is better that `v-show` has similar behavior as `v-if`.\r\nif `_enterCb` was executed, `v-show` would lose enter transition.",
"created_at": "2018-03-28T03:30:45Z"
},
{
"body": "I was playing around with an example from the docs and hit the same issue as described (e.g. toggle button: https://codepen.io/pen/BGjJGL).\r\n\r\nSince the PR is still open - are there currently any workarounds for this? Using `v-if` works perfectly but is not an option due to performance reasons.",
"created_at": "2018-11-08T00:01:45Z"
}
],
"number": 7879,
"title": "<transition-group> and v-show triggers move transition on enter"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\nfix #7879",
"number": 7906,
"review_comments": [
{
"body": "Accessing element.style here in a loop will probably cause serious perf issues due to forced layouts. More info: https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing\r\nIt's probably better to just check for empty rects (` { x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 }`) below\r\n",
"created_at": "2018-04-07T13:23:23Z"
},
{
"body": "Here you can check if `oldPos` is empty rect by comparing every field to `{ x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 }`.",
"created_at": "2018-04-07T13:24:39Z"
}
],
"title": "fix(transition-group): not add class v-move to v-show element"
} | {
"commits": [
{
"message": "fix(transition-group): not add class v-move to v-show element, fix #7879"
}
],
"files": [
{
"diff": "@@ -161,7 +161,7 @@ function callPendingCbs (c: VNode) {\n c.elm._moveCb()\n }\n /* istanbul ignore if */\n- if (c.elm._enterCb) {\n+ if (c.elm._enterCb && !Object.keys(c.data.pos).every(key => c.data.pos[key] === 0)) {\n c.elm._enterCb()\n }\n }\n@@ -175,7 +175,7 @@ function applyTranslation (c: VNode) {\n const newPos = c.data.newPos\n const dx = oldPos.left - newPos.left\n const dy = oldPos.top - newPos.top\n- if (dx || dy) {\n+ if ((dx || dy) && !Object.keys(oldPos).every(key => oldPos[key] === 0)) {\n c.data.moved = true\n const s = c.elm.style\n s.transform = s.WebkitTransform = `translate(${dx}px,${dy}px)`",
"filename": "src/platforms/web/runtime/components/transition-group.js",
"status": "modified"
},
{
"diff": "@@ -340,5 +340,40 @@ if (!isIE9) {\n )\n }).then(done)\n })\n+\n+ // GitHub issue #7879\n+ it('should work with v-show like v-if', done => {\n+ const vm = new Vue({\n+ template: `\n+ <div>\n+ <transition-group name=\"group\">\n+ <div v-show=\"ok\" key=\"foo\" class=\"test\">foo</div>\n+ </transition-group>\n+ </div>\n+ `,\n+ data: { ok: false }\n+ }).$mount(el)\n+\n+ vm.ok = true\n+ waitForUpdate(() => {\n+ expect(vm.$el.innerHTML.replace(/\\s?style=\"\"(\\s?)/g, '$1')).toBe(\n+ `<span>` +\n+ `<div class=\"test group-enter group-enter-active\">foo</div>` +\n+ `</span>`\n+ )\n+ }).thenWaitFor(nextFrame).then(() => {\n+ expect(vm.$el.innerHTML.replace(/\\s?style=\"\"(\\s?)/g, '$1')).toBe(\n+ `<span>` +\n+ `<div class=\"test group-enter-active group-enter-to\">foo</div>` +\n+ `</span>`\n+ )\n+ }).thenWaitFor(duration + buffer).then(() => {\n+ expect(vm.$el.innerHTML.replace(/\\s?style=\"\"(\\s?)/g, '$1')).toBe(\n+ `<span>` +\n+ `<div class=\"test\">foo</div>` +\n+ `</span>`\n+ )\n+ }).then(done)\n+ })\n })\n }",
"filename": "test/unit/features/transition/transition-group.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.13\r\n\r\n### Reproduction link\r\n[https://codepen.io/asiankingofwhales/pen/zpQBQM](https://codepen.io/asiankingofwhales/pen/zpQBQM)\r\n\r\n### Steps to reproduce\r\n1. Click Toggle Slide to enable transition, which is currently not working\r\n2. If you remove the scrollTop layout calculations in beforeSlideEnter, the element will slide in smoothly. Now the transition is working.\r\n\r\n### What is expected?\r\nGradual sliding in from right\r\n\r\n### What is actually happening?\r\nWith scrollTop calculations, the entering transition is gone.\r\n\r\n---\r\nI have found that wrapping the child component in an additional div will solve this problem. However, this seems like a hack.\r\n\r\nI apologize if this is not a bug. I have raised this questions in forum, discord and stackoverflow but no one is able to answer. So I have started to think that it might be a bug.\r\n\r\n### Stackoverflow Link\r\nhttps://stackoverflow.com/questions/48420077/beforeenter-hook-on-child-component-transition-cancelled-by-scrolltop-layout-cal\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "mmh, weird. We may be doing something wrong but here is a version without Vue (mimics what Vue does) that also fails but only on Chrome: http://codepan.net/gist/bf91a55172b1302acc2ade0681e9fbd3\r\nI think that by doing a layout calculation, it may be enforcing the values too early and thus not triggering the transition",
"created_at": "2018-01-25T09:55:38Z"
},
{
"body": "This is truly strange.. Maybe a chrome bug? \r\n\r\nThe vue example does have the same issue on safari and firefox. For now, my solution is just to wrap the child component in an additional div, which seems to solve the problem. But I wonder if this is a bug..\r\n\r\nSolution: https://codepen.io/asiankingofwhales/pen/baPWYQ?editors=1010 ",
"created_at": "2018-01-25T10:33:24Z"
},
{
"body": "maybe chrome just triggers a `transitionend` event when it does a layout calcultion?",
"created_at": "2018-01-26T13:21:33Z"
},
{
"body": "The vue example isn't limited to chrome only though. It's happening in firefox and safari too.\r\n\r\nBeing able to solve this by wrapping the child component in another parent div makes me think that this might be a vue bug too.. For now, this is my solution..",
"created_at": "2018-01-29T03:54:28Z"
},
{
"body": "thanks a lot!!!! :stuck_out_tongue_closed_eyes::stuck_out_tongue_closed_eyes::stuck_out_tongue_closed_eyes:\r\n\r\n感谢大神们!!!!!",
"created_at": "2018-03-13T07:03:25Z"
}
],
"number": 7531,
"title": "layout calculations in beforeEnter hook will cancel entering animation for transition elements"
} | {
"body": "fix #7531",
"number": 7823,
"review_comments": [],
"title": "fix: invoke component node create hooks before insertion"
} | {
"commits": [
{
"message": "fix: invoke component node create hooks before insertion\n\nfix #7531"
}
],
"files": [
{
"diff": "@@ -2,8 +2,6 @@ declare type InternalComponentOptions = {\n _isComponent: true;\n parent: Component;\n _parentVnode: VNode;\n- _parentElm: ?Node;\n- _refElm: ?Node;\n render?: Function;\n staticRenderFns?: Array<Function>\n };\n@@ -81,8 +79,6 @@ declare type ComponentOptions = {\n _componentTag: ?string;\n _scopeId: ?string;\n _base: Class<Component>;\n- _parentElm: ?Node;\n- _refElm: ?Node;\n };\n \n declare type PropOptions = {",
"filename": "flow/options.js",
"status": "modified"
},
{
"diff": "@@ -77,8 +77,6 @@ export function initInternalComponent (vm: Component, options: InternalComponent\n const parentVnode = options._parentVnode\n opts.parent = options.parent\n opts._parentVnode = parentVnode\n- opts._parentElm = options._parentElm\n- opts._refElm = options._refElm\n \n const vnodeComponentOptions = parentVnode.componentOptions\n opts.propsData = vnodeComponentOptions.propsData",
"filename": "src/core/instance/init.js",
"status": "modified"
},
{
"diff": "@@ -62,14 +62,7 @@ export function lifecycleMixin (Vue: Class<Component>) {\n // based on the rendering backend used.\n if (!prevVnode) {\n // initial render\n- vm.$el = vm.__patch__(\n- vm.$el, vnode, hydrating, false /* removeOnly */,\n- vm.$options._parentElm,\n- vm.$options._refElm\n- )\n- // no need for the ref nodes after initial patch\n- // this prevents keeping a detached DOM tree in memory (#5851)\n- vm.$options._parentElm = vm.$options._refElm = null\n+ vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)\n } else {\n // updates\n vm.$el = vm.__patch__(prevVnode, vnode)",
"filename": "src/core/instance/lifecycle.js",
"status": "modified"
},
{
"diff": "@@ -34,12 +34,7 @@ import {\n \n // inline hooks to be invoked on component VNodes during patch\n const componentVNodeHooks = {\n- init (\n- vnode: VNodeWithData,\n- hydrating: boolean,\n- parentElm: ?Node,\n- refElm: ?Node\n- ): ?boolean {\n+ init (vnode: VNodeWithData, hydrating: boolean): ?boolean {\n if (\n vnode.componentInstance &&\n !vnode.componentInstance._isDestroyed &&\n@@ -51,9 +46,7 @@ const componentVNodeHooks = {\n } else {\n const child = vnode.componentInstance = createComponentInstanceForVnode(\n vnode,\n- activeInstance,\n- parentElm,\n- refElm\n+ activeInstance\n )\n child.$mount(hydrating ? vnode.elm : undefined, hydrating)\n }\n@@ -215,15 +208,11 @@ export function createComponent (\n export function createComponentInstanceForVnode (\n vnode: any, // we know it's MountedComponentVNode but flow doesn't\n parent: any, // activeInstance in lifecycle state\n- parentElm?: ?Node,\n- refElm?: ?Node\n ): Component {\n const options: InternalComponentOptions = {\n _isComponent: true,\n- parent,\n _parentVnode: vnode,\n- _parentElm: parentElm || null,\n- _refElm: refElm || null\n+ parent\n }\n // check inline-template render functions\n const inlineTemplate = vnode.data.inlineTemplate",
"filename": "src/core/vdom/create-component.js",
"status": "modified"
},
{
"diff": "@@ -212,14 +212,15 @@ export function createPatchFunction (backend) {\n if (isDef(i)) {\n const isReactivated = isDef(vnode.componentInstance) && i.keepAlive\n if (isDef(i = i.hook) && isDef(i = i.init)) {\n- i(vnode, false /* hydrating */, parentElm, refElm)\n+ i(vnode, false /* hydrating */)\n }\n // after calling the init hook, if the vnode is a child component\n // it should've created a child instance and mounted it. the child\n // component also has set the placeholder vnode's elm.\n // in that case we can just return the element and be done.\n if (isDef(vnode.componentInstance)) {\n initComponent(vnode, insertedVnodeQueue)\n+ insert(parentElm, vnode.elm, refElm)\n if (isTrue(isReactivated)) {\n reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm)\n }\n@@ -681,7 +682,7 @@ export function createPatchFunction (backend) {\n }\n }\n \n- return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) {\n+ return function patch (oldVnode, vnode, hydrating, removeOnly) {\n if (isUndef(vnode)) {\n if (isDef(oldVnode)) invokeDestroyHook(oldVnode)\n return\n@@ -693,7 +694,7 @@ export function createPatchFunction (backend) {\n if (isUndef(oldVnode)) {\n // empty mount (likely as component), create new root element\n isInitialPatch = true\n- createElm(vnode, insertedVnodeQueue, parentElm, refElm)\n+ createElm(vnode, insertedVnodeQueue)\n } else {\n const isRealElement = isDef(oldVnode.nodeType)\n if (!isRealElement && sameVnode(oldVnode, vnode)) {",
"filename": "src/core/vdom/patch.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.13\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/hhu05cd2/18/](https://jsfiddle.net/hhu05cd2/18/)\r\n\r\n### Steps to reproduce\r\nAssign any element with ref to 0.\r\nSuch as <p :ref=\"0\"></p>\r\n\r\n\r\n### What is expected?\r\np exist in $refs\r\n\r\n### What is actually happening?\r\np isn't in $refs\r\n\r\n---\r\nWorkaround is to put additional char to :ref such as\r\n<p :ref=\"a0\"></p>\r\n\r\nNow, that p will be in this.$refs.\r\n\r\nReference: https://forum.vuejs.org/t/element-with-ref-0-disappear-from-refs/27925\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Looks like a bug. Probably [this check](https://github.com/vuejs/vue/blob/956756b1be7084daf8b6afb92ac0da7c24cde2a5/src/core/vdom/modules/ref.js#L22) should be replaced with `if (!isDef(key)) return`\r\n\r\n",
"created_at": "2018-02-20T11:54:11Z"
}
],
"number": 7669,
"title": "Assign :ref to zero result in missing element in $refs"
} | {
"body": "prevents missing elements when :ref value is \"0\"\r\n\r\nfix #7669\r\n\r\n<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n",
"number": 7676,
"review_comments": [],
"title": "fix(refs): allow ref key to be zero (fix #7669)"
} | {
"commits": [
{
"message": "fix(ref): allow ref key to be zero\n\nprevents missing elements when :ref value is \"0\"\n\nfix #7669"
}
],
"files": [
{
"diff": "@@ -1,6 +1,6 @@\n /* @flow */\n \n-import { remove } from 'shared/util'\n+import { remove, isDef } from 'shared/util'\n \n export default {\n create (_: any, vnode: VNodeWithData) {\n@@ -19,7 +19,7 @@ export default {\n \n export function registerRef (vnode: VNodeWithData, isRemoval: ?boolean) {\n const key = vnode.data.ref\n- if (!key) return\n+ if (!isDef(key)) return\n \n const vm = vnode.context\n const ref = vnode.componentInstance || vnode.elm",
"filename": "src/core/vdom/modules/ref.js",
"status": "modified"
},
{
"diff": "@@ -9,6 +9,10 @@ describe('ref', () => {\n test2: {\n id: 'test2',\n template: '<div>test2</div>'\n+ },\n+ test3: {\n+ id: 'test3',\n+ template: '<div>test3</div>'\n }\n }\n \n@@ -20,6 +24,7 @@ describe('ref', () => {\n template: `<div>\n <test ref=\"foo\"></test>\n <test2 :ref=\"value\"></test2>\n+ <test3 :ref=\"0\"></test3>\n </div>`,\n components\n })\n@@ -28,6 +33,8 @@ describe('ref', () => {\n expect(vm.$refs.foo.$options.id).toBe('test')\n expect(vm.$refs.bar).toBeTruthy()\n expect(vm.$refs.bar.$options.id).toBe('test2')\n+ expect(vm.$refs['0']).toBeTruthy()\n+ expect(vm.$refs['0'].$options.id).toBe('test3')\n })\n \n it('should dynamically update refs', done => {",
"filename": "test/unit/features/ref.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.13\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/lxjwlt/ajy768fs/](https://jsfiddle.net/lxjwlt/ajy768fs/)\r\n\r\n### Steps to reproduce\r\nin chrome 57 and 56, \r\n\r\n1. filter with empty arguments:\r\n\r\n ```html\r\n <div>{{text | someFilter()}}</div>\r\n ```\r\n\r\n2. when no parentheses:\r\n\r\n ```html\r\n <div>{{text | someFilter}}</div>\r\n ```\r\n\r\n\r\n### What is expected?\r\n\r\n1. no error\r\n2. no error\r\n\r\n### What is actually happening?\r\n\r\n1.in chrome 57 and 56, report error:\r\n\r\n```\r\n[Vue warn]: Error compiling template:\r\n\r\n<div>{{text | someFilter()}}</div>\r\n\r\n- invalid expression: Unexpected token ) in\r\n\r\n _s(_f(\"someFilter\")(text,))\r\n\r\n Raw expression: {{text | someFilter()}}\r\n\r\n\r\n\r\n(found in <Root>)\r\n```\r\n\r\n2.no error\r\n\r\n---\r\nI have also examined the chrome 58 and 63 which have no errors both, so i guess this bug only occurs in chrome 57-.\r\n\r\nmac-chrome57: https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Mac/444958/\r\n\r\nwin-chrome57: https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Win/444958/\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "It was generating `someFilter(text,)` which fails in older browsers.\r\nFYI you can do `text | someFilter` when there're no arguments",
"created_at": "2018-01-27T15:22:08Z"
}
],
"number": 7544,
"title": "filter with empty arguments cause error in chrome 57-"
} | {
"body": "Fix #7544\r\nMake sure no extra , is added at the end of the call so it also work with older browsers\r\n\r\n<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n",
"number": 7545,
"review_comments": [],
"title": "fix(codegen): support filters with () in older browsers"
} | {
"commits": [
{
"message": "fix(codegen): support filters with () in older browsers\n\nFix #7544\nMake sure no extra , is added at the end of the call so it also work with older browsers"
}
],
"files": [
{
"diff": "@@ -92,6 +92,6 @@ function wrapFilter (exp: string, filter: string): string {\n } else {\n const name = filter.slice(0, i)\n const args = filter.slice(i + 1)\n- return `_f(\"${name}\")(${exp},${args}`\n+ return `_f(\"${name}\")(${exp}${args !== ')' ? ',' + args : args}`\n }\n }",
"filename": "src/compiler/parser/filter-parser.js",
"status": "modified"
},
{
"diff": "@@ -44,6 +44,13 @@ describe('codegen', () => {\n )\n })\n \n+ it('generate filters with no arguments', () => {\n+ assertCodegen(\n+ '<div>{{ d | e() }}</div>',\n+ `with(this){return _c('div',[_v(_s(_f(\"e\")(d)))])}`\n+ )\n+ })\n+\n it('generate v-for directive', () => {\n assertCodegen(\n '<div><li v-for=\"item in items\" :key=\"item.uid\"></li></div>',",
"filename": "test/unit/modules/compiler/codegen.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.13\r\n\r\n### Reproduction link\r\n[https://codepen.io/zsk/pen/XVpxaR](https://codepen.io/zsk/pen/XVpxaR)\r\n\r\n### Steps to reproduce\r\nv1.0.28 is ok: https://codepen.io/zsk/pen/bagmYb\r\n\r\nv2.5.13 has bug: https://codepen.io/zsk/pen/XVpxaR\r\n\r\n### What is expected?\r\nforeignObject再嵌套svg元素,这个svg元素的子元素(如:rect)不能显示。\r\n\r\n### What is actually happening?\r\nforeignObject再嵌套svg元素,这个svg元素的子元素(如:rect)能显示。\r\n\r\n---\r\n在svg的foreignObject的元素内再嵌套svg元素,被嵌套的svg元素的子元素(如:rect)不能显示,不过text元素可以显示。\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [],
"number": 7330,
"title": "svg中foreignObject元素内的svg内部子元素不显示"
} | {
"body": "**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\n**Other information:**\r\nfix #7330",
"number": 7350,
"review_comments": [],
"title": "fix(vdom): svg inside foreignObject should be rendered with correct namespace (fix #7330)"
} | {
"commits": [
{
"message": "add failed test case"
},
{
"message": "fix failed test case"
},
{
"message": "fix(vdom): svg inside foreignObject should be rendered with correct namespace"
},
{
"message": "adjust comments"
}
],
"files": [
{
"diff": "@@ -139,7 +139,8 @@ function applyNS (vnode, ns, force) {\n if (isDef(vnode.children)) {\n for (let i = 0, l = vnode.children.length; i < l; i++) {\n const child = vnode.children[i]\n- if (isDef(child.tag) && (isUndef(child.ns) || isTrue(force))) {\n+ if (isDef(child.tag) && (\n+ isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {\n applyNS(child, ns, force)\n }\n }",
"filename": "src/core/vdom/create-element.js",
"status": "modified"
},
{
"diff": "@@ -135,10 +135,12 @@ describe('create-element', () => {\n it('render svg foreignObject with correct namespace', () => {\n const vm = new Vue({})\n const h = vm.$createElement\n- const vnode = h('svg', [h('foreignObject', [h('p')])])\n+ const vnode = h('svg', [h('foreignObject', [h('p'), h('svg')])])\n expect(vnode.ns).toBe('svg')\n expect(vnode.children[0].ns).toBe('svg')\n expect(vnode.children[0].children[0].ns).toBeUndefined()\n+ // #7330\n+ expect(vnode.children[0].children[1].ns).toBe('svg')\n })\n \n // #6642",
"filename": "test/unit/modules/vdom/create-element.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.9\r\n\r\n### Reproduction link\r\n[https://gist.github.com/2b3c1a683b334022c626917b0abb2adc](https://gist.github.com/2b3c1a683b334022c626917b0abb2adc)\r\n\r\n(I used a Gist, because ssrCompile is not exposed by the globals build of Vue.)\r\n\r\n### Steps to reproduce\r\n```javascript\r\ncompiler = require('vue-template-compiler')\r\ntemplate = \"<div id=\\\"foo,\\nbar\\\">\\n<textarea id=\\\"foo,\\nbar\\\">foo\\nbar</textarea>\\n</div>\"\r\nresult = compiler.ssrCompile(template)\r\nconsole.log(result.render)\r\n// output: with(this){return _c('div',{attrs:{\"id\":\"foo,\\nbar\"}},[_ssrNode(\"<textarea id=\\\"foo,\\\\nbar\\\">foo\\nbar</textarea>\")])}\r\n```\r\n\r\n### What is expected?\r\nvue-template-compiler should not double-escape newlines in attributes for _ssrNode string templates.\r\n\r\n### What is actually happening?\r\nvue-template-compiler double-escapes newlines in attributes of _ssrNodes.\r\n\r\n---\r\nIf you look at the output from the reproduction steps, you will see that the newline character '\\n' is only double escaped, if it is part of an attribute in an ssrNode, if is nor optimized to a string template and stored in the attrs property, is it fine and other newlines that are outside attributes are also fine.\r\n\r\nThe bug was observed with vue-template-compiler v2.5.9 and node.js v8.9.1.\r\n\r\nWhile the above example seems silly, newlines in attribute are very common when using responsive images, with multiple sizes in the srcset attribute, which are usually broken onto one line per size/url for readability and this is how a colleague of mine ran into this bug, where responsive images were working differently between ssr and rehydration due to the problem, because the browser aborted srcset parsing when finding the \"\\n\" literal string.\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "While the report explicitly mentions newlines, the double escaping also occurs for other escape sequences like `\\t`.",
"created_at": "2017-12-12T01:27:14Z"
},
{
"body": "It looks like the attribute is first escaped using `JSON.stringify` in `processAttrs` call to `addAttr` and then finally the whole string template is escaped again using `JSON.stringify(textBuffer)` inside `flattenSegments`, which causes the double escaping.",
"created_at": "2017-12-12T02:39:25Z"
},
{
"body": "I could fix the problem by applying the following patch to the `genAttrSegment` function:\r\n\r\n```diff\r\ndiff --git a/src/server/optimizing-compiler/modules.js b/src/server/optimizing-compiler/modules.js\r\nindex 41b1af1d..69a7be87 100644\r\n--- a/src/server/optimizing-compiler/modules.js\r\n+++ b/src/server/optimizing-compiler/modules.js\r\n@@ -77,7 +77,7 @@ function genAttrSegment (name: string, value: string): StringSegment {\r\n ? ` ${name}=\"${name}\"`\r\n : value === '\"\"'\r\n ? ` ${name}`\r\n- : ` ${name}=${value}`\r\n+ : ` ${name}=\"${JSON.parse(value)}\"`\r\n }\r\n } else {\r\n return {\r\n```",
"created_at": "2017-12-12T02:54:05Z"
}
],
"number": 7223,
"title": "vue-template-compiler double-escaping newlines in _ssrNode text string templates"
} | {
"body": "This fixes a double escaping of attribute values in the SSR optimizing\r\ncompiler, because literal attribute values get escaped early during the\r\ncall to `addAttr` inside `processAttrs` before it is known, if this\r\nattribute will be serialized to an _ssrNode string template.\r\n\r\nLater on the _ssrNode string template gets escaped again to preserve\r\nwhitespace and this causes double escaping of the whitespace inside the\r\nattribute value.\r\n\r\nThis approach fixes the problem by undoing the escaping by parsing the\r\nattribute value JSON in `genAttrSegment`, which is the easiest fix to\r\nthe problem, but probably not the best.\r\n\r\nThis fixes #7223 at least for the cases where I encountered the problem.\r\n\r\nSee #7223 for an in-depth description of the problem and a test-case.\r\n\r\n<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [ ] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n\r\nI would love to add a breaking test, that shows that the fix is working, but I'm not sure were to add it with the large test suite, so some advise on that would be appreciated.",
"number": 7224,
"review_comments": [],
"title": "fix(compiler): fix double escaping of ssrNode attribute values (fix #7223)"
} | {
"commits": [
{
"message": "fix(compiler): fix double escaping of ssrNode attribute values\n\nThis fixes a double escaping of attribute values in the SSR optimizing\ncompiler by unescaping the value in `genAttrSegment` because literal\nattribute values get escaped early during `processAttrs` before it is\nknown, if this attribute will be optimized to an _ssrNode string template,\nwhich is escaped as well, causing the double escape.\n\nfix #7223"
}
],
"files": [
{
"diff": "@@ -77,7 +77,7 @@ function genAttrSegment (name: string, value: string): StringSegment {\n ? ` ${name}=\"${name}\"`\n : value === '\"\"'\n ? ` ${name}`\n- : ` ${name}=${value}`\n+ : ` ${name}=\"${JSON.parse(value)}\"`\n }\n } else {\n return {",
"filename": "src/server/optimizing-compiler/modules.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.9\r\n\r\n### Reproduction link\r\n[https://codepen.io/cool_zjy/pen/KyLpve](https://codepen.io/cool_zjy/pen/KyLpve)\r\n\r\n### Steps to reproduce\r\n1. run the reproduction\r\n2. `VueComponent` logged in console\r\n3. uncomment `// mixins: [mixin],`\r\n4. run the reproduction again\r\n\r\n\r\n### What is expected?\r\n`VueComponent` logged in console\r\n\r\n### What is actually happening?\r\n`undefined` logged in console\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Please use `this` to access component instance in hooks and other methods.\r\nhttps://codepen.io/Akryum/pen/OOYywd",
"created_at": "2017-12-06T13:02:04Z"
},
{
"body": "@Akryum Why? Since 2.5 `data` function receives vm instance as the first argument https://github.com/vuejs/vue/pull/6760",
"created_at": "2017-12-06T13:16:03Z"
},
{
"body": "I'm on a PR.",
"created_at": "2017-12-06T13:39:51Z"
},
{
"body": "I think the fix is adding `this` as the second arg on `call` in the `mergeDataOrFn` function",
"created_at": "2017-12-06T13:42:19Z"
}
],
"number": 7191,
"title": "data method not called with `this` as argument when using mixins with data option"
} | {
"body": "Fix #7191 \r\n\r\n<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n",
"number": 7192,
"review_comments": [
{
"body": "should *be*",
"created_at": "2017-12-06T14:01:57Z"
}
],
"title": "Fix 7191 - data arg merge"
} | {
"commits": [
{
"message": "Call hook with vm arg when data merging"
},
{
"message": "Unit test"
},
{
"message": "Update data.spec.js"
}
],
"files": [
{
"diff": "@@ -85,18 +85,18 @@ export function mergeDataOrFn (\n // it has to be a function to pass previous merges.\n return function mergedDataFn () {\n return mergeData(\n- typeof childVal === 'function' ? childVal.call(this) : childVal,\n- typeof parentVal === 'function' ? parentVal.call(this) : parentVal\n+ typeof childVal === 'function' ? childVal.call(this, this) : childVal,\n+ typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal\n )\n }\n } else {\n return function mergedInstanceDataFn () {\n // instance merge\n const instanceData = typeof childVal === 'function'\n- ? childVal.call(vm)\n+ ? childVal.call(vm, vm)\n : childVal\n const defaultData = typeof parentVal === 'function'\n- ? parentVal.call(vm)\n+ ? parentVal.call(vm, vm)\n : parentVal\n if (instanceData) {\n return mergeData(instanceData, defaultData)",
"filename": "src/core/util/options.js",
"status": "modified"
},
{
"diff": "@@ -107,7 +107,7 @@ describe('Options data', () => {\n expect(vm.a).toBe(1)\n })\n \n- it('should called with this', () => {\n+ it('should be called with this', () => {\n const vm = new Vue({\n template: '<div><child></child></div>',\n provide: { foo: 1 },\n@@ -123,4 +123,32 @@ describe('Options data', () => {\n }).$mount()\n expect(vm.$el.innerHTML).toBe('<span>foo:1</span>')\n })\n+\n+ it('should be called with vm as first argument when merged', () => {\n+ const superComponent = {\n+ data: ({ foo }) => ({ ext: 'ext:' + foo })\n+ }\n+ const mixins = [\n+ {\n+ data: ({ foo }) => ({ mixin1: 'm1:' + foo })\n+ },\n+ {\n+ data: ({ foo }) => ({ mixin2: 'm2:' + foo })\n+ }\n+ ]\n+ const vm = new Vue({\n+ template: '<div><child></child></div>',\n+ provide: { foo: 1 },\n+ components: {\n+ child: {\n+ extends: superComponent,\n+ mixins,\n+ template: '<span>{{bar}}-{{ext}}-{{mixin1}}-{{mixin2}}</span>',\n+ inject: ['foo'],\n+ data: ({ foo }) => ({ bar: 'foo:' + foo })\n+ }\n+ }\n+ }).$mount()\n+ expect(vm.$el.innerHTML).toBe('<span>foo:1-ext:1-m1:1-m2:1</span>')\n+ })\n })",
"filename": "test/unit/features/options/data.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.2\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/50wL7mdz/71931/](https://jsfiddle.net/50wL7mdz/71931/)\r\n\r\n### Steps to reproduce\r\nrun the jsfiddle example\r\n\r\n### What is expected?\r\n`v-else` to work\r\n\r\n### What is actually happening?\r\n`v-else` seems to have no effect\r\n\r\n---\r\nmaybe related/duplicate with issue #6917 or issue #6907\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "I'd like a take a look at this if no one is on it yet :)",
"created_at": "2017-10-26T00:56:37Z"
},
{
"body": "This seems to be strongly related to the dynamic type `:type=\"'text'\"`",
"created_at": "2017-10-26T07:40:28Z"
},
{
"body": "It seems that we need to add a pre condition\r\n\r\nin https://github.com/vuejs/vue/blob/dev/src/platforms/web/compiler/modules/model.js#L31",
"created_at": "2017-10-26T15:37:38Z"
},
{
"body": "@misoguy OK, you come first 😭 ",
"created_at": "2017-10-26T15:58:46Z"
},
{
"body": "We also need to consider `v-else-if` ...\r\n\r\nI'm sorry to dirty your issue 😃 ",
"created_at": "2017-10-29T16:40:20Z"
},
{
"body": "I've been digging into this issue for a while and realized that it's not that simple.\r\nI have a roughly implemented working code for\r\n`<div v-if=\"ok\">haha</div><input v-else :type=\"type\" v-model=\"test\">`\r\nbut I think I need to write test for\r\n```\r\n<div v-if=\"ok\">haha</div>\r\n<input v-else-if=\"test==='b'\" :type=\"type\" v-model=\"test\">\r\n<input v-else :type=\"type\" v-model=\"test\">\r\n```\r\nand make this case to work as well. I'll work on this and send a PR :)",
"created_at": "2017-10-30T00:32:17Z"
},
{
"body": "@gebilaoxiong My browser didn't refresh and didn't see your comment and PR before commenting :( I guess this issue is closed then?",
"created_at": "2017-10-30T00:36:53Z"
},
{
"body": "@misoguy \r\n\r\nI thought no one was in the process of it, so it is repaired\r\n\r\nI don't know if there is any other problem",
"created_at": "2017-10-30T01:58:31Z"
},
{
"body": "@gebilaoxiong I should have commented that I was gonna work on it during the weekends.\r\nMy bad :( I tried out your code and tested it with \r\n```\r\n<div v-if=\"foo\">text</div>\r\n<input v-else-if=\"bar\" :type=\"type\" v-model=\"test\">\r\n<input v-else :type=\"type\" v-model=\"test\">\r\n```\r\nas well. I don't think there is any more problem regarding this issue 👍 ",
"created_at": "2017-10-30T02:05:28Z"
},
{
"body": "@misoguy \r\n\r\nyou can use your code to open a PR\r\n\r\nI will merge my code to yours",
"created_at": "2017-10-30T02:38:48Z"
},
{
"body": "@gebilaoxiong Would that be ok? But your implementation and test code seems much better than mine! :) I'll open a PR as you suggested and let you decide whether or not to merge yours with mine :)",
"created_at": "2017-10-30T03:07:47Z"
},
{
"body": "@gebilaoxiong I have opened a PR as you suggested and only included the code to check `v-else` since I didn't want to get the credit for your work regarding `v-else-if` :)\r\nIt would be nice to contribute for the first time on `vue.js`!\r\n\r\nBy the way, while implementing my first PR on `vue.js`, I found that it was wonderfully maintained with all the test codes that were written! Great library! 👍 ",
"created_at": "2017-10-30T03:31:33Z"
},
{
"body": "@misoguy have a nice day. 😄 \r\n",
"created_at": "2017-10-30T03:46:51Z"
},
{
"body": "Thank you!",
"created_at": "2017-10-30T04:40:51Z"
}
],
"number": 6918,
"title": "v-if / v-else not working with :type + v-model"
} | {
"body": "fix #6918\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [x] Yes\r\n- [ ] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n",
"number": 6955,
"review_comments": [],
"title": "fix #6918: v-if / v-else not working with :type + v-model"
} | {
"commits": [
{
"message": "Add test to verify bug reported in issue #6918"
},
{
"message": "Add Implementation to fix issue #6918"
},
{
"message": "fix(model): fix dynamic v-model with v-else-if statement"
}
],
"files": [
{
"diff": "@@ -29,6 +29,8 @@ function preTransformNode (el: ASTElement, options: CompilerOptions) {\n const typeBinding: any = getBindingAttr(el, 'type')\n const ifCondition = getAndRemoveAttr(el, 'v-if', true)\n const ifConditionExtra = ifCondition ? `&&(${ifCondition})` : ``\n+ const hasElse = getAndRemoveAttr(el, 'v-else', true) != null\n+ const elseIfCondition = getAndRemoveAttr(el, 'v-else-if', true)\n // 1. checkbox\n const branch0 = cloneASTElement(el)\n // process for on the main node\n@@ -59,6 +61,13 @@ function preTransformNode (el: ASTElement, options: CompilerOptions) {\n exp: ifCondition,\n block: branch2\n })\n+\n+ if (hasElse) {\n+ branch0.else = true\n+ } else if (elseIfCondition) {\n+ branch0.elseif = elseIfCondition\n+ }\n+\n return branch0\n }\n }",
"filename": "src/platforms/web/compiler/modules/model.js",
"status": "modified"
},
{
"diff": "@@ -40,6 +40,48 @@ describe('Directive v-model dynamic input type', () => {\n assertInputWorks(vm, chain).then(done)\n })\n \n+ it('with v-else', done => {\n+ const data = {\n+ ok: true,\n+ type: null,\n+ test: 'b'\n+ }\n+ const vm = new Vue({\n+ data,\n+ template: `<div v-if=\"ok\">haha</div><input v-else :type=\"type\" v-model=\"test\">`\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ expect(vm.$el.textContent).toBe('haha')\n+\n+ vm.ok = false\n+ assertInputWorks(vm).then(done)\n+ })\n+\n+ it('with v-else-if', done => {\n+ const vm = new Vue({\n+ data: {\n+ foo: true,\n+ bar: false,\n+ type: null,\n+ test: 'b'\n+ },\n+ template: `<div v-if=\"foo\">text</div><input v-else-if=\"bar\" :type=\"type\" v-model=\"test\">`\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+\n+ const chain = waitForUpdate(() => {\n+ expect(vm.$el.textContent).toBe('text')\n+ }).then(() => {\n+ vm.foo = false\n+ }).then(() => {\n+ expect(vm._vnode.isComment).toBe(true)\n+ }).then(() => {\n+ vm.bar = true\n+ })\n+\n+ assertInputWorks(vm, chain).then(done)\n+ })\n+\n it('with v-for', done => {\n const vm = new Vue({\n data: {",
"filename": "test/unit/features/directives/model-dynamic.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.2\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/50wL7mdz/71931/](https://jsfiddle.net/50wL7mdz/71931/)\r\n\r\n### Steps to reproduce\r\nrun the jsfiddle example\r\n\r\n### What is expected?\r\n`v-else` to work\r\n\r\n### What is actually happening?\r\n`v-else` seems to have no effect\r\n\r\n---\r\nmaybe related/duplicate with issue #6917 or issue #6907\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "I'd like a take a look at this if no one is on it yet :)",
"created_at": "2017-10-26T00:56:37Z"
},
{
"body": "This seems to be strongly related to the dynamic type `:type=\"'text'\"`",
"created_at": "2017-10-26T07:40:28Z"
},
{
"body": "It seems that we need to add a pre condition\r\n\r\nin https://github.com/vuejs/vue/blob/dev/src/platforms/web/compiler/modules/model.js#L31",
"created_at": "2017-10-26T15:37:38Z"
},
{
"body": "@misoguy OK, you come first 😭 ",
"created_at": "2017-10-26T15:58:46Z"
},
{
"body": "We also need to consider `v-else-if` ...\r\n\r\nI'm sorry to dirty your issue 😃 ",
"created_at": "2017-10-29T16:40:20Z"
},
{
"body": "I've been digging into this issue for a while and realized that it's not that simple.\r\nI have a roughly implemented working code for\r\n`<div v-if=\"ok\">haha</div><input v-else :type=\"type\" v-model=\"test\">`\r\nbut I think I need to write test for\r\n```\r\n<div v-if=\"ok\">haha</div>\r\n<input v-else-if=\"test==='b'\" :type=\"type\" v-model=\"test\">\r\n<input v-else :type=\"type\" v-model=\"test\">\r\n```\r\nand make this case to work as well. I'll work on this and send a PR :)",
"created_at": "2017-10-30T00:32:17Z"
},
{
"body": "@gebilaoxiong My browser didn't refresh and didn't see your comment and PR before commenting :( I guess this issue is closed then?",
"created_at": "2017-10-30T00:36:53Z"
},
{
"body": "@misoguy \r\n\r\nI thought no one was in the process of it, so it is repaired\r\n\r\nI don't know if there is any other problem",
"created_at": "2017-10-30T01:58:31Z"
},
{
"body": "@gebilaoxiong I should have commented that I was gonna work on it during the weekends.\r\nMy bad :( I tried out your code and tested it with \r\n```\r\n<div v-if=\"foo\">text</div>\r\n<input v-else-if=\"bar\" :type=\"type\" v-model=\"test\">\r\n<input v-else :type=\"type\" v-model=\"test\">\r\n```\r\nas well. I don't think there is any more problem regarding this issue 👍 ",
"created_at": "2017-10-30T02:05:28Z"
},
{
"body": "@misoguy \r\n\r\nyou can use your code to open a PR\r\n\r\nI will merge my code to yours",
"created_at": "2017-10-30T02:38:48Z"
},
{
"body": "@gebilaoxiong Would that be ok? But your implementation and test code seems much better than mine! :) I'll open a PR as you suggested and let you decide whether or not to merge yours with mine :)",
"created_at": "2017-10-30T03:07:47Z"
},
{
"body": "@gebilaoxiong I have opened a PR as you suggested and only included the code to check `v-else` since I didn't want to get the credit for your work regarding `v-else-if` :)\r\nIt would be nice to contribute for the first time on `vue.js`!\r\n\r\nBy the way, while implementing my first PR on `vue.js`, I found that it was wonderfully maintained with all the test codes that were written! Great library! 👍 ",
"created_at": "2017-10-30T03:31:33Z"
},
{
"body": "@misoguy have a nice day. 😄 \r\n",
"created_at": "2017-10-30T03:46:51Z"
},
{
"body": "Thank you!",
"created_at": "2017-10-30T04:40:51Z"
}
],
"number": 6918,
"title": "v-if / v-else not working with :type + v-model"
} | {
"body": "fix #6918\r\n\r\n<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [x] Yes\r\n- [ ] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n",
"number": 6952,
"review_comments": [],
"title": "fix(model): fix dynamic v-model with v-else statement"
} | {
"commits": [
{
"message": "fix(model): fix dynamic v-model with v-else statement\n\nfix #6918"
}
],
"files": [
{
"diff": "@@ -29,6 +29,8 @@ function preTransformNode (el: ASTElement, options: CompilerOptions) {\n const typeBinding: any = getBindingAttr(el, 'type')\n const ifCondition = getAndRemoveAttr(el, 'v-if', true)\n const ifConditionExtra = ifCondition ? `&&(${ifCondition})` : ``\n+ const elseStmt = getAndRemoveAttr(el, 'v-else', true)\n+ const elseIfStmt = getAndRemoveAttr(el, 'v-else-if', true)\n // 1. checkbox\n const branch0 = cloneASTElement(el)\n // process for on the main node\n@@ -59,6 +61,13 @@ function preTransformNode (el: ASTElement, options: CompilerOptions) {\n exp: ifCondition,\n block: branch2\n })\n+\n+ // v-else and v-else-if\n+ if (elseStmt != null) {\n+ branch0.else = true\n+ } else if (elseIfStmt) {\n+ branch0.elseif = elseIfStmt\n+ }\n return branch0\n }\n }",
"filename": "src/platforms/web/compiler/modules/model.js",
"status": "modified"
},
{
"diff": "@@ -40,6 +40,51 @@ describe('Directive v-model dynamic input type', () => {\n assertInputWorks(vm, chain).then(done)\n })\n \n+ it('with v-else-if', done => {\n+ const vm = new Vue({\n+ data: {\n+ foo: true,\n+ bar: false,\n+ type: null,\n+ test: 'b'\n+ },\n+ template: `<div v-if=\"foo\">text</div><input v-else-if=\"bar\" :type=\"type\" v-model=\"test\">`\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+\n+ const chain = waitForUpdate(() => {\n+ expect(vm.$el.textContent).toBe('text')\n+ }).then(() => {\n+ vm.foo = false\n+ }).then(() => {\n+ expect(vm._vnode.isComment).toBe(true)\n+ }).then(() => {\n+ vm.bar = true\n+ })\n+\n+ assertInputWorks(vm, chain).then(done)\n+ })\n+\n+ it('with v-else', done => {\n+ const vm = new Vue({\n+ data: {\n+ ok: true,\n+ type: null,\n+ test: 'b'\n+ },\n+ template: `<div v-if=\"ok\">text</div><input v-else :type=\"type\" v-model=\"test\">`\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+\n+ const chain = waitForUpdate(() => {\n+ expect(vm.$el.textContent).toBe('text')\n+ }).then(() => {\n+ vm.ok = false\n+ })\n+\n+ assertInputWorks(vm, chain).then(done)\n+ })\n+\n it('with v-for', done => {\n const vm = new Vue({\n data: {",
"filename": "test/unit/features/directives/model-dynamic.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.2\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/CHENGKANG/4owjvLLk/5/](https://jsfiddle.net/CHENGKANG/4owjvLLk/5/)\r\n\r\n### Steps to reproduce\r\n1. Add multiple custom event listeners\r\n```js\r\nthis.$on(['event1', 'event2'], () => {\r\n console.log('This is callback.')\r\n})\r\n```\r\n2. Try to remove them with `vm.$off`\r\n```\r\nthis.$off(['event1', 'event2'])\r\n```\r\n3. Try to emit the removed events\r\n```\r\nthis.$emit('event1')\r\n```\r\n\r\n### What is expected?\r\nNothing should happen because the event listeners should have been removed.\r\n\r\n### What is actually happening?\r\nGot `\"This is callback.\"` printed in the console, which means that the event listeners are not removed as expected.\r\n\r\n---\r\nPlease check [my post](https://forum.vuejs.org/t/vm-off-not-working-when-passing-an-array-as-first-argument/20555) in Vue forum for more details.\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Changing the condition for **specific event** from `arguments.length === 1` to `!fn` should do.\r\n\r\n```js\r\n // Fixed Version\r\n Vue.prototype.$off = function (event?: string | Array<string>, fn?: Function): Component {\r\n const vm: Component = this\r\n // all\r\n if (!arguments.length) {\r\n vm._events = Object.create(null)\r\n return vm\r\n }\r\n // array of events\r\n if (Array.isArray(event)) {\r\n for (let i = 0, l = event.length; i < l; i++) {\r\n this.$off(event[i], fn)\r\n }\r\n return vm\r\n }\r\n // specific event\r\n const cbs = vm._events[event]\r\n if (!cbs) {\r\n return vm\r\n }\r\n if (!fn) {\r\n vm._events[event] = null\r\n return vm\r\n }\r\n\r\n // specific handler\r\n let cb\r\n let i = cbs.length\r\n while (i--) {\r\n cb = cbs[i]\r\n if (cb === fn || cb.fn === fn) {\r\n cbs.splice(i, 1)\r\n break\r\n }\r\n }\r\n return vm\r\n }\r\n```\r\n\r\n```js\r\n // Current Version\r\n Vue.prototype.$off = function (event, fn) {\r\n var this$1 = this;\r\n\r\n var vm = this;\r\n // all\r\n if (!arguments.length) {\r\n vm._events = Object.create(null);\r\n return vm\r\n }\r\n // array of events\r\n if (Array.isArray(event)) {\r\n for (var i = 0, l = event.length; i < l; i++) {\r\n this$1.$off(event[i], fn);\r\n }\r\n return vm\r\n }\r\n // specific event\r\n var cbs = vm._events[event];\r\n if (!cbs) {\r\n return vm\r\n }\r\n if (arguments.length === 1) {\r\n vm._events[event] = null;\r\n return vm\r\n }\r\n if (fn) {\r\n // specific handler\r\n var cb;\r\n var i$1 = cbs.length;\r\n while (i$1--) {\r\n cb = cbs[i$1];\r\n if (cb === fn || cb.fn === fn) {\r\n cbs.splice(i$1, 1);\r\n break\r\n }\r\n }\r\n }\r\n return vm\r\n };\r\n```",
"created_at": "2017-10-27T20:13:05Z"
},
{
"body": "Thanks to the nice description and analysis by @cheng-kang , I have just submitted #6949 with a passing test.",
"created_at": "2017-10-28T16:12:49Z"
},
{
"body": "closed via c24f3e42",
"created_at": "2017-11-02T21:11:59Z"
}
],
"number": 6945,
"title": "`vm.$off` not working when passing an array as first argument"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix of #6945 \r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [X] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [X] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [X] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [X] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [X] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n\r\nThe existing test were passing due to the fact that the $off had a second argument. I have fixed the bug and introduced one more test to test the scenario where it doesn't make use of the second argument.",
"number": 6949,
"review_comments": [],
"title": "fix #6945: properly $off array of events"
} | {
"commits": [
{
"message": "fix(events): properly $off array of events"
}
],
"files": [
{
"diff": "@@ -92,7 +92,7 @@ export function eventsMixin (Vue: Class<Component>) {\n if (!cbs) {\n return vm\n }\n- if (arguments.length === 1) {\n+ if (!fn) {\n vm._events[event] = null\n return vm\n }",
"filename": "src/core/instance/events.js",
"status": "modified"
},
{
"diff": "@@ -41,6 +41,13 @@ describe('Instance methods events', () => {\n expect(spy.calls.count()).toBe(1)\n })\n \n+ it('$off multi event without callback', () => {\n+ vm.$on(['test1', 'test2'], spy)\n+ vm.$off(['test1', 'test2'])\n+ vm.$emit('test1')\n+ expect(spy).not.toHaveBeenCalled()\n+ })\n+\n it('$once', () => {\n vm.$once('test', spy)\n vm.$emit('test', 1, 2, 3)",
"filename": "test/unit/features/instance/methods-events.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.5.0\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/nkovacs/rt9vcrj2/3/](https://jsfiddle.net/nkovacs/rt9vcrj2/3/)\r\n\r\n### Steps to reproduce\r\nIf you use a dynamic type on an input, and the property is not called `type`, you'll get this warning:\r\n\r\n```\r\nvue.js:491 [Vue warn]: Property or method \"type\" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.\r\n\r\n(found in <Root>)\r\n```\r\n\r\nAnd it won't work if you switch from a normal type like text to a checkbox or radio button (the special types that are in the else branch: https://github.com/vuejs/vue/commit/f3fe012d5499f607656b152ce5fcb506c641f9f4#diff-6eaa1698ef4f51c9112e2e5dd84fcde8R4)\r\n\r\nClick the button (Click me) to switch the input to a checkbox, then try checking and unchecking the box. The model's value will not change.\r\n\r\nCalling the property `type` works, the model's value will change: https://jsfiddle.net/nkovacs/rt9vcrj2/2/\r\n\r\n### What is expected?\r\nDynamic input type should work regardless of the property name.\r\n\r\n### What is actually happening?\r\nDynamic input type only works if the property is called `type`\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [],
"number": 6800,
"title": "Dynamic input type only works if the property is called type"
} | {
"body": "Fix #6800\r\n\r\n<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [ ] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n",
"number": 6802,
"review_comments": [],
"title": "fix(model): allow arbitrary naems for type binding"
} | {
"commits": [
{
"message": "fix(model): allow arbitrary naems for type binding\n\nFix #6800"
}
],
"files": [
{
"diff": "@@ -36,7 +36,7 @@ function preTransformNode (el: ASTElement, options: CompilerOptions) {\n addRawAttr(branch0, 'type', 'checkbox')\n processElement(branch0, options)\n branch0.processed = true // prevent it from double-processed\n- branch0.if = `type==='checkbox'` + ifConditionExtra\n+ branch0.if = `(${typeBinding})==='checkbox'` + ifConditionExtra\n addIfCondition(branch0, {\n exp: branch0.if,\n block: branch0\n@@ -47,7 +47,7 @@ function preTransformNode (el: ASTElement, options: CompilerOptions) {\n addRawAttr(branch1, 'type', 'radio')\n processElement(branch1, options)\n addIfCondition(branch0, {\n- exp: `type==='radio'` + ifConditionExtra,\n+ exp: `(${typeBinding})==='radio'` + ifConditionExtra,\n block: branch1\n })\n // 3. other",
"filename": "src/platforms/web/compiler/modules/model.js",
"status": "modified"
},
{
"diff": "@@ -4,15 +4,15 @@ describe('Directive v-model dynamic input type', () => {\n it('should work', done => {\n const vm = new Vue({\n data: {\n- type: null,\n+ inputType: null,\n test: 'b'\n },\n- template: `<input :type=\"type\" v-model=\"test\">`\n+ template: `<input :type=\"inputType\" v-model=\"test\">`\n }).$mount()\n document.body.appendChild(vm.$el)\n \n // test text\n- assertInputWorks(vm).then(done)\n+ assertInputWorks(vm, 'inputType').then(done)\n })\n \n it('with v-if', done => {\n@@ -87,7 +87,11 @@ describe('Directive v-model dynamic input type', () => {\n })\n })\n \n-function assertInputWorks (vm, chain) {\n+function assertInputWorks (vm, type, chain) {\n+ if (typeof type !== 'string') {\n+ if (!chain) chain = type\n+ type = 'type'\n+ }\n if (!chain) chain = waitForUpdate()\n chain.then(() => {\n expect(vm.$el.value).toBe('b')\n@@ -99,7 +103,7 @@ function assertInputWorks (vm, chain) {\n expect(vm.test).toBe('c')\n }).then(() => {\n // change it to password\n- vm.type = 'password'\n+ vm[type] = 'password'\n vm.test = 'b'\n }).then(() => {\n expect(vm.$el.type).toBe('password')\n@@ -109,7 +113,7 @@ function assertInputWorks (vm, chain) {\n expect(vm.test).toBe('c')\n }).then(() => {\n // change it to checkbox...\n- vm.type = 'checkbox'\n+ vm[type] = 'checkbox'\n }).then(() => {\n expect(vm.$el.type).toBe('checkbox')\n expect(vm.$el.checked).toBe(true)",
"filename": "test/unit/features/directives/model-dynamic.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.4.4\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/sn7o1mm3/](https://jsfiddle.net/sn7o1mm3/)\r\n\r\n### Steps to reproduce\r\nEmbed `<p xmlns=\"http://www.w3.org/1999/xhtml\">` in the svg <foreignObject> element \r\n\r\n### What is expected?\r\nthe `<p>` should be rendered as a htmlElment and show.\r\n\r\n### What is actually happening?\r\n`<p>` did not show\r\n\r\n---\r\nseems related to this https://github.com/vuejs/vue/issues/6506\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Thanks @rrandom . An issue related with #6506\r\n\r\nA svg namespace now is attached to the `p` element within `foreignObject`, so it gets an unexpected behavior.\r\n\r\nI'm trying to fix it.\r\n\r\nPS, it seems also broken with the previous vue version because of the `isSVG` check, as `isSVG` checks the lowercased of `foreignObject`\r\n\r\nSomething more about https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject",
"created_at": "2017-09-20T00:32:40Z"
},
{
"body": "Seems that the parameter of method `createElementNS` is case-sensitive.\r\n[https://dom.spec.whatwg.org/#internal-createelementns-steps](https://dom.spec.whatwg.org/#internal-createelementns-steps)",
"created_at": "2017-09-22T03:46:39Z"
}
],
"number": 6642,
"title": "Embed HTML into an HTML5 SVG fragment got wrong namespace in template"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n\r\nfix #6642 \r\n",
"number": 6665,
"review_comments": [],
"title": "fix: remove ns within foreignObject node.fix #6642"
} | {
"commits": [
{
"message": "fix: remove ns within foreignObject node."
},
{
"message": "style: remove semicolon"
},
{
"message": "style: remove semicolon"
},
{
"message": "Merge remote-tracking branch 'originUpstream/dev' into fix-svg"
}
],
"files": [
{
"diff": "@@ -126,13 +126,34 @@ function applyNS (vnode, ns) {\n vnode.ns = ns\n if (vnode.tag === 'foreignObject') {\n // use default namespace inside foreignObject\n+ // #6642\n+ removeNS(vnode)\n return\n }\n+ walkChildren(\n+ vnode,\n+ child => isDef(child.tag) && isUndef(child.ns),\n+ child => applyNS(child, ns)\n+ )\n+}\n+\n+function removeNS (vnode: VNode): void {\n+ walkChildren(\n+ vnode,\n+ child => isDef(child.tag) && isDef(child.ns),\n+ child => {\n+ child.ns = undefined\n+ removeNS(child)\n+ }\n+ )\n+}\n+\n+function walkChildren (vnode: VNode, tester: Function, cb: Function): void {\n if (isDef(vnode.children)) {\n for (let i = 0, l = vnode.children.length; i < l; i++) {\n const child = vnode.children[i]\n- if (isDef(child.tag) && isUndef(child.ns)) {\n- applyNS(child, ns)\n+ if (tester(child)) {\n+ cb(child)\n }\n }\n }",
"filename": "src/core/vdom/create-element.js",
"status": "modified"
},
{
"diff": "@@ -26,7 +26,7 @@ export const isHTMLTag = makeMap(\n // contain child elements.\n export const isSVG = makeMap(\n 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +\n- 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +\n+ 'foreignobject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +\n 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',\n true\n )",
"filename": "src/platforms/web/util/element.js",
"status": "modified"
},
{
"diff": "@@ -141,6 +141,32 @@ describe('create-element', () => {\n expect(vnode.children[0].children[0].ns).toBeUndefined()\n })\n \n+ // #6642\n+ it('render svg foreignObject component with correct namespace', () => {\n+ const vm = new Vue({\n+ template: `\n+ <svg>\n+ <test></test>\n+ </svg>\n+ `,\n+ components: {\n+ test: {\n+ template: `\n+ <foreignObject>\n+ <p xmlns=\"http://www.w3.org/1999/xhtml\"></p>\n+ </foreignObject>\n+ `\n+ }\n+ }\n+ }).$mount()\n+ const testComp = vm.$children[0]\n+ expect(testComp.$vnode.ns).toBe('svg')\n+ expect(testComp._vnode.tag).toBe('foreignObject')\n+ expect(testComp._vnode.ns).toBe('svg')\n+ expect(testComp._vnode.children[0].tag).toBe('p')\n+ expect(testComp._vnode.children[0].ns).toBeUndefined()\n+ })\n+\n // #6506\n it('render SVGAElement in a component correctly', () => {\n const vm = new Vue({",
"filename": "test/unit/modules/vdom/create-element.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.4.2\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/50wL7mdz/55826/](https://jsfiddle.net/50wL7mdz/55826/)\r\n\r\n### Steps to reproduce\r\n1. Use Vue.extend() to create a subclass which contains `provide` option.\r\n2. Inject property in child component of subclass.\r\n\r\n### What is expected?\r\nProperty is injected correctly.\r\n\r\n### What is actually happening?\r\nProperty is not injected.\r\n\r\n---\r\nIn src/core/util/options.js, Line 97-99. `defaultData` is set to `undefined` if `parentVal` is not a function. It may cause this issue.\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [],
"number": 6436,
"title": "Inject/Provide not working in Vue.extend() class."
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n#6436 ",
"number": 6473,
"review_comments": [],
"title": "fix(provide): provide should default to parentVal during merging, fix #6436"
} | {
"commits": [
{
"message": "test(inject): add failing test for provide with Vue.extend"
},
{
"message": "fix(provide): provide should default to parentVal"
}
],
"files": [
{
"diff": "@@ -96,7 +96,7 @@ export function mergeDataOrFn (\n : childVal\n const defaultData = typeof parentVal === 'function'\n ? parentVal.call(vm)\n- : undefined\n+ : parentVal\n if (instanceData) {\n return mergeData(instanceData, defaultData)\n } else {",
"filename": "src/core/util/options.js",
"status": "modified"
},
{
"diff": "@@ -545,4 +545,24 @@ describe('Options provide/inject', () => {\n \n expect(vm.$el.textContent).toBe(`foo: foo injected, bar: bar injected`)\n })\n+\n+ it('merge provide with object syntax when using Vue.extend', () => {\n+ const child = {\n+ inject: ['foo'],\n+ template: `<span/>`,\n+ created () {\n+ injected = this.foo\n+ }\n+ }\n+ const Ctor = Vue.extend({\n+ provide: { foo: 'foo' },\n+ render (h) {\n+ return h(child)\n+ }\n+ })\n+\n+ new Ctor().$mount()\n+\n+ expect(injected).toEqual('foo')\n+ })\n })",
"filename": "test/unit/features/options/inject.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.4.2\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/50wL7mdz/50757/](https://jsfiddle.net/50wL7mdz/50757/)\r\n\r\n### Steps to reproduce\r\nAccess $attrs as object within component context, when no props were provided.\r\n\r\n### What is expected?\r\n$attrs is an object containing unrecognized props. Therefore I would expect an empty object, when no props are specified on component tag.\r\n\r\n### What is actually happening?\r\n$attrs is undefined\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Out of curiosity, what problem are you facing by having an undefined `$attrs`? Are you accessing `$attrs.something`? (if so, why?)\r\n\r\nedit: I'm also asking because having `$attrs` equal undefined when there're no attrs can actually be useful\r\n",
"created_at": "2017-08-01T08:30:33Z"
},
{
"body": "@greegus, in case you're doing something like `if ($attrs.myProp)` you can do `if ($attrs?.myProp)` by using [babel-plugin-transform-optional-chaining](https://www.npmjs.com/package/babel-plugin-transform-optional-chaining).",
"created_at": "2017-08-01T21:33:43Z"
},
{
"body": "I would judge this to be expected behaviour, but it's debatable.",
"created_at": "2017-08-02T14:05:42Z"
},
{
"body": "ping @greegus ",
"created_at": "2017-08-07T16:21:09Z"
},
{
"body": "Just ran into this and it was definitely unexpected for me that `$attrs` should ever be `undefined`.\r\n\r\nFor example, if you were writing a todo app that starts out with no todos, it would be very strange to make the list begin as `undefined` instead of `[]`. You'd have to add `if` statements (or optional chaining) all over your app. This case is similar.\r\n\r\nFor niche cases when a user wants to check if any `$attrs` exist, it'd still be possible to use `Object.keys($attrs).length`, so that case is still covered.\r\n\r\nThe part that really convinces me this is a bug though, is that `$attrs` _is_ set to an empty object [when a prop is passed to a component](https://jsfiddle.net/chrisvfritz/kev55ep3/) - as the OP points out. So currently, really checking if any `$attrs` exist would require both strategies:\r\n\r\n``` js\r\n$attrs && Object.keys($attrs).length\r\n```",
"created_at": "2017-08-08T17:04:05Z"
},
{
"body": "@chrisvfritz convinced me - it's a bug.",
"created_at": "2017-08-08T17:28:30Z"
},
{
"body": "@LinusBorg Looks like no one is working on this bug currently. May I have a pr for this?",
"created_at": "2017-08-24T04:25:53Z"
},
{
"body": "Sure! ",
"created_at": "2017-08-24T04:38:43Z"
}
],
"number": 6263,
"title": "$attrs is undefined when component has no props"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\nfix #6263",
"number": 6441,
"review_comments": [],
"title": "fix #6263: $attrs is undefined when component has no props bug (#6263)"
} | {
"commits": [
{
"message": "fix is undefined when component has no props bug (#6263)"
},
{
"message": "Update render.js"
},
{
"message": "fix: ensure $listeners is also an object + fix types"
}
],
"files": [
{
"diff": "@@ -29,8 +29,8 @@ declare interface Component {\n $slots: { [key: string]: Array<VNode> };\n $scopedSlots: { [key: string]: () => VNodeChildren };\n $vnode: VNode; // the placeholder node for the component in parent's render tree\n- $attrs: ?{ [key: string] : string };\n- $listeners: ?{ [key: string]: Function | Array<Function> };\n+ $attrs: { [key: string] : string };\n+ $listeners: { [key: string]: Function | Array<Function> };\n $isServer: boolean;\n \n // public methods",
"filename": "flow/component.js",
"status": "modified"
},
{
"diff": "@@ -232,8 +232,8 @@ export function updateChildComponent (\n // update $attrs and $listensers hash\n // these are also reactive so they may trigger child update if the child\n // used them during render\n- vm.$attrs = parentVnode.data && parentVnode.data.attrs\n- vm.$listeners = listeners\n+ vm.$attrs = (parentVnode.data && parentVnode.data.attrs) || emptyObject\n+ vm.$listeners = listeners || emptyObject\n \n // update props\n if (propsData && vm.$options.props) {",
"filename": "src/core/instance/lifecycle.js",
"status": "modified"
},
{
"diff": "@@ -49,17 +49,18 @@ export function initRender (vm: Component) {\n // $attrs & $listeners are exposed for easier HOC creation.\n // they need to be reactive so that HOCs using them are always updated\n const parentData = parentVnode && parentVnode.data\n+\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n- defineReactive(vm, '$attrs', parentData && parentData.attrs, () => {\n+ defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, () => {\n !isUpdatingChildComponent && warn(`$attrs is readonly.`, vm)\n }, true)\n- defineReactive(vm, '$listeners', vm.$options._parentListeners, () => {\n+ defineReactive(vm, '$listeners', vm.$options._parentListeners || emptyObject, () => {\n !isUpdatingChildComponent && warn(`$listeners is readonly.`, vm)\n }, true)\n } else {\n- defineReactive(vm, '$attrs', parentData && parentData.attrs, null, true)\n- defineReactive(vm, '$listeners', vm.$options._parentListeners, null, true)\n+ defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true)\n+ defineReactive(vm, '$listeners', vm.$options._parentListeners || emptyObject, null, true)\n }\n }\n ",
"filename": "src/core/instance/render.js",
"status": "modified"
},
{
"diff": "@@ -146,6 +146,20 @@ describe('Instance properties', () => {\n }).then(done)\n })\n \n+ // #6263\n+ it('$attrs should not be undefined when no props passed in', () => {\n+ const vm = new Vue({\n+ template: `<foo/>`,\n+ data: { foo: 'foo' },\n+ components: {\n+ foo: {\n+ template: `<div>{{ this.foo }}</div>`\n+ }\n+ }\n+ }).$mount()\n+ expect(vm.$attrs).toBeDefined()\n+ })\n+\n it('warn mutating $attrs', () => {\n const vm = new Vue()\n vm.$attrs = {}",
"filename": "test/unit/features/instance/properties.spec.js",
"status": "modified"
},
{
"diff": "@@ -45,8 +45,8 @@ export declare class Vue {\n readonly $ssrContext: any;\n readonly $props: any;\n readonly $vnode: VNode;\n- readonly $attrs: { [key: string] : string } | void;\n- readonly $listeners: { [key: string]: Function | Array<Function> } | void;\n+ readonly $attrs: { [key: string] : string };\n+ readonly $listeners: { [key: string]: Function | Array<Function> };\n \n $mount(elementOrSelector?: Element | String, hydrating?: boolean): this;\n $forceUpdate(): void;",
"filename": "types/vue.d.ts",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.4.2\r\n\r\n### Reproduction link\r\n[http://jsfiddle.net/yMv7y/3265/](http://jsfiddle.net/yMv7y/3265/)\r\n\r\n### Steps to reproduce\r\nOn the JSFiddle, wait for the `setTimeout` on L15 to complete after two seconds.\r\n\r\n### What is expected?\r\nFor CustomElA to still be in the DOM.\r\n\r\n### What is actually happening?\r\nCustomElA is removed from the DOM on re-render. However, it comes back on the third re-render (tested using `setInterval` instead of `setTimeout` on JSFiddle on L16).\r\n\r\n---\r\nThe JSfiddle is using Vue v2.4.0 but I have verified the bug on v2.4.2 locally.\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Looks like a bug, thanks for reporting it. Looks like it was introduced in 2.1.4. It looks like the problem happens during the patch of vnodes though.\r\n\r\nedit: looks like `_isDestroyed` is false at `init` during vnode patch, making it not to call mount and disappearing from the node tree",
"created_at": "2017-08-15T07:22:00Z"
},
{
"body": "This is fixed, but do note that because you are changing the element wrapping the slots, the element is considered \"replaced\" and thus all slot content, including the components in it, will be destroyed and then re-created. This is unfortunately how the vdom patching works and unlikely to change.",
"created_at": "2017-08-29T22:58:06Z"
},
{
"body": "@yyx990803 \r\nSounds good, thanks. Do you have a ballpark date for the next release?",
"created_at": "2017-08-30T00:38:39Z"
},
{
"body": "Also wondering about when the next release will occur, or, in the mean-time, is there a way to install this version? Thanks.",
"created_at": "2017-09-08T22:33:42Z"
},
{
"body": "@Tolmark12 clone the repo, build the files and run `npm link` to use the local version of vue 😉 (those are very rough instructions)",
"created_at": "2017-09-08T23:28:20Z"
}
],
"number": 6372,
"title": "Component disappears on first re-render"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\n**Other information:**\r\nfix #6372 .",
"number": 6380,
"review_comments": [],
"title": "fix #6372: should re-create nested components in slot when re-rendering container"
} | {
"commits": [
{
"message": "[release] weex-vue-framework@2.4.2-weex.1 (#6196)\n\n* build(release weex): ignore the file path of entries\r\n\r\n* [release] weex-vue-framework@2.4.2-weex.1"
},
{
"message": "fix-Firefox (#6359)"
},
{
"message": "fix:should re-create nested components in slot when rerendering container"
}
],
"files": [
{
"diff": "@@ -31,7 +31,6 @@ if [[ $REPLY =~ ^[Yy]$ ]]; then\n cd -\n \n # commit\n- git add src/entries/weex*\n git add packages/weex*\n git commit -m \"[release] weex-vue-framework@$NEXT_VERSION\"\n fi",
"filename": "build/release-weex.sh",
"status": "modified"
},
{
"diff": "@@ -2,7 +2,9 @@\n \n Object.defineProperty(exports, '__esModule', { value: true });\n \n-var he = require('he');\n+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n+\n+var he = _interopDefault(require('he'));\n \n /* */\n \n@@ -14,6 +16,8 @@ var he = require('he');\n \n \n \n+\n+\n /**\n * Check if value is primitive\n */\n@@ -24,15 +28,29 @@ var he = require('he');\n * Objects from primitive values when we know the value\n * is a JSON-compliant type.\n */\n+function isObject (obj) {\n+ return obj !== null && typeof obj === 'object'\n+}\n \n+var _toString = Object.prototype.toString;\n \n /**\n * Strict object type check. Only returns true\n * for plain JavaScript objects.\n */\n+function isPlainObject (obj) {\n+ return _toString.call(obj) === '[object Object]'\n+}\n \n \n \n+/**\n+ * Check if val is a valid array index.\n+ */\n+function isValidArrayIndex (val) {\n+ var n = parseFloat(val);\n+ return n >= 0 && Math.floor(n) === n && isFinite(val)\n+}\n \n /**\n * Convert a value to a string that is actually rendered.\n@@ -69,11 +87,29 @@ function makeMap (\n var isBuiltInTag = makeMap('slot,component', true);\n \n /**\n- * Remove an item from an array\n+ * Check if a attribute is a reserved attribute.\n */\n+var isReservedAttribute = makeMap('key,ref,slot,is');\n \n+/**\n+ * Remove an item from an array\n+ */\n+function remove (arr, item) {\n+ if (arr.length) {\n+ var index = arr.indexOf(item);\n+ if (index > -1) {\n+ return arr.splice(index, 1)\n+ }\n+ }\n+}\n \n-\n+/**\n+ * Check whether the object has the property.\n+ */\n+var hasOwnProperty = Object.prototype.hasOwnProperty;\n+function hasOwn (obj, key) {\n+ return hasOwnProperty.call(obj, key)\n+}\n \n /**\n * Create a cached version of a pure function.\n@@ -128,13 +164,15 @@ function extend (to, _from) {\n \n /**\n * Perform no operation.\n+ * Stubbing args to make Flow happy without leaving useless transpiled code\n+ * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/)\n */\n-function noop () {}\n+function noop (a, b, c) {}\n \n /**\n * Always return false.\n */\n-var no = function () { return false; };\n+var no = function (a, b, c) { return false; };\n \n /**\n * Return same value\n@@ -243,6 +281,10 @@ var decodingMap = {\n var encodedAttr = /&(?:lt|gt|quot|amp);/g;\n var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g;\n \n+// #5992\n+var isIgnoreNewlineTag = makeMap('pre,textarea', true);\n+var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\\n'; };\n+\n function decodeAttr (value, shouldDecodeNewlines) {\n var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr;\n return value.replace(re, function (match) { return decodingMap[match]; })\n@@ -266,6 +308,9 @@ function parseHTML (html, options) {\n var commentEnd = html.indexOf('-->');\n \n if (commentEnd >= 0) {\n+ if (options.shouldKeepComment) {\n+ options.comment(html.substring(4, commentEnd));\n+ }\n advance(commentEnd + 3);\n continue\n }\n@@ -301,24 +346,27 @@ function parseHTML (html, options) {\n var startTagMatch = parseStartTag();\n if (startTagMatch) {\n handleStartTag(startTagMatch);\n+ if (shouldIgnoreFirstNewline(lastTag, html)) {\n+ advance(1);\n+ }\n continue\n }\n }\n \n- var text = (void 0), rest$1 = (void 0), next = (void 0);\n+ var text = (void 0), rest = (void 0), next = (void 0);\n if (textEnd >= 0) {\n- rest$1 = html.slice(textEnd);\n+ rest = html.slice(textEnd);\n while (\n- !endTag.test(rest$1) &&\n- !startTagOpen.test(rest$1) &&\n- !comment.test(rest$1) &&\n- !conditionalComment.test(rest$1)\n+ !endTag.test(rest) &&\n+ !startTagOpen.test(rest) &&\n+ !comment.test(rest) &&\n+ !conditionalComment.test(rest)\n ) {\n // < in plain text, be forgiving and treat it as text\n- next = rest$1.indexOf('<', 1);\n+ next = rest.indexOf('<', 1);\n if (next < 0) { break }\n textEnd += next;\n- rest$1 = html.slice(textEnd);\n+ rest = html.slice(textEnd);\n }\n text = html.substring(0, textEnd);\n advance(textEnd);\n@@ -333,23 +381,26 @@ function parseHTML (html, options) {\n options.chars(text);\n }\n } else {\n+ var endTagLength = 0;\n var stackedTag = lastTag.toLowerCase();\n var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\\\s\\\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));\n- var endTagLength = 0;\n- var rest = html.replace(reStackedTag, function (all, text, endTag) {\n+ var rest$1 = html.replace(reStackedTag, function (all, text, endTag) {\n endTagLength = endTag.length;\n if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {\n text = text\n .replace(/<!--([\\s\\S]*?)-->/g, '$1')\n .replace(/<!\\[CDATA\\[([\\s\\S]*?)]]>/g, '$1');\n }\n+ if (shouldIgnoreFirstNewline(stackedTag, text)) {\n+ text = text.slice(1);\n+ }\n if (options.chars) {\n options.chars(text);\n }\n return ''\n });\n- index += html.length - rest.length;\n- html = rest;\n+ index += html.length - rest$1.length;\n+ html = rest$1;\n parseEndTag(stackedTag, index - endTagLength, index);\n }\n \n@@ -406,7 +457,7 @@ function parseHTML (html, options) {\n }\n }\n \n- var unary = isUnaryTag$$1(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash;\n+ var unary = isUnaryTag$$1(tagName) || !!unarySlash;\n \n var l = match.attrs.length;\n var attrs = new Array(l);\n@@ -463,8 +514,9 @@ function parseHTML (html, options) {\n // Close all the open elements, up the stack\n for (var i = stack.length - 1; i >= pos; i--) {\n if (process.env.NODE_ENV !== 'production' &&\n- (i > pos || !tagName) &&\n- options.warn) {\n+ (i > pos || !tagName) &&\n+ options.warn\n+ ) {\n options.warn(\n (\"tag <\" + (stack[i].tag) + \"> has no matching end tag.\")\n );\n@@ -674,10 +726,7 @@ function genAssignmentCode (\n if (modelRs.idx === null) {\n return (value + \"=\" + assignment)\n } else {\n- return \"var $$exp = \" + (modelRs.exp) + \", $$idx = \" + (modelRs.idx) + \";\" +\n- \"if (!Array.isArray($$exp)){\" +\n- value + \"=\" + assignment + \"}\" +\n- \"else{$$exp.splice($$idx, 1, \" + assignment + \")}\"\n+ return (\"$set(\" + (modelRs.exp) + \", \" + (modelRs.idx) + \", \" + assignment + \")\")\n }\n }\n \n@@ -770,6 +819,12 @@ function parseString (chr) {\n }\n }\n \n+var ASSET_TYPES = [\n+ 'component',\n+ 'directive',\n+ 'filter'\n+];\n+\n var LIFECYCLE_HOOKS = [\n 'beforeCreate',\n 'created',\n@@ -816,6 +871,11 @@ var config = ({\n */\n errorHandler: null,\n \n+ /**\n+ * Warn handler for watcher warns\n+ */\n+ warnHandler: null,\n+\n /**\n * Ignore certain custom elements\n */\n@@ -866,9 +926,11 @@ var config = ({\n _lifecycleHooks: LIFECYCLE_HOOKS\n });\n \n+/* */\n+\n var warn$1 = noop;\n var tip = noop;\n-var formatComponentName;\n+var formatComponentName = (null); // work around flow check\n \n if (process.env.NODE_ENV !== 'production') {\n var hasConsole = typeof console !== 'undefined';\n@@ -878,10 +940,12 @@ if (process.env.NODE_ENV !== 'production') {\n .replace(/[-_]/g, ''); };\n \n warn$1 = function (msg, vm) {\n- if (hasConsole && (!config.silent)) {\n- console.error(\"[Vue warn]: \" + msg + (\n- vm ? generateComponentTrace(vm) : ''\n- ));\n+ var trace = vm ? generateComponentTrace(vm) : '';\n+\n+ if (config.warnHandler) {\n+ config.warnHandler.call(null, msg, vm, trace);\n+ } else if (hasConsole && (!config.silent)) {\n+ console.error((\"[Vue warn]: \" + msg + trace));\n }\n };\n \n@@ -957,6 +1021,8 @@ if (process.env.NODE_ENV !== 'production') {\n };\n }\n \n+/* */\n+\n function handleError (err, vm, info) {\n if (config.errorHandler) {\n config.errorHandler.call(null, err, vm, info);\n@@ -977,7 +1043,7 @@ function handleError (err, vm, info) {\n /* globals MutationObserver */\n \n // can we use __proto__?\n-\n+var hasProto = '__proto__' in {};\n \n // Browser environment sniffing\n var inBrowser = typeof window !== 'undefined';\n@@ -989,6 +1055,9 @@ var isAndroid = UA && UA.indexOf('android') > 0;\n var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);\n var isChrome = UA && /chrome\\/\\d+/.test(UA) && !isEdge;\n \n+// Firefix has a \"watch\" function on Object.prototype...\n+var nativeWatch = ({}).watch;\n+\n var supportsPassive = false;\n if (inBrowser) {\n try {\n@@ -998,7 +1067,7 @@ if (inBrowser) {\n /* istanbul ignore next */\n supportsPassive = true;\n }\n- } )); // https://github.com/facebook/flow/issues/285\n+ })); // https://github.com/facebook/flow/issues/285\n window.addEventListener('test-passive', null, opts);\n } catch (e) {}\n }\n@@ -1292,12 +1361,15 @@ function parse (\n options\n ) {\n warn = options.warn || baseWarn;\n- platformGetTagNamespace = options.getTagNamespace || no;\n- platformMustUseProp = options.mustUseProp || no;\n+\n platformIsPreTag = options.isPreTag || no;\n- preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');\n+ platformMustUseProp = options.mustUseProp || no;\n+ platformGetTagNamespace = options.getTagNamespace || no;\n+\n transforms = pluckModuleFunction(options.modules, 'transformNode');\n+ preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');\n postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');\n+\n delimiters = options.delimiters;\n \n var stack = [];\n@@ -1331,6 +1403,7 @@ function parse (\n isUnaryTag: options.isUnaryTag,\n canBeLeftOpenTag: options.canBeLeftOpenTag,\n shouldDecodeNewlines: options.shouldDecodeNewlines,\n+ shouldKeepComment: options.comments,\n start: function start (tag, attrs, unary) {\n // check namespace.\n // inherit parent ns if there is one\n@@ -1489,8 +1562,9 @@ function parse (\n // IE textarea placeholder bug\n /* istanbul ignore if */\n if (isIE &&\n- currentParent.tag === 'textarea' &&\n- currentParent.attrsMap.placeholder === text) {\n+ currentParent.tag === 'textarea' &&\n+ currentParent.attrsMap.placeholder === text\n+ ) {\n return\n }\n var children = currentParent.children;\n@@ -1513,6 +1587,13 @@ function parse (\n });\n }\n }\n+ },\n+ comment: function comment (text) {\n+ currentParent.children.push({\n+ type: 3,\n+ text: text,\n+ isComment: true\n+ });\n }\n });\n return root\n@@ -1714,7 +1795,9 @@ function processAttrs (el) {\n );\n }\n }\n- if (isProp || platformMustUseProp(el.tag, el.attrsMap.type, name)) {\n+ if (isProp || (\n+ !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name)\n+ )) {\n addProp(el, name, value);\n } else {\n addAttr(el, name, value);\n@@ -1889,6 +1972,15 @@ function markStatic (node) {\n node.static = false;\n }\n }\n+ if (node.ifConditions) {\n+ for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) {\n+ var block = node.ifConditions[i$1].block;\n+ markStatic(block);\n+ if (!block.static) {\n+ node.static = false;\n+ }\n+ }\n+ }\n }\n }\n \n@@ -1915,17 +2007,13 @@ function markStaticRoots (node, isInFor) {\n }\n }\n if (node.ifConditions) {\n- walkThroughConditionsBlocks(node.ifConditions, isInFor);\n+ for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) {\n+ markStaticRoots(node.ifConditions[i$1].block, isInFor);\n+ }\n }\n }\n }\n \n-function walkThroughConditionsBlocks (conditionBlocks, isInFor) {\n- for (var i = 1, len = conditionBlocks.length; i < len; i++) {\n- markStaticRoots(conditionBlocks[i].block, isInFor);\n- }\n-}\n-\n function isStatic (node) {\n if (node.type === 2) { // expression\n return false\n@@ -1994,17 +2082,17 @@ var modifierCode = {\n \n function genHandlers (\n events,\n- native,\n+ isNative,\n warn\n ) {\n- var res = native ? 'nativeOn:{' : 'on:{';\n+ var res = isNative ? 'nativeOn:{' : 'on:{';\n for (var name in events) {\n var handler = events[name];\n // #5330: warn click.right, since right clicks do not actually fire click events.\n if (process.env.NODE_ENV !== 'production' &&\n- name === 'click' &&\n- handler && handler.modifiers && handler.modifiers.right\n- ) {\n+ name === 'click' &&\n+ handler && handler.modifiers && handler.modifiers.right\n+ ) {\n warn(\n \"Use \\\"contextmenu\\\" instead of \\\"click.right\\\" since right clicks \" +\n \"do not actually fire \\\"click\\\" events.\"\n@@ -2080,99 +2168,639 @@ function genFilterCode (key) {\n \n /* */\n \n+var emptyObject = Object.freeze({});\n+\n+/**\n+ * Check if a string starts with $ or _\n+ */\n+\n+\n+/**\n+ * Define a property.\n+ */\n+function def (obj, key, val, enumerable) {\n+ Object.defineProperty(obj, key, {\n+ value: val,\n+ enumerable: !!enumerable,\n+ writable: true,\n+ configurable: true\n+ });\n+}\n+\n+/* */\n+\n+\n+var uid = 0;\n+\n+/**\n+ * A dep is an observable that can have multiple\n+ * directives subscribing to it.\n+ */\n+var Dep = function Dep () {\n+ this.id = uid++;\n+ this.subs = [];\n+};\n+\n+Dep.prototype.addSub = function addSub (sub) {\n+ this.subs.push(sub);\n+};\n+\n+Dep.prototype.removeSub = function removeSub (sub) {\n+ remove(this.subs, sub);\n+};\n+\n+Dep.prototype.depend = function depend () {\n+ if (Dep.target) {\n+ Dep.target.addDep(this);\n+ }\n+};\n+\n+Dep.prototype.notify = function notify () {\n+ // stabilize the subscriber list first\n+ var subs = this.subs.slice();\n+ for (var i = 0, l = subs.length; i < l; i++) {\n+ subs[i].update();\n+ }\n+};\n+\n+// the current target watcher being evaluated.\n+// this is globally unique because there could be only one\n+// watcher being evaluated at any time.\n+Dep.target = null;\n+\n+/*\n+ * not type checking this file because flow doesn't play well with\n+ * dynamically accessing methods on Array prototype\n+ */\n+\n+var arrayProto = Array.prototype;\n+var arrayMethods = Object.create(arrayProto);[\n+ 'push',\n+ 'pop',\n+ 'shift',\n+ 'unshift',\n+ 'splice',\n+ 'sort',\n+ 'reverse'\n+]\n+.forEach(function (method) {\n+ // cache original method\n+ var original = arrayProto[method];\n+ def(arrayMethods, method, function mutator () {\n+ var args = [], len = arguments.length;\n+ while ( len-- ) args[ len ] = arguments[ len ];\n+\n+ var result = original.apply(this, args);\n+ var ob = this.__ob__;\n+ var inserted;\n+ switch (method) {\n+ case 'push':\n+ case 'unshift':\n+ inserted = args;\n+ break\n+ case 'splice':\n+ inserted = args.slice(2);\n+ break\n+ }\n+ if (inserted) { ob.observeArray(inserted); }\n+ // notify change\n+ ob.dep.notify();\n+ return result\n+ });\n+});\n+\n+/* */\n+\n+var arrayKeys = Object.getOwnPropertyNames(arrayMethods);\n+\n+/**\n+ * By default, when a reactive property is set, the new value is\n+ * also converted to become reactive. However when passing down props,\n+ * we don't want to force conversion because the value may be a nested value\n+ * under a frozen data structure. Converting it would defeat the optimization.\n+ */\n+var observerState = {\n+ shouldConvert: true\n+};\n+\n+/**\n+ * Observer class that are attached to each observed\n+ * object. Once attached, the observer converts target\n+ * object's property keys into getter/setters that\n+ * collect dependencies and dispatches updates.\n+ */\n+var Observer = function Observer (value) {\n+ this.value = value;\n+ this.dep = new Dep();\n+ this.vmCount = 0;\n+ def(value, '__ob__', this);\n+ if (Array.isArray(value)) {\n+ var augment = hasProto\n+ ? protoAugment\n+ : copyAugment;\n+ augment(value, arrayMethods, arrayKeys);\n+ this.observeArray(value);\n+ } else {\n+ this.walk(value);\n+ }\n+};\n+\n+/**\n+ * Walk through each property and convert them into\n+ * getter/setters. This method should only be called when\n+ * value type is Object.\n+ */\n+Observer.prototype.walk = function walk (obj) {\n+ var keys = Object.keys(obj);\n+ for (var i = 0; i < keys.length; i++) {\n+ defineReactive$$1(obj, keys[i], obj[keys[i]]);\n+ }\n+};\n+\n+/**\n+ * Observe a list of Array items.\n+ */\n+Observer.prototype.observeArray = function observeArray (items) {\n+ for (var i = 0, l = items.length; i < l; i++) {\n+ observe(items[i]);\n+ }\n+};\n+\n+// helpers\n+\n+/**\n+ * Augment an target Object or Array by intercepting\n+ * the prototype chain using __proto__\n+ */\n+function protoAugment (target, src, keys) {\n+ /* eslint-disable no-proto */\n+ target.__proto__ = src;\n+ /* eslint-enable no-proto */\n+}\n+\n+/**\n+ * Augment an target Object or Array by defining\n+ * hidden properties.\n+ */\n+/* istanbul ignore next */\n+function copyAugment (target, src, keys) {\n+ for (var i = 0, l = keys.length; i < l; i++) {\n+ var key = keys[i];\n+ def(target, key, src[key]);\n+ }\n+}\n+\n+/**\n+ * Attempt to create an observer instance for a value,\n+ * returns the new observer if successfully observed,\n+ * or the existing observer if the value already has one.\n+ */\n+function observe (value, asRootData) {\n+ if (!isObject(value)) {\n+ return\n+ }\n+ var ob;\n+ if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {\n+ ob = value.__ob__;\n+ } else if (\n+ observerState.shouldConvert &&\n+ !isServerRendering() &&\n+ (Array.isArray(value) || isPlainObject(value)) &&\n+ Object.isExtensible(value) &&\n+ !value._isVue\n+ ) {\n+ ob = new Observer(value);\n+ }\n+ if (asRootData && ob) {\n+ ob.vmCount++;\n+ }\n+ return ob\n+}\n+\n+/**\n+ * Define a reactive property on an Object.\n+ */\n+function defineReactive$$1 (\n+ obj,\n+ key,\n+ val,\n+ customSetter,\n+ shallow\n+) {\n+ var dep = new Dep();\n+\n+ var property = Object.getOwnPropertyDescriptor(obj, key);\n+ if (property && property.configurable === false) {\n+ return\n+ }\n+\n+ // cater for pre-defined getter/setters\n+ var getter = property && property.get;\n+ var setter = property && property.set;\n+\n+ var childOb = !shallow && observe(val);\n+ Object.defineProperty(obj, key, {\n+ enumerable: true,\n+ configurable: true,\n+ get: function reactiveGetter () {\n+ var value = getter ? getter.call(obj) : val;\n+ if (Dep.target) {\n+ dep.depend();\n+ if (childOb) {\n+ childOb.dep.depend();\n+ }\n+ if (Array.isArray(value)) {\n+ dependArray(value);\n+ }\n+ }\n+ return value\n+ },\n+ set: function reactiveSetter (newVal) {\n+ var value = getter ? getter.call(obj) : val;\n+ /* eslint-disable no-self-compare */\n+ if (newVal === value || (newVal !== newVal && value !== value)) {\n+ return\n+ }\n+ /* eslint-enable no-self-compare */\n+ if (process.env.NODE_ENV !== 'production' && customSetter) {\n+ customSetter();\n+ }\n+ if (setter) {\n+ setter.call(obj, newVal);\n+ } else {\n+ val = newVal;\n+ }\n+ childOb = !shallow && observe(newVal);\n+ dep.notify();\n+ }\n+ });\n+}\n+\n+/**\n+ * Set a property on an object. Adds the new property and\n+ * triggers change notification if the property doesn't\n+ * already exist.\n+ */\n+function set (target, key, val) {\n+ if (Array.isArray(target) && isValidArrayIndex(key)) {\n+ target.length = Math.max(target.length, key);\n+ target.splice(key, 1, val);\n+ return val\n+ }\n+ if (hasOwn(target, key)) {\n+ target[key] = val;\n+ return val\n+ }\n+ var ob = (target).__ob__;\n+ if (target._isVue || (ob && ob.vmCount)) {\n+ process.env.NODE_ENV !== 'production' && warn$1(\n+ 'Avoid adding reactive properties to a Vue instance or its root $data ' +\n+ 'at runtime - declare it upfront in the data option.'\n+ );\n+ return val\n+ }\n+ if (!ob) {\n+ target[key] = val;\n+ return val\n+ }\n+ defineReactive$$1(ob.value, key, val);\n+ ob.dep.notify();\n+ return val\n+}\n+\n+/**\n+ * Delete a property and trigger change if necessary.\n+ */\n+\n+\n+/**\n+ * Collect dependencies on array elements when the array is touched, since\n+ * we cannot intercept array element access like property getters.\n+ */\n+function dependArray (value) {\n+ for (var e = (void 0), i = 0, l = value.length; i < l; i++) {\n+ e = value[i];\n+ e && e.__ob__ && e.__ob__.dep.depend();\n+ if (Array.isArray(e)) {\n+ dependArray(e);\n+ }\n+ }\n+}\n+\n+/* */\n+\n+/**\n+ * Option overwriting strategies are functions that handle\n+ * how to merge a parent option value and a child option\n+ * value into the final value.\n+ */\n+var strats = config.optionMergeStrategies;\n+\n+/**\n+ * Options with restrictions\n+ */\n+if (process.env.NODE_ENV !== 'production') {\n+ strats.el = strats.propsData = function (parent, child, vm, key) {\n+ if (!vm) {\n+ warn$1(\n+ \"option \\\"\" + key + \"\\\" can only be used during instance \" +\n+ 'creation with the `new` keyword.'\n+ );\n+ }\n+ return defaultStrat(parent, child)\n+ };\n+}\n+\n+/**\n+ * Helper that recursively merges two data objects together.\n+ */\n+function mergeData (to, from) {\n+ if (!from) { return to }\n+ var key, toVal, fromVal;\n+ var keys = Object.keys(from);\n+ for (var i = 0; i < keys.length; i++) {\n+ key = keys[i];\n+ toVal = to[key];\n+ fromVal = from[key];\n+ if (!hasOwn(to, key)) {\n+ set(to, key, fromVal);\n+ } else if (isPlainObject(toVal) && isPlainObject(fromVal)) {\n+ mergeData(toVal, fromVal);\n+ }\n+ }\n+ return to\n+}\n+\n+/**\n+ * Data\n+ */\n+function mergeDataOrFn (\n+ parentVal,\n+ childVal,\n+ vm\n+) {\n+ if (!vm) {\n+ // in a Vue.extend merge, both should be functions\n+ if (!childVal) {\n+ return parentVal\n+ }\n+ if (!parentVal) {\n+ return childVal\n+ }\n+ // when parentVal & childVal are both present,\n+ // we need to return a function that returns the\n+ // merged result of both functions... no need to\n+ // check if parentVal is a function here because\n+ // it has to be a function to pass previous merges.\n+ return function mergedDataFn () {\n+ return mergeData(\n+ typeof childVal === 'function' ? childVal.call(this) : childVal,\n+ typeof parentVal === 'function' ? parentVal.call(this) : parentVal\n+ )\n+ }\n+ } else if (parentVal || childVal) {\n+ return function mergedInstanceDataFn () {\n+ // instance merge\n+ var instanceData = typeof childVal === 'function'\n+ ? childVal.call(vm)\n+ : childVal;\n+ var defaultData = typeof parentVal === 'function'\n+ ? parentVal.call(vm)\n+ : undefined;\n+ if (instanceData) {\n+ return mergeData(instanceData, defaultData)\n+ } else {\n+ return defaultData\n+ }\n+ }\n+ }\n+}\n+\n+strats.data = function (\n+ parentVal,\n+ childVal,\n+ vm\n+) {\n+ if (!vm) {\n+ if (childVal && typeof childVal !== 'function') {\n+ process.env.NODE_ENV !== 'production' && warn$1(\n+ 'The \"data\" option should be a function ' +\n+ 'that returns a per-instance value in component ' +\n+ 'definitions.',\n+ vm\n+ );\n+\n+ return parentVal\n+ }\n+ return mergeDataOrFn.call(this, parentVal, childVal)\n+ }\n+\n+ return mergeDataOrFn(parentVal, childVal, vm)\n+};\n+\n+/**\n+ * Hooks and props are merged as arrays.\n+ */\n+function mergeHook (\n+ parentVal,\n+ childVal\n+) {\n+ return childVal\n+ ? parentVal\n+ ? parentVal.concat(childVal)\n+ : Array.isArray(childVal)\n+ ? childVal\n+ : [childVal]\n+ : parentVal\n+}\n+\n+LIFECYCLE_HOOKS.forEach(function (hook) {\n+ strats[hook] = mergeHook;\n+});\n+\n+/**\n+ * Assets\n+ *\n+ * When a vm is present (instance creation), we need to do\n+ * a three-way merge between constructor options, instance\n+ * options and parent options.\n+ */\n+function mergeAssets (parentVal, childVal) {\n+ var res = Object.create(parentVal || null);\n+ return childVal\n+ ? extend(res, childVal)\n+ : res\n+}\n+\n+ASSET_TYPES.forEach(function (type) {\n+ strats[type + 's'] = mergeAssets;\n+});\n+\n+/**\n+ * Watchers.\n+ *\n+ * Watchers hashes should not overwrite one\n+ * another, so we merge them as arrays.\n+ */\n+strats.watch = function (parentVal, childVal) {\n+ // work around Firefox's Object.prototype.watch...\n+ if (parentVal === nativeWatch) { parentVal = undefined; }\n+ if (childVal === nativeWatch) { childVal = undefined; }\n+ /* istanbul ignore if */\n+ if (!childVal) { return Object.create(parentVal || null) }\n+ if (!parentVal) { return childVal }\n+ var ret = {};\n+ extend(ret, parentVal);\n+ for (var key in childVal) {\n+ var parent = ret[key];\n+ var child = childVal[key];\n+ if (parent && !Array.isArray(parent)) {\n+ parent = [parent];\n+ }\n+ ret[key] = parent\n+ ? parent.concat(child)\n+ : Array.isArray(child) ? child : [child];\n+ }\n+ return ret\n+};\n+\n+/**\n+ * Other object hashes.\n+ */\n+strats.props =\n+strats.methods =\n+strats.inject =\n+strats.computed = function (parentVal, childVal) {\n+ if (!parentVal) { return childVal }\n+ var ret = Object.create(null);\n+ extend(ret, parentVal);\n+ if (childVal) { extend(ret, childVal); }\n+ return ret\n+};\n+strats.provide = mergeDataOrFn;\n+\n+/**\n+ * Default strategy.\n+ */\n+var defaultStrat = function (parentVal, childVal) {\n+ return childVal === undefined\n+ ? parentVal\n+ : childVal\n+};\n+\n+/**\n+ * Merge two option objects into a new one.\n+ * Core utility used in both instantiation and inheritance.\n+ */\n+\n+\n+/**\n+ * Resolve an asset.\n+ * This function is used because child instances need access\n+ * to assets defined in its ancestor chain.\n+ */\n+\n+/* */\n+\n+/* */\n+\n+/* */\n+\n+function on (el, dir) {\n+ if (process.env.NODE_ENV !== 'production' && dir.modifiers) {\n+ warn$1(\"v-on without argument does not support modifiers.\");\n+ }\n+ el.wrapListeners = function (code) { return (\"_g(\" + code + \",\" + (dir.value) + \")\"); };\n+}\n+\n+/* */\n+\n function bind$1 (el, dir) {\n el.wrapData = function (code) {\n- return (\"_b(\" + code + \",'\" + (el.tag) + \"',\" + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + \")\")\n+ return (\"_b(\" + code + \",'\" + (el.tag) + \"',\" + (dir.value) + \",\" + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + \")\")\n };\n }\n \n /* */\n \n var baseDirectives = {\n+ on: on,\n bind: bind$1,\n cloak: noop\n };\n \n /* */\n \n-// configurable state\n-var warn$2;\n-var transforms$1;\n-var dataGenFns;\n-var platformDirectives;\n-var isPlatformReservedTag$1;\n-var staticRenderFns;\n-var onceCount;\n-var currentOptions;\n+var CodegenState = function CodegenState (options) {\n+ this.options = options;\n+ this.warn = options.warn || baseWarn;\n+ this.transforms = pluckModuleFunction(options.modules, 'transformCode');\n+ this.dataGenFns = pluckModuleFunction(options.modules, 'genData');\n+ this.directives = extend(extend({}, baseDirectives), options.directives);\n+ var isReservedTag = options.isReservedTag || no;\n+ this.maybeComponent = function (el) { return !isReservedTag(el.tag); };\n+ this.onceId = 0;\n+ this.staticRenderFns = [];\n+};\n+\n+\n \n function generate (\n ast,\n options\n ) {\n- // save previous staticRenderFns so generate calls can be nested\n- var prevStaticRenderFns = staticRenderFns;\n- var currentStaticRenderFns = staticRenderFns = [];\n- var prevOnceCount = onceCount;\n- onceCount = 0;\n- currentOptions = options;\n- warn$2 = options.warn || baseWarn;\n- transforms$1 = pluckModuleFunction(options.modules, 'transformCode');\n- dataGenFns = pluckModuleFunction(options.modules, 'genData');\n- platformDirectives = options.directives || {};\n- isPlatformReservedTag$1 = options.isReservedTag || no;\n- var code = ast ? genElement(ast) : '_c(\"div\")';\n- staticRenderFns = prevStaticRenderFns;\n- onceCount = prevOnceCount;\n+ var state = new CodegenState(options);\n+ var code = ast ? genElement(ast, state) : '_c(\"div\")';\n return {\n render: (\"with(this){return \" + code + \"}\"),\n- staticRenderFns: currentStaticRenderFns\n+ staticRenderFns: state.staticRenderFns\n }\n }\n \n-function genElement (el) {\n+function genElement (el, state) {\n if (el.staticRoot && !el.staticProcessed) {\n- return genStatic(el)\n+ return genStatic(el, state)\n } else if (el.once && !el.onceProcessed) {\n- return genOnce(el)\n+ return genOnce(el, state)\n } else if (el.for && !el.forProcessed) {\n- return genFor(el)\n+ return genFor(el, state)\n } else if (el.if && !el.ifProcessed) {\n- return genIf(el)\n+ return genIf(el, state)\n } else if (el.tag === 'template' && !el.slotTarget) {\n- return genChildren(el) || 'void 0'\n+ return genChildren(el, state) || 'void 0'\n } else if (el.tag === 'slot') {\n- return genSlot(el)\n+ return genSlot(el, state)\n } else {\n // component or element\n var code;\n if (el.component) {\n- code = genComponent(el.component, el);\n+ code = genComponent(el.component, el, state);\n } else {\n- var data = el.plain ? undefined : genData(el);\n+ var data = el.plain ? undefined : genData(el, state);\n \n- var children = el.inlineTemplate ? null : genChildren(el, true);\n+ var children = el.inlineTemplate ? null : genChildren(el, state, true);\n code = \"_c('\" + (el.tag) + \"'\" + (data ? (\",\" + data) : '') + (children ? (\",\" + children) : '') + \")\";\n }\n // module transforms\n- for (var i = 0; i < transforms$1.length; i++) {\n- code = transforms$1[i](el, code);\n+ for (var i = 0; i < state.transforms.length; i++) {\n+ code = state.transforms[i](el, code);\n }\n return code\n }\n }\n \n // hoist static sub-trees out\n-function genStatic (el) {\n+function genStatic (el, state) {\n el.staticProcessed = true;\n- staticRenderFns.push((\"with(this){return \" + (genElement(el)) + \"}\"));\n- return (\"_m(\" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + \")\")\n+ state.staticRenderFns.push((\"with(this){return \" + (genElement(el, state)) + \"}\"));\n+ return (\"_m(\" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + \")\")\n }\n \n // v-once\n-function genOnce (el) {\n+function genOnce (el, state) {\n el.onceProcessed = true;\n if (el.if && !el.ifProcessed) {\n- return genIf(el)\n+ return genIf(el, state)\n } else if (el.staticInFor) {\n var key = '';\n var parent = el.parent;\n@@ -2184,51 +2812,72 @@ function genOnce (el) {\n parent = parent.parent;\n }\n if (!key) {\n- process.env.NODE_ENV !== 'production' && warn$2(\n+ process.env.NODE_ENV !== 'production' && state.warn(\n \"v-once can only be used inside v-for that is keyed. \"\n );\n- return genElement(el)\n+ return genElement(el, state)\n }\n- return (\"_o(\" + (genElement(el)) + \",\" + (onceCount++) + (key ? (\",\" + key) : \"\") + \")\")\n+ return (\"_o(\" + (genElement(el, state)) + \",\" + (state.onceId++) + (key ? (\",\" + key) : \"\") + \")\")\n } else {\n- return genStatic(el)\n+ return genStatic(el, state)\n }\n }\n \n-function genIf (el) {\n+function genIf (\n+ el,\n+ state,\n+ altGen,\n+ altEmpty\n+) {\n el.ifProcessed = true; // avoid recursion\n- return genIfConditions(el.ifConditions.slice())\n+ return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty)\n }\n \n-function genIfConditions (conditions) {\n+function genIfConditions (\n+ conditions,\n+ state,\n+ altGen,\n+ altEmpty\n+) {\n if (!conditions.length) {\n- return '_e()'\n+ return altEmpty || '_e()'\n }\n \n var condition = conditions.shift();\n if (condition.exp) {\n- return (\"(\" + (condition.exp) + \")?\" + (genTernaryExp(condition.block)) + \":\" + (genIfConditions(conditions)))\n+ return (\"(\" + (condition.exp) + \")?\" + (genTernaryExp(condition.block)) + \":\" + (genIfConditions(conditions, state, altGen, altEmpty)))\n } else {\n return (\"\" + (genTernaryExp(condition.block)))\n }\n \n // v-if with v-once should generate code like (a)?_m(0):_m(1)\n function genTernaryExp (el) {\n- return el.once ? genOnce(el) : genElement(el)\n+ return altGen\n+ ? altGen(el, state)\n+ : el.once\n+ ? genOnce(el, state)\n+ : genElement(el, state)\n }\n }\n \n-function genFor (el) {\n+function genFor (\n+ el,\n+ state,\n+ altGen,\n+ altHelper\n+) {\n var exp = el.for;\n var alias = el.alias;\n var iterator1 = el.iterator1 ? (\",\" + (el.iterator1)) : '';\n var iterator2 = el.iterator2 ? (\",\" + (el.iterator2)) : '';\n \n- if (\n- process.env.NODE_ENV !== 'production' &&\n- maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key\n+ if (process.env.NODE_ENV !== 'production' &&\n+ state.maybeComponent(el) &&\n+ el.tag !== 'slot' &&\n+ el.tag !== 'template' &&\n+ !el.key\n ) {\n- warn$2(\n+ state.warn(\n \"<\" + (el.tag) + \" v-for=\\\"\" + alias + \" in \" + exp + \"\\\">: component lists rendered with \" +\n \"v-for should have explicit keys. \" +\n \"See https://vuejs.org/guide/list.html#key for more info.\",\n@@ -2237,18 +2886,18 @@ function genFor (el) {\n }\n \n el.forProcessed = true; // avoid recursion\n- return \"_l((\" + exp + \"),\" +\n+ return (altHelper || '_l') + \"((\" + exp + \"),\" +\n \"function(\" + alias + iterator1 + iterator2 + \"){\" +\n- \"return \" + (genElement(el)) +\n+ \"return \" + ((altGen || genElement)(el, state)) +\n '})'\n }\n \n-function genData (el) {\n+function genData (el, state) {\n var data = '{';\n \n // directives first.\n // directives may mutate the el's other properties before they are generated.\n- var dirs = genDirectives(el);\n+ var dirs = genDirectives(el, state);\n if (dirs) { data += dirs + ','; }\n \n // key\n@@ -2271,8 +2920,8 @@ function genData (el) {\n data += \"tag:\\\"\" + (el.tag) + \"\\\",\";\n }\n // module data generation functions\n- for (var i = 0; i < dataGenFns.length; i++) {\n- data += dataGenFns[i](el);\n+ for (var i = 0; i < state.dataGenFns.length; i++) {\n+ data += state.dataGenFns[i](el);\n }\n // attributes\n if (el.attrs) {\n@@ -2284,26 +2933,26 @@ function genData (el) {\n }\n // event handlers\n if (el.events) {\n- data += (genHandlers(el.events, false, warn$2)) + \",\";\n+ data += (genHandlers(el.events, false, state.warn)) + \",\";\n }\n if (el.nativeEvents) {\n- data += (genHandlers(el.nativeEvents, true, warn$2)) + \",\";\n+ data += (genHandlers(el.nativeEvents, true, state.warn)) + \",\";\n }\n // slot target\n if (el.slotTarget) {\n data += \"slot:\" + (el.slotTarget) + \",\";\n }\n // scoped slots\n if (el.scopedSlots) {\n- data += (genScopedSlots(el.scopedSlots)) + \",\";\n+ data += (genScopedSlots(el.scopedSlots, state)) + \",\";\n }\n // component v-model\n if (el.model) {\n data += \"model:{value:\" + (el.model.value) + \",callback:\" + (el.model.callback) + \",expression:\" + (el.model.expression) + \"},\";\n }\n // inline-template\n if (el.inlineTemplate) {\n- var inlineTemplate = genInlineTemplate(el);\n+ var inlineTemplate = genInlineTemplate(el, state);\n if (inlineTemplate) {\n data += inlineTemplate + \",\";\n }\n@@ -2313,10 +2962,14 @@ function genData (el) {\n if (el.wrapData) {\n data = el.wrapData(data);\n }\n+ // v-on data wrap\n+ if (el.wrapListeners) {\n+ data = el.wrapListeners(data);\n+ }\n return data\n }\n \n-function genDirectives (el) {\n+function genDirectives (el, state) {\n var dirs = el.directives;\n if (!dirs) { return }\n var res = 'directives:[';\n@@ -2325,11 +2978,11 @@ function genDirectives (el) {\n for (i = 0, l = dirs.length; i < l; i++) {\n dir = dirs[i];\n needRuntime = true;\n- var gen = platformDirectives[dir.name] || baseDirectives[dir.name];\n+ var gen = state.directives[dir.name];\n if (gen) {\n // compile-time directive that manipulates AST.\n // returns true if it also needs a runtime counterpart.\n- needRuntime = !!gen(el, dir, warn$2);\n+ needRuntime = !!gen(el, dir, state.warn);\n }\n if (needRuntime) {\n hasRuntime = true;\n@@ -2341,51 +2994,92 @@ function genDirectives (el) {\n }\n }\n \n-function genInlineTemplate (el) {\n+function genInlineTemplate (el, state) {\n var ast = el.children[0];\n if (process.env.NODE_ENV !== 'production' && (\n el.children.length > 1 || ast.type !== 1\n )) {\n- warn$2('Inline-template components must have exactly one child element.');\n+ state.warn('Inline-template components must have exactly one child element.');\n }\n if (ast.type === 1) {\n- var inlineRenderFns = generate(ast, currentOptions);\n+ var inlineRenderFns = generate(ast, state.options);\n return (\"inlineTemplate:{render:function(){\" + (inlineRenderFns.render) + \"},staticRenderFns:[\" + (inlineRenderFns.staticRenderFns.map(function (code) { return (\"function(){\" + code + \"}\"); }).join(',')) + \"]}\")\n }\n }\n \n-function genScopedSlots (slots) {\n- return (\"scopedSlots:_u([\" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + \"])\")\n+function genScopedSlots (\n+ slots,\n+ state\n+) {\n+ return (\"scopedSlots:_u([\" + (Object.keys(slots).map(function (key) {\n+ return genScopedSlot(key, slots[key], state)\n+ }).join(',')) + \"])\")\n }\n \n-function genScopedSlot (key, el) {\n- return \"[\" + key + \",function(\" + (String(el.attrsMap.scope)) + \"){\" +\n+function genScopedSlot (\n+ key,\n+ el,\n+ state\n+) {\n+ if (el.for && !el.forProcessed) {\n+ return genForScopedSlot(key, el, state)\n+ }\n+ return \"{key:\" + key + \",fn:function(\" + (String(el.attrsMap.scope)) + \"){\" +\n \"return \" + (el.tag === 'template'\n- ? genChildren(el) || 'void 0'\n- : genElement(el)) + \"}]\"\n+ ? genChildren(el, state) || 'void 0'\n+ : genElement(el, state)) + \"}}\"\n }\n \n-function genChildren (el, checkSkip) {\n+function genForScopedSlot (\n+ key,\n+ el,\n+ state\n+) {\n+ var exp = el.for;\n+ var alias = el.alias;\n+ var iterator1 = el.iterator1 ? (\",\" + (el.iterator1)) : '';\n+ var iterator2 = el.iterator2 ? (\",\" + (el.iterator2)) : '';\n+ el.forProcessed = true; // avoid recursion\n+ return \"_l((\" + exp + \"),\" +\n+ \"function(\" + alias + iterator1 + iterator2 + \"){\" +\n+ \"return \" + (genScopedSlot(key, el, state)) +\n+ '})'\n+}\n+\n+function genChildren (\n+ el,\n+ state,\n+ checkSkip,\n+ altGenElement,\n+ altGenNode\n+) {\n var children = el.children;\n if (children.length) {\n var el$1 = children[0];\n // optimize single v-for\n if (children.length === 1 &&\n- el$1.for &&\n- el$1.tag !== 'template' &&\n- el$1.tag !== 'slot') {\n- return genElement(el$1)\n+ el$1.for &&\n+ el$1.tag !== 'template' &&\n+ el$1.tag !== 'slot'\n+ ) {\n+ return (altGenElement || genElement)(el$1, state)\n }\n- var normalizationType = checkSkip ? getNormalizationType(children) : 0;\n- return (\"[\" + (children.map(genNode).join(',')) + \"]\" + (normalizationType ? (\",\" + normalizationType) : ''))\n+ var normalizationType = checkSkip\n+ ? getNormalizationType(children, state.maybeComponent)\n+ : 0;\n+ var gen = altGenNode || genNode;\n+ return (\"[\" + (children.map(function (c) { return gen(c, state); }).join(',')) + \"]\" + (normalizationType ? (\",\" + normalizationType) : ''))\n }\n }\n \n // determine the normalization needed for the children array.\n // 0: no normalization needed\n // 1: simple normalization needed (possible 1-level deep nested array)\n // 2: full normalization needed\n-function getNormalizationType (children) {\n+function getNormalizationType (\n+ children,\n+ maybeComponent\n+) {\n var res = 0;\n for (var i = 0; i < children.length; i++) {\n var el = children[i];\n@@ -2409,13 +3103,11 @@ function needsNormalization (el) {\n return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'\n }\n \n-function maybeComponent (el) {\n- return !isPlatformReservedTag$1(el.tag)\n-}\n-\n-function genNode (node) {\n+function genNode (node, state) {\n if (node.type === 1) {\n- return genElement(node)\n+ return genElement(node, state)\n+ } if (node.type === 3 && node.isComment) {\n+ return genComment(node)\n } else {\n return genText(node)\n }\n@@ -2427,9 +3119,13 @@ function genText (text) {\n : transformSpecialNewlines(JSON.stringify(text.text))) + \")\")\n }\n \n-function genSlot (el) {\n+function genComment (comment) {\n+ return (\"_e(\" + (JSON.stringify(comment.text)) + \")\")\n+}\n+\n+function genSlot (el, state) {\n var slotName = el.slotName || '\"default\"';\n- var children = genChildren(el);\n+ var children = genChildren(el, state);\n var res = \"_t(\" + slotName + (children ? (\",\" + children) : '');\n var attrs = el.attrs && (\"{\" + (el.attrs.map(function (a) { return ((camelize(a.name)) + \":\" + (a.value)); }).join(',')) + \"}\");\n var bind$$1 = el.attrsMap['v-bind'];\n@@ -2446,9 +3142,13 @@ function genSlot (el) {\n }\n \n // componentName is el.component, take it as argument to shun flow's pessimistic refinement\n-function genComponent (componentName, el) {\n- var children = el.inlineTemplate ? null : genChildren(el, true);\n- return (\"_c(\" + componentName + \",\" + (genData(el)) + (children ? (\",\" + children) : '') + \")\")\n+function genComponent (\n+ componentName,\n+ el,\n+ state\n+) {\n+ var children = el.inlineTemplate ? null : genChildren(el, state, true);\n+ return (\"_c(\" + componentName + \",\" + (genData(el, state)) + (children ? (\",\" + children) : '') + \")\")\n }\n \n function genProps (props) {\n@@ -2566,21 +3266,7 @@ function checkExpression (exp, text, errors) {\n \n /* */\n \n-function baseCompile (\n- template,\n- options\n-) {\n- var ast = parse(template.trim(), options);\n- optimize(ast, options);\n- var code = generate(ast, options);\n- return {\n- ast: ast,\n- render: code.render,\n- staticRenderFns: code.staticRenderFns\n- }\n-}\n-\n-function makeFunction (code, errors) {\n+function createFunction (code, errors) {\n try {\n return new Function(code)\n } catch (err) {\n@@ -2589,50 +3275,10 @@ function makeFunction (code, errors) {\n }\n }\n \n-function createCompiler (baseOptions) {\n- var functionCompileCache = Object.create(null);\n-\n- function compile (\n- template,\n- options\n- ) {\n- var finalOptions = Object.create(baseOptions);\n- var errors = [];\n- var tips = [];\n- finalOptions.warn = function (msg, tip$$1) {\n- (tip$$1 ? tips : errors).push(msg);\n- };\n-\n- if (options) {\n- // merge custom modules\n- if (options.modules) {\n- finalOptions.modules = (baseOptions.modules || []).concat(options.modules);\n- }\n- // merge custom directives\n- if (options.directives) {\n- finalOptions.directives = extend(\n- Object.create(baseOptions.directives),\n- options.directives\n- );\n- }\n- // copy other options\n- for (var key in options) {\n- if (key !== 'modules' && key !== 'directives') {\n- finalOptions[key] = options[key];\n- }\n- }\n- }\n-\n- var compiled = baseCompile(template, finalOptions);\n- if (process.env.NODE_ENV !== 'production') {\n- errors.push.apply(errors, detectErrors(compiled.ast));\n- }\n- compiled.errors = errors;\n- compiled.tips = tips;\n- return compiled\n- }\n+function createCompileToFunctionFn (compile) {\n+ var cache = Object.create(null);\n \n- function compileToFunctions (\n+ return function compileToFunctions (\n template,\n options,\n vm\n@@ -2661,8 +3307,8 @@ function createCompiler (baseOptions) {\n var key = options.delimiters\n ? String(options.delimiters) + template\n : template;\n- if (functionCompileCache[key]) {\n- return functionCompileCache[key]\n+ if (cache[key]) {\n+ return cache[key]\n }\n \n // compile\n@@ -2685,12 +3331,10 @@ function createCompiler (baseOptions) {\n // turn code into functions\n var res = {};\n var fnGenErrors = [];\n- res.render = makeFunction(compiled.render, fnGenErrors);\n- var l = compiled.staticRenderFns.length;\n- res.staticRenderFns = new Array(l);\n- for (var i = 0; i < l; i++) {\n- res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i], fnGenErrors);\n- }\n+ res.render = createFunction(compiled.render, fnGenErrors);\n+ res.staticRenderFns = compiled.staticRenderFns.map(function (code) {\n+ return createFunction(code, fnGenErrors)\n+ });\n \n // check function generation errors.\n // this should only happen if there is a bug in the compiler itself.\n@@ -2711,17 +3355,83 @@ function createCompiler (baseOptions) {\n }\n }\n \n- return (functionCompileCache[key] = res)\n+ return (cache[key] = res)\n }\n+}\n \n- return {\n- compile: compile,\n- compileToFunctions: compileToFunctions\n+/* */\n+\n+function createCompilerCreator (baseCompile) {\n+ return function createCompiler (baseOptions) {\n+ function compile (\n+ template,\n+ options\n+ ) {\n+ var finalOptions = Object.create(baseOptions);\n+ var errors = [];\n+ var tips = [];\n+ finalOptions.warn = function (msg, tip) {\n+ (tip ? tips : errors).push(msg);\n+ };\n+\n+ if (options) {\n+ // merge custom modules\n+ if (options.modules) {\n+ finalOptions.modules =\n+ (baseOptions.modules || []).concat(options.modules);\n+ }\n+ // merge custom directives\n+ if (options.directives) {\n+ finalOptions.directives = extend(\n+ Object.create(baseOptions.directives),\n+ options.directives\n+ );\n+ }\n+ // copy other options\n+ for (var key in options) {\n+ if (key !== 'modules' && key !== 'directives') {\n+ finalOptions[key] = options[key];\n+ }\n+ }\n+ }\n+\n+ var compiled = baseCompile(template, finalOptions);\n+ if (process.env.NODE_ENV !== 'production') {\n+ errors.push.apply(errors, detectErrors(compiled.ast));\n+ }\n+ compiled.errors = errors;\n+ compiled.tips = tips;\n+ return compiled\n+ }\n+\n+ return {\n+ compile: compile,\n+ compileToFunctions: createCompileToFunctionFn(compile)\n+ }\n }\n }\n \n /* */\n \n+// `createCompilerCreator` allows creating compilers that use alternative\n+// parser/optimizer/codegen, e.g the SSR optimizing compiler.\n+// Here we just export a default compiler using the default parts.\n+var createCompiler = createCompilerCreator(function baseCompile (\n+ template,\n+ options\n+) {\n+ var ast = parse(template.trim(), options);\n+ optimize(ast, options);\n+ var code = generate(ast, options);\n+ return {\n+ ast: ast,\n+ render: code.render,\n+ staticRenderFns: code.staticRenderFns\n+ }\n+});\n+\n+/* */\n+\n function transformNode (el, options) {\n var warn = options.warn || baseWarn;\n var staticClass = getAndRemoveAttr(el, 'class');\n@@ -2860,7 +3570,7 @@ var style = {\n \n var normalize$1 = cached(camelize);\n \n-function normalizeKeyName (str) {\n+function normalizeKeyName (str) {\n if (str.match(/^v\\-/)) {\n return str.replace(/(v-[a-z\\-]+\\:)([a-z\\-]+)$/i, function ($, directive, prop) {\n return directive + normalize$1(prop)",
"filename": "packages/weex-template-compiler/build.js",
"status": "modified"
},
{
"diff": "@@ -1,6 +1,6 @@\n {\n \"name\": \"weex-template-compiler\",\n- \"version\": \"2.1.9-weex.1\",\n+ \"version\": \"2.4.2-weex.1\",\n \"description\": \"Weex template compiler for Vue 2.0\",\n \"main\": \"index.js\",\n \"repository\": {",
"filename": "packages/weex-template-compiler/package.json",
"status": "modified"
},
{
"diff": "@@ -18,11 +18,19 @@ function isTrue (v) {\n return v === true\n }\n \n+function isFalse (v) {\n+ return v === false\n+}\n+\n /**\n * Check if value is primitive\n */\n function isPrimitive (value) {\n- return typeof value === 'string' || typeof value === 'number'\n+ return (\n+ typeof value === 'string' ||\n+ typeof value === 'number' ||\n+ typeof value === 'boolean'\n+ )\n }\n \n /**\n@@ -34,24 +42,32 @@ function isObject (obj) {\n return obj !== null && typeof obj === 'object'\n }\n \n-var toString = Object.prototype.toString;\n+var _toString = Object.prototype.toString;\n \n /**\n * Strict object type check. Only returns true\n * for plain JavaScript objects.\n */\n function isPlainObject (obj) {\n- return toString.call(obj) === '[object Object]'\n+ return _toString.call(obj) === '[object Object]'\n }\n \n function isRegExp (v) {\n- return toString.call(v) === '[object RegExp]'\n+ return _toString.call(v) === '[object RegExp]'\n+}\n+\n+/**\n+ * Check if val is a valid array index.\n+ */\n+function isValidArrayIndex (val) {\n+ var n = parseFloat(val);\n+ return n >= 0 && Math.floor(n) === n && isFinite(val)\n }\n \n /**\n * Convert a value to a string that is actually rendered.\n */\n-function _toString (val) {\n+function toString (val) {\n return val == null\n ? ''\n : typeof val === 'object'\n@@ -91,6 +107,11 @@ function makeMap (\n */\n var isBuiltInTag = makeMap('slot,component', true);\n \n+/**\n+ * Check if a attribute is a reserved attribute.\n+ */\n+var isReservedAttribute = makeMap('key,ref,slot,is');\n+\n /**\n * Remove an item from an array\n */\n@@ -203,13 +224,15 @@ function toObject (arr) {\n \n /**\n * Perform no operation.\n+ * Stubbing args to make Flow happy without leaving useless transpiled code\n+ * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/)\n */\n-function noop () {}\n+function noop (a, b, c) {}\n \n /**\n * Always return false.\n */\n-var no = function () { return false; };\n+var no = function (a, b, c) { return false; };\n \n /**\n * Return same value\n@@ -226,14 +249,30 @@ var identity = function (_) { return _; };\n * if they are plain objects, do they have the same shape?\n */\n function looseEqual (a, b) {\n+ if (a === b) { return true }\n var isObjectA = isObject(a);\n var isObjectB = isObject(b);\n if (isObjectA && isObjectB) {\n try {\n- return JSON.stringify(a) === JSON.stringify(b)\n+ var isArrayA = Array.isArray(a);\n+ var isArrayB = Array.isArray(b);\n+ if (isArrayA && isArrayB) {\n+ return a.length === b.length && a.every(function (e, i) {\n+ return looseEqual(e, b[i])\n+ })\n+ } else if (!isArrayA && !isArrayB) {\n+ var keysA = Object.keys(a);\n+ var keysB = Object.keys(b);\n+ return keysA.length === keysB.length && keysA.every(function (key) {\n+ return looseEqual(a[key], b[key])\n+ })\n+ } else {\n+ /* istanbul ignore next */\n+ return false\n+ }\n } catch (e) {\n- // possible circular reference\n- return a === b\n+ /* istanbul ignore next */\n+ return false\n }\n } else if (!isObjectA && !isObjectB) {\n return String(a) === String(b)\n@@ -316,6 +355,11 @@ var config = ({\n */\n errorHandler: null,\n \n+ /**\n+ * Warn handler for watcher warns\n+ */\n+ warnHandler: null,\n+\n /**\n * Ignore certain custom elements\n */\n@@ -408,9 +452,11 @@ function parsePath (path) {\n }\n }\n \n+/* */\n+\n var warn = noop;\n var tip = noop;\n-var formatComponentName;\n+var formatComponentName = (null); // work around flow check\n \n if (process.env.NODE_ENV !== 'production') {\n var hasConsole = typeof console !== 'undefined';\n@@ -420,10 +466,12 @@ if (process.env.NODE_ENV !== 'production') {\n .replace(/[-_]/g, ''); };\n \n warn = function (msg, vm) {\n- if (hasConsole && (!config.silent)) {\n- console.error(\"[Vue warn]: \" + msg + (\n- vm ? generateComponentTrace(vm) : ''\n- ));\n+ var trace = vm ? generateComponentTrace(vm) : '';\n+\n+ if (config.warnHandler) {\n+ config.warnHandler.call(null, msg, vm, trace);\n+ } else if (hasConsole && (!config.silent)) {\n+ console.error((\"[Vue warn]: \" + msg + trace));\n }\n };\n \n@@ -499,6 +547,8 @@ if (process.env.NODE_ENV !== 'production') {\n };\n }\n \n+/* */\n+\n function handleError (err, vm, info) {\n if (config.errorHandler) {\n config.errorHandler.call(null, err, vm, info);\n@@ -531,6 +581,9 @@ var isAndroid = UA && UA.indexOf('android') > 0;\n var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);\n var isChrome = UA && /chrome\\/\\d+/.test(UA) && !isEdge;\n \n+// Firefix has a \"watch\" function on Object.prototype...\n+var nativeWatch = ({}).watch;\n+\n var supportsPassive = false;\n if (inBrowser) {\n try {\n@@ -540,7 +593,7 @@ if (inBrowser) {\n /* istanbul ignore next */\n supportsPassive = true;\n }\n- } )); // https://github.com/facebook/flow/issues/285\n+ })); // https://github.com/facebook/flow/issues/285\n window.addEventListener('test-passive', null, opts);\n } catch (e) {}\n }\n@@ -755,22 +808,14 @@ var arrayMethods = Object.create(arrayProto);[\n // cache original method\n var original = arrayProto[method];\n def(arrayMethods, method, function mutator () {\n- var arguments$1 = arguments;\n+ var args = [], len = arguments.length;\n+ while ( len-- ) args[ len ] = arguments[ len ];\n \n- // avoid leaking arguments:\n- // http://jsperf.com/closure-with-arguments\n- var i = arguments.length;\n- var args = new Array(i);\n- while (i--) {\n- args[i] = arguments$1[i];\n- }\n var result = original.apply(this, args);\n var ob = this.__ob__;\n var inserted;\n switch (method) {\n case 'push':\n- inserted = args;\n- break\n case 'unshift':\n inserted = args;\n break\n@@ -796,8 +841,7 @@ var arrayKeys = Object.getOwnPropertyNames(arrayMethods);\n * under a frozen data structure. Converting it would defeat the optimization.\n */\n var observerState = {\n- shouldConvert: true,\n- isSettingProps: false\n+ shouldConvert: true\n };\n \n /**\n@@ -849,7 +893,7 @@ Observer.prototype.observeArray = function observeArray (items) {\n * Augment an target Object or Array by intercepting\n * the prototype chain using __proto__\n */\n-function protoAugment (target, src) {\n+function protoAugment (target, src, keys) {\n /* eslint-disable no-proto */\n target.__proto__ = src;\n /* eslint-enable no-proto */\n@@ -901,7 +945,8 @@ function defineReactive$$1 (\n obj,\n key,\n val,\n- customSetter\n+ customSetter,\n+ shallow\n ) {\n var dep = new Dep();\n \n@@ -914,7 +959,7 @@ function defineReactive$$1 (\n var getter = property && property.get;\n var setter = property && property.set;\n \n- var childOb = observe(val);\n+ var childOb = !shallow && observe(val);\n Object.defineProperty(obj, key, {\n enumerable: true,\n configurable: true,\n@@ -946,7 +991,7 @@ function defineReactive$$1 (\n } else {\n val = newVal;\n }\n- childOb = observe(newVal);\n+ childOb = !shallow && observe(newVal);\n dep.notify();\n }\n });\n@@ -958,7 +1003,7 @@ function defineReactive$$1 (\n * already exist.\n */\n function set (target, key, val) {\n- if (Array.isArray(target) && typeof key === 'number') {\n+ if (Array.isArray(target) && isValidArrayIndex(key)) {\n target.length = Math.max(target.length, key);\n target.splice(key, 1, val);\n return val\n@@ -967,7 +1012,7 @@ function set (target, key, val) {\n target[key] = val;\n return val\n }\n- var ob = (target ).__ob__;\n+ var ob = (target).__ob__;\n if (target._isVue || (ob && ob.vmCount)) {\n process.env.NODE_ENV !== 'production' && warn(\n 'Avoid adding reactive properties to a Vue instance or its root $data ' +\n@@ -988,11 +1033,11 @@ function set (target, key, val) {\n * Delete a property and trigger change if necessary.\n */\n function del (target, key) {\n- if (Array.isArray(target) && typeof key === 'number') {\n+ if (Array.isArray(target) && isValidArrayIndex(key)) {\n target.splice(key, 1);\n return\n }\n- var ob = (target ).__ob__;\n+ var ob = (target).__ob__;\n if (target._isVue || (ob && ob.vmCount)) {\n process.env.NODE_ENV !== 'production' && warn(\n 'Avoid deleting properties on a Vue instance or its root $data ' +\n@@ -1071,7 +1116,7 @@ function mergeData (to, from) {\n /**\n * Data\n */\n-strats.data = function (\n+function mergeDataOrFn (\n parentVal,\n childVal,\n vm\n@@ -1081,15 +1126,6 @@ strats.data = function (\n if (!childVal) {\n return parentVal\n }\n- if (typeof childVal !== 'function') {\n- process.env.NODE_ENV !== 'production' && warn(\n- 'The \"data\" option should be a function ' +\n- 'that returns a per-instance value in component ' +\n- 'definitions.',\n- vm\n- );\n- return parentVal\n- }\n if (!parentVal) {\n return childVal\n }\n@@ -1100,8 +1136,8 @@ strats.data = function (\n // it has to be a function to pass previous merges.\n return function mergedDataFn () {\n return mergeData(\n- childVal.call(this),\n- parentVal.call(this)\n+ typeof childVal === 'function' ? childVal.call(this) : childVal,\n+ typeof parentVal === 'function' ? parentVal.call(this) : parentVal\n )\n }\n } else if (parentVal || childVal) {\n@@ -1120,6 +1156,28 @@ strats.data = function (\n }\n }\n }\n+}\n+\n+strats.data = function (\n+ parentVal,\n+ childVal,\n+ vm\n+) {\n+ if (!vm) {\n+ if (childVal && typeof childVal !== 'function') {\n+ process.env.NODE_ENV !== 'production' && warn(\n+ 'The \"data\" option should be a function ' +\n+ 'that returns a per-instance value in component ' +\n+ 'definitions.',\n+ vm\n+ );\n+\n+ return parentVal\n+ }\n+ return mergeDataOrFn.call(this, parentVal, childVal)\n+ }\n+\n+ return mergeDataOrFn(parentVal, childVal, vm)\n };\n \n /**\n@@ -1167,6 +1225,9 @@ ASSET_TYPES.forEach(function (type) {\n * another, so we merge them as arrays.\n */\n strats.watch = function (parentVal, childVal) {\n+ // work around Firefox's Object.prototype.watch...\n+ if (parentVal === nativeWatch) { parentVal = undefined; }\n+ if (childVal === nativeWatch) { childVal = undefined; }\n /* istanbul ignore if */\n if (!childVal) { return Object.create(parentVal || null) }\n if (!parentVal) { return childVal }\n@@ -1180,7 +1241,7 @@ strats.watch = function (parentVal, childVal) {\n }\n ret[key] = parent\n ? parent.concat(child)\n- : [child];\n+ : Array.isArray(child) ? child : [child];\n }\n return ret\n };\n@@ -1190,14 +1251,15 @@ strats.watch = function (parentVal, childVal) {\n */\n strats.props =\n strats.methods =\n+strats.inject =\n strats.computed = function (parentVal, childVal) {\n- if (!childVal) { return Object.create(parentVal || null) }\n if (!parentVal) { return childVal }\n var ret = Object.create(null);\n extend(ret, parentVal);\n- extend(ret, childVal);\n+ if (childVal) { extend(ret, childVal); }\n return ret\n };\n+strats.provide = mergeDataOrFn;\n \n /**\n * Default strategy.\n@@ -1255,6 +1317,19 @@ function normalizeProps (options) {\n options.props = res;\n }\n \n+/**\n+ * Normalize all injections into Object-based format\n+ */\n+function normalizeInject (options) {\n+ var inject = options.inject;\n+ if (Array.isArray(inject)) {\n+ var normalized = options.inject = {};\n+ for (var i = 0; i < inject.length; i++) {\n+ normalized[inject[i]] = inject[i];\n+ }\n+ }\n+}\n+\n /**\n * Normalize raw function directives into object format.\n */\n@@ -1288,6 +1363,7 @@ function mergeOptions (\n }\n \n normalizeProps(child);\n+ normalizeInject(child);\n normalizeDirectives(child);\n var extendsFrom = child.extends;\n if (extendsFrom) {\n@@ -1405,7 +1481,8 @@ function getPropDefaultValue (vm, prop, key) {\n // return previous default value to avoid unnecessary watcher trigger\n if (vm && vm.$options.propsData &&\n vm.$options.propsData[key] === undefined &&\n- vm._props[key] !== undefined) {\n+ vm._props[key] !== undefined\n+ ) {\n return vm._props[key]\n }\n // call factory function for non-Function types\n@@ -1511,6 +1588,8 @@ function isType (type, fn) {\n return false\n }\n \n+/* */\n+\n /* not type checking this file because flow doesn't play well with Proxy */\n \n var initProxy;\n@@ -1617,7 +1696,8 @@ var VNode = function VNode (\n text,\n elm,\n context,\n- componentOptions\n+ componentOptions,\n+ asyncFactory\n ) {\n this.tag = tag;\n this.data = data;\n@@ -1637,6 +1717,9 @@ var VNode = function VNode (\n this.isComment = false;\n this.isCloned = false;\n this.isOnce = false;\n+ this.asyncFactory = asyncFactory;\n+ this.asyncMeta = undefined;\n+ this.isAsyncPlaceholder = false;\n };\n \n var prototypeAccessors = { child: {} };\n@@ -1649,9 +1732,11 @@ prototypeAccessors.child.get = function () {\n \n Object.defineProperties( VNode.prototype, prototypeAccessors );\n \n-var createEmptyVNode = function () {\n+var createEmptyVNode = function (text) {\n+ if ( text === void 0 ) text = '';\n+\n var node = new VNode();\n- node.text = '';\n+ node.text = text;\n node.isComment = true;\n return node\n };\n@@ -1672,11 +1757,13 @@ function cloneVNode (vnode) {\n vnode.text,\n vnode.elm,\n vnode.context,\n- vnode.componentOptions\n+ vnode.componentOptions,\n+ vnode.asyncFactory\n );\n cloned.ns = vnode.ns;\n cloned.isStatic = vnode.isStatic;\n cloned.key = vnode.key;\n+ cloned.isComment = vnode.isComment;\n cloned.isCloned = true;\n return cloned\n }\n@@ -1713,8 +1800,9 @@ function createFnInvoker (fns) {\n \n var fns = invoker.fns;\n if (Array.isArray(fns)) {\n- for (var i = 0; i < fns.length; i++) {\n- fns[i].apply(null, arguments$1);\n+ var cloned = fns.slice();\n+ for (var i = 0; i < cloned.length; i++) {\n+ cloned[i].apply(null, arguments$1);\n }\n } else {\n // return handler return value for single handlers\n@@ -1895,6 +1983,10 @@ function normalizeChildren (children) {\n : undefined\n }\n \n+function isTextNode (node) {\n+ return isDef(node) && isDef(node.text) && isFalse(node.isComment)\n+}\n+\n function normalizeArrayChildren (children, nestedIndex) {\n var res = [];\n var i, c, last;\n@@ -1906,19 +1998,26 @@ function normalizeArrayChildren (children, nestedIndex) {\n if (Array.isArray(c)) {\n res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + \"_\" + i)));\n } else if (isPrimitive(c)) {\n- if (isDef(last) && isDef(last.text)) {\n+ if (isTextNode(last)) {\n+ // merge adjacent text nodes\n+ // this is necessary for SSR hydration because text nodes are\n+ // essentially merged when rendered to HTML strings\n (last).text += String(c);\n } else if (c !== '') {\n // convert primitive to vnode\n res.push(createTextVNode(c));\n }\n } else {\n- if (isDef(c.text) && isDef(last) && isDef(last.text)) {\n+ if (isTextNode(c) && isTextNode(last)) {\n+ // merge adjacent text nodes\n res[res.length - 1] = createTextVNode(last.text + c.text);\n } else {\n // default key for nested array children (likely generated by v-for)\n- if (isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) {\n- c.key = \"__vlist\" + ((nestedIndex)) + \"_\" + i + \"__\";\n+ if (isTrue(children._isVList) &&\n+ isDef(c.tag) &&\n+ isUndef(c.key) &&\n+ isDef(nestedIndex)) {\n+ c.key = \"__vlist\" + nestedIndex + \"_\" + i + \"__\";\n }\n res.push(c);\n }\n@@ -1930,11 +2029,27 @@ function normalizeArrayChildren (children, nestedIndex) {\n /* */\n \n function ensureCtor (comp, base) {\n+ if (comp.__esModule && comp.default) {\n+ comp = comp.default;\n+ }\n return isObject(comp)\n ? base.extend(comp)\n : comp\n }\n \n+function createAsyncPlaceholder (\n+ factory,\n+ data,\n+ context,\n+ children,\n+ tag\n+) {\n+ var node = createEmptyVNode();\n+ node.asyncFactory = factory;\n+ node.asyncMeta = { data: data, context: context, children: children, tag: tag };\n+ return node\n+}\n+\n function resolveAsyncComponent (\n factory,\n baseCtor,\n@@ -2017,11 +2132,13 @@ function resolveAsyncComponent (\n \n if (isDef(res.timeout)) {\n setTimeout(function () {\n- reject(\n- process.env.NODE_ENV !== 'production'\n- ? (\"timeout (\" + (res.timeout) + \"ms)\")\n- : null\n- );\n+ if (isUndef(factory.resolved)) {\n+ reject(\n+ process.env.NODE_ENV !== 'production'\n+ ? (\"timeout (\" + (res.timeout) + \"ms)\")\n+ : null\n+ );\n+ }\n }, res.timeout);\n }\n }\n@@ -2174,7 +2291,11 @@ function eventsMixin (Vue) {\n cbs = cbs.length > 1 ? toArray(cbs) : cbs;\n var args = toArray(arguments, 1);\n for (var i = 0, l = cbs.length; i < l; i++) {\n- cbs[i].apply(vm, args);\n+ try {\n+ cbs[i].apply(vm, args);\n+ } catch (e) {\n+ handleError(e, vm, (\"event handler for \\\"\" + event + \"\\\"\"));\n+ }\n }\n }\n return vm\n@@ -2200,7 +2321,8 @@ function resolveSlots (\n // named slots should only be respected if the vnode was rendered in the\n // same context.\n if ((child.context === context || child.functionalContext === context) &&\n- child.data && child.data.slot != null) {\n+ child.data && child.data.slot != null\n+ ) {\n var name = child.data.slot;\n var slot = (slots[name] || (slots[name] = []));\n if (child.tag === 'template') {\n@@ -2224,18 +2346,24 @@ function isWhitespace (node) {\n }\n \n function resolveScopedSlots (\n- fns\n+ fns, // see flow/vnode\n+ res\n ) {\n- var res = {};\n+ res = res || {};\n for (var i = 0; i < fns.length; i++) {\n- res[fns[i][0]] = fns[i][1];\n+ if (Array.isArray(fns[i])) {\n+ resolveScopedSlots(fns[i], res);\n+ } else {\n+ res[fns[i].key] = fns[i].fn;\n+ }\n }\n return res\n }\n \n /* */\n \n var activeInstance = null;\n+var isUpdatingChildComponent = false;\n \n function initLifecycle (vm) {\n var options = vm.$options;\n@@ -2283,6 +2411,9 @@ function lifecycleMixin (Vue) {\n vm.$options._parentElm,\n vm.$options._refElm\n );\n+ // no need for the ref nodes after initial patch\n+ // this prevents keeping a detached DOM tree in memory (#5851)\n+ vm.$options._parentElm = vm.$options._refElm = null;\n } else {\n // updates\n vm.$el = vm.__patch__(prevVnode, vnode);\n@@ -2347,8 +2478,6 @@ function lifecycleMixin (Vue) {\n if (vm.$el) {\n vm.$el.__vue__ = null;\n }\n- // remove reference to DOM nodes (prevents leak)\n- vm.$options._parentElm = vm.$options._refElm = null;\n };\n }\n \n@@ -2424,6 +2553,10 @@ function updateChildComponent (\n parentVnode,\n renderChildren\n ) {\n+ if (process.env.NODE_ENV !== 'production') {\n+ isUpdatingChildComponent = true;\n+ }\n+\n // determine whether component has slot children\n // we need to do this before overwriting $options._renderChildren\n var hasChildren = !!(\n@@ -2435,30 +2568,32 @@ function updateChildComponent (\n \n vm.$options._parentVnode = parentVnode;\n vm.$vnode = parentVnode; // update vm's placeholder node without re-render\n+\n if (vm._vnode) { // update child tree's parent\n vm._vnode.parent = parentVnode;\n }\n vm.$options._renderChildren = renderChildren;\n \n+ // update $attrs and $listensers hash\n+ // these are also reactive so they may trigger child update if the child\n+ // used them during render\n+ vm.$attrs = parentVnode.data && parentVnode.data.attrs;\n+ vm.$listeners = listeners;\n+\n // update props\n if (propsData && vm.$options.props) {\n observerState.shouldConvert = false;\n- if (process.env.NODE_ENV !== 'production') {\n- observerState.isSettingProps = true;\n- }\n var props = vm._props;\n var propKeys = vm.$options._propKeys || [];\n for (var i = 0; i < propKeys.length; i++) {\n var key = propKeys[i];\n props[key] = validateProp(key, vm.$options.props, propsData, vm);\n }\n observerState.shouldConvert = true;\n- if (process.env.NODE_ENV !== 'production') {\n- observerState.isSettingProps = false;\n- }\n // keep a copy of raw propsData\n vm.$options.propsData = propsData;\n }\n+\n // update listeners\n if (listeners) {\n var oldListeners = vm.$options._parentListeners;\n@@ -2470,6 +2605,10 @@ function updateChildComponent (\n vm.$slots = resolveSlots(renderChildren, parentVnode.context);\n vm.$forceUpdate();\n }\n+\n+ if (process.env.NODE_ENV !== 'production') {\n+ isUpdatingChildComponent = false;\n+ }\n }\n \n function isInInactiveTree (vm) {\n@@ -2546,7 +2685,7 @@ var index = 0;\n * Reset the scheduler's state.\n */\n function resetSchedulerState () {\n- queue.length = activatedChildren.length = 0;\n+ index = queue.length = activatedChildren.length = 0;\n has = {};\n if (process.env.NODE_ENV !== 'production') {\n circular = {};\n@@ -2603,7 +2742,7 @@ function flushSchedulerQueue () {\n \n // call component updated and activated hooks\n callActivatedHooks(activatedQueue);\n- callUpdateHooks(updatedQueue);\n+ callUpdatedHooks(updatedQueue);\n \n // devtool hook\n /* istanbul ignore if */\n@@ -2612,7 +2751,7 @@ function flushSchedulerQueue () {\n }\n }\n \n-function callUpdateHooks (queue) {\n+function callUpdatedHooks (queue) {\n var i = queue.length;\n while (i--) {\n var watcher = queue[i];\n@@ -2656,10 +2795,10 @@ function queueWatcher (watcher) {\n // if already flushing, splice the watcher based on its id\n // if already past its id, it will be run next immediately.\n var i = queue.length - 1;\n- while (i >= 0 && queue[i].id > watcher.id) {\n+ while (i > index && queue[i].id > watcher.id) {\n i--;\n }\n- queue.splice(Math.max(i, index) + 1, 0, watcher);\n+ queue.splice(i + 1, 0, watcher);\n }\n // queue the flush\n if (!waiting) {\n@@ -2733,22 +2872,23 @@ Watcher.prototype.get = function get () {\n pushTarget(this);\n var value;\n var vm = this.vm;\n- if (this.user) {\n- try {\n- value = this.getter.call(vm, vm);\n- } catch (e) {\n+ try {\n+ value = this.getter.call(vm, vm);\n+ } catch (e) {\n+ if (this.user) {\n handleError(e, vm, (\"getter for watcher \\\"\" + (this.expression) + \"\\\"\"));\n+ } else {\n+ throw e\n }\n- } else {\n- value = this.getter.call(vm, vm);\n- }\n- // \"touch\" every property so they are all tracked as\n- // dependencies for deep watching\n- if (this.deep) {\n- traverse(value);\n+ } finally {\n+ // \"touch\" every property so they are all tracked as\n+ // dependencies for deep watching\n+ if (this.deep) {\n+ traverse(value);\n+ }\n+ popTarget();\n+ this.cleanupDeps();\n }\n- popTarget();\n- this.cleanupDeps();\n return value\n };\n \n@@ -2941,14 +3081,20 @@ function initState (vm) {\n observe(vm._data = {}, true /* asRootData */);\n }\n if (opts.computed) { initComputed(vm, opts.computed); }\n- if (opts.watch) { initWatch(vm, opts.watch); }\n+ if (opts.watch && opts.watch !== nativeWatch) {\n+ initWatch(vm, opts.watch);\n+ }\n }\n \n-var isReservedProp = {\n- key: 1,\n- ref: 1,\n- slot: 1\n-};\n+function checkOptionType (vm, name) {\n+ var option = vm.$options[name];\n+ if (!isPlainObject(option)) {\n+ warn(\n+ (\"component option \\\"\" + name + \"\\\" should be an object.\"),\n+ vm\n+ );\n+ }\n+}\n \n function initProps (vm, propsOptions) {\n var propsData = vm.$options.propsData || {};\n@@ -2964,14 +3110,14 @@ function initProps (vm, propsOptions) {\n var value = validateProp(key, propsOptions, propsData, vm);\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n- if (isReservedProp[key] || config.isReservedAttr(key)) {\n+ if (isReservedAttribute(key) || config.isReservedAttr(key)) {\n warn(\n (\"\\\"\" + key + \"\\\" is a reserved attribute and cannot be used as component prop.\"),\n vm\n );\n }\n defineReactive$$1(props, key, value, function () {\n- if (vm.$parent && !observerState.isSettingProps) {\n+ if (vm.$parent && !isUpdatingChildComponent) {\n warn(\n \"Avoid mutating a prop directly since the value will be \" +\n \"overwritten whenever the parent component re-renders. \" +\n@@ -3012,16 +3158,26 @@ function initData (vm) {\n // proxy data on instance\n var keys = Object.keys(data);\n var props = vm.$options.props;\n+ var methods = vm.$options.methods;\n var i = keys.length;\n while (i--) {\n- if (props && hasOwn(props, keys[i])) {\n+ var key = keys[i];\n+ if (process.env.NODE_ENV !== 'production') {\n+ if (methods && hasOwn(methods, key)) {\n+ warn(\n+ (\"method \\\"\" + key + \"\\\" has already been defined as a data property.\"),\n+ vm\n+ );\n+ }\n+ }\n+ if (props && hasOwn(props, key)) {\n process.env.NODE_ENV !== 'production' && warn(\n- \"The data property \\\"\" + (keys[i]) + \"\\\" is already declared as a prop. \" +\n+ \"The data property \\\"\" + key + \"\\\" is already declared as a prop. \" +\n \"Use prop default value instead.\",\n vm\n );\n- } else if (!isReserved(keys[i])) {\n- proxy(vm, \"_data\", keys[i]);\n+ } else if (!isReserved(key)) {\n+ proxy(vm, \"_data\", key);\n }\n }\n // observe data\n@@ -3040,22 +3196,20 @@ function getData (data, vm) {\n var computedWatcherOptions = { lazy: true };\n \n function initComputed (vm, computed) {\n+ process.env.NODE_ENV !== 'production' && checkOptionType(vm, 'computed');\n var watchers = vm._computedWatchers = Object.create(null);\n \n for (var key in computed) {\n var userDef = computed[key];\n var getter = typeof userDef === 'function' ? userDef : userDef.get;\n- if (process.env.NODE_ENV !== 'production') {\n- if (getter === undefined) {\n- warn(\n- (\"No getter function has been defined for computed property \\\"\" + key + \"\\\".\"),\n- vm\n- );\n- getter = noop;\n- }\n+ if (process.env.NODE_ENV !== 'production' && getter == null) {\n+ warn(\n+ (\"Getter is missing for computed property \\\"\" + key + \"\\\".\"),\n+ vm\n+ );\n }\n // create internal watcher for the computed property.\n- watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions);\n+ watchers[key] = new Watcher(vm, getter || noop, noop, computedWatcherOptions);\n \n // component-defined computed properties are already defined on the\n // component prototype. We only need to define computed properties defined\n@@ -3086,6 +3240,15 @@ function defineComputed (target, key, userDef) {\n ? userDef.set\n : noop;\n }\n+ if (process.env.NODE_ENV !== 'production' &&\n+ sharedPropertyDefinition.set === noop) {\n+ sharedPropertyDefinition.set = function () {\n+ warn(\n+ (\"Computed property \\\"\" + key + \"\\\" was assigned to but it has no setter.\"),\n+ this\n+ );\n+ };\n+ }\n Object.defineProperty(target, key, sharedPropertyDefinition);\n }\n \n@@ -3105,6 +3268,7 @@ function createComputedGetter (key) {\n }\n \n function initMethods (vm, methods) {\n+ process.env.NODE_ENV !== 'production' && checkOptionType(vm, 'methods');\n var props = vm.$options.props;\n for (var key in methods) {\n vm[key] = methods[key] == null ? noop : bind(methods[key], vm);\n@@ -3127,6 +3291,7 @@ function initMethods (vm, methods) {\n }\n \n function initWatch (vm, watch) {\n+ process.env.NODE_ENV !== 'production' && checkOptionType(vm, 'watch');\n for (var key in watch) {\n var handler = watch[key];\n if (Array.isArray(handler)) {\n@@ -3139,16 +3304,20 @@ function initWatch (vm, watch) {\n }\n }\n \n-function createWatcher (vm, key, handler) {\n- var options;\n+function createWatcher (\n+ vm,\n+ keyOrFn,\n+ handler,\n+ options\n+) {\n if (isPlainObject(handler)) {\n options = handler;\n handler = handler.handler;\n }\n if (typeof handler === 'string') {\n handler = vm[handler];\n }\n- vm.$watch(key, handler, options);\n+ return vm.$watch(keyOrFn, handler, options)\n }\n \n function stateMixin (Vue) {\n@@ -3183,6 +3352,9 @@ function stateMixin (Vue) {\n options\n ) {\n var vm = this;\n+ if (isPlainObject(cb)) {\n+ return createWatcher(vm, expOrFn, cb, options)\n+ }\n options = options || {};\n options.user = true;\n var watcher = new Watcher(vm, expOrFn, cb, options);\n@@ -3209,6 +3381,7 @@ function initProvide (vm) {\n function initInjections (vm) {\n var result = resolveInject(vm.$options.inject, vm);\n if (result) {\n+ observerState.shouldConvert = false;\n Object.keys(result).forEach(function (key) {\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n@@ -3224,24 +3397,21 @@ function initInjections (vm) {\n defineReactive$$1(vm, key, result[key]);\n }\n });\n+ observerState.shouldConvert = true;\n }\n }\n \n function resolveInject (inject, vm) {\n if (inject) {\n // inject is :any because flow is not smart enough to figure out cached\n- // isArray here\n- var isArray = Array.isArray(inject);\n var result = Object.create(null);\n- var keys = isArray\n- ? inject\n- : hasSymbol\n+ var keys = hasSymbol\n ? Reflect.ownKeys(inject)\n : Object.keys(inject);\n \n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n- var provideKey = isArray ? key : inject[key];\n+ var provideKey = inject[key];\n var source = vm;\n while (source) {\n if (source._provided && provideKey in source._provided) {\n@@ -3250,6 +3420,9 @@ function resolveInject (inject, vm) {\n }\n source = source.$parent;\n }\n+ if (process.env.NODE_ENV !== 'production' && !source) {\n+ warn((\"Injection \\\"\" + key + \"\\\" not found\"), vm);\n+ }\n }\n return result\n }\n@@ -3268,7 +3441,7 @@ function createFunctionalComponent (\n var propOptions = Ctor.options.props;\n if (isDef(propOptions)) {\n for (var key in propOptions) {\n- props[key] = validateProp(key, propOptions, propsData);\n+ props[key] = validateProp(key, propOptions, propsData || {});\n }\n } else {\n if (isDef(data.attrs)) { mergeProps(props, data.attrs); }\n@@ -3289,6 +3462,7 @@ function createFunctionalComponent (\n });\n if (vnode instanceof VNode) {\n vnode.functionalContext = context;\n+ vnode.functionalOptions = Ctor.options;\n if (data.slot) {\n (vnode.data || (vnode.data = {})).slot = data.slot;\n }\n@@ -3402,21 +3576,30 @@ function createComponent (\n }\n \n // async component\n+ var asyncFactory;\n if (isUndef(Ctor.cid)) {\n- Ctor = resolveAsyncComponent(Ctor, baseCtor, context);\n+ asyncFactory = Ctor;\n+ Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context);\n if (Ctor === undefined) {\n- // return nothing if this is indeed an async component\n- // wait for the callback to trigger parent update.\n- return\n+ // return a placeholder node for async component, which is rendered\n+ // as a comment node but preserves all the raw information for the node.\n+ // the information will be used for async server-rendering and hydration.\n+ return createAsyncPlaceholder(\n+ asyncFactory,\n+ data,\n+ context,\n+ children,\n+ tag\n+ )\n }\n }\n \n+ data = data || {};\n+\n // resolve constructor options in case global mixins are applied after\n // component constructor creation\n resolveConstructorOptions(Ctor);\n \n- data = data || {};\n-\n // transform component v-model data into props & events\n if (isDef(data.model)) {\n transformModel(Ctor.options, data);\n@@ -3434,12 +3617,19 @@ function createComponent (\n // child component listeners instead of DOM listeners\n var listeners = data.on;\n // replace with listeners with .native modifier\n+ // so it gets processed during parent component patch.\n data.on = data.nativeOn;\n \n if (isTrue(Ctor.options.abstract)) {\n // abstract components do not keep anything\n- // other than props & listeners\n+ // other than props & listeners & slot\n+\n+ // work around flow\n+ var slot = data.slot;\n data = {};\n+ if (slot) {\n+ data.slot = slot;\n+ }\n }\n \n // merge component management hooks onto the placeholder node\n@@ -3450,7 +3640,8 @@ function createComponent (\n var vnode = new VNode(\n (\"vue-component-\" + (Ctor.cid) + (name ? (\"-\" + name) : '')),\n data, undefined, undefined, undefined, context,\n- { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }\n+ { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children },\n+ asyncFactory\n );\n return vnode\n }\n@@ -3555,13 +3746,28 @@ function _createElement (\n );\n return createEmptyVNode()\n }\n+ // object syntax in v-bind\n+ if (isDef(data) && isDef(data.is)) {\n+ tag = data.is;\n+ }\n if (!tag) {\n // in case of component :is set to falsy value\n return createEmptyVNode()\n }\n+ // warn against non-primitive key\n+ if (process.env.NODE_ENV !== 'production' &&\n+ isDef(data) && isDef(data.key) && !isPrimitive(data.key)\n+ ) {\n+ warn(\n+ 'Avoid using non-primitive value as key, ' +\n+ 'use string/number value instead.',\n+ context\n+ );\n+ }\n // support single function children as default scoped slot\n if (Array.isArray(children) &&\n- typeof children[0] === 'function') {\n+ typeof children[0] === 'function'\n+ ) {\n data = data || {};\n data.scopedSlots = { default: children[0] };\n children.length = 0;\n@@ -3597,7 +3803,7 @@ function _createElement (\n // direct component options / constructor\n vnode = createComponent(tag, data, context, children);\n }\n- if (vnode !== undefined) {\n+ if (isDef(vnode)) {\n if (ns) { applyNS(vnode, ns); }\n return vnode\n } else {\n@@ -3611,7 +3817,7 @@ function applyNS (vnode, ns) {\n // use default namespace inside foreignObject\n return\n }\n- if (Array.isArray(vnode.children)) {\n+ if (isDef(vnode.children)) {\n for (var i = 0, l = vnode.children.length; i < l; i++) {\n var child = vnode.children[i];\n if (isDef(child.tag) && isUndef(child.ns)) {\n@@ -3649,6 +3855,9 @@ function renderList (\n ret[i] = render(val[key], key, i);\n }\n }\n+ if (isDef(ret)) {\n+ (ret)._isVList = true;\n+ }\n return ret\n }\n \n@@ -3667,7 +3876,7 @@ function renderSlot (\n if (scopedSlotFn) { // scoped slot\n props = props || {};\n if (bindObject) {\n- extend(props, bindObject);\n+ props = extend(extend({}, bindObject), props);\n }\n return scopedSlotFn(props) || fallback\n } else {\n@@ -3721,7 +3930,8 @@ function bindObjectProps (\n data,\n tag,\n value,\n- asProp\n+ asProp,\n+ isSync\n ) {\n if (value) {\n if (!isObject(value)) {\n@@ -3734,8 +3944,12 @@ function bindObjectProps (\n value = toObject(value);\n }\n var hash;\n- for (var key in value) {\n- if (key === 'class' || key === 'style') {\n+ var loop = function ( key ) {\n+ if (\n+ key === 'class' ||\n+ key === 'style' ||\n+ isReservedAttribute(key)\n+ ) {\n hash = data;\n } else {\n var type = data.attrs && data.attrs.type;\n@@ -3745,8 +3959,17 @@ function bindObjectProps (\n }\n if (!(key in hash)) {\n hash[key] = value[key];\n+\n+ if (isSync) {\n+ var on = data.on || (data.on = {});\n+ on[(\"update:\" + key)] = function ($event) {\n+ value[key] = $event;\n+ };\n+ }\n }\n- }\n+ };\n+\n+ for (var key in value) loop( key );\n }\n }\n return data\n@@ -3813,6 +4036,27 @@ function markStaticNode (node, key, isOnce) {\n \n /* */\n \n+function bindObjectListeners (data, value) {\n+ if (value) {\n+ if (!isPlainObject(value)) {\n+ process.env.NODE_ENV !== 'production' && warn(\n+ 'v-on without argument expects an Object value',\n+ this\n+ );\n+ } else {\n+ var on = data.on = data.on ? extend({}, data.on) : {};\n+ for (var key in value) {\n+ var existing = on[key];\n+ var ours = value[key];\n+ on[key] = existing ? [].concat(ours, existing) : ours;\n+ }\n+ }\n+ }\n+ return data\n+}\n+\n+/* */\n+\n function initRender (vm) {\n vm._vnode = null; // the root of the child tree\n vm._staticTrees = null;\n@@ -3828,6 +4072,22 @@ function initRender (vm) {\n // normalization is always applied for the public version, used in\n // user-written render functions.\n vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };\n+\n+ // $attrs & $listeners are exposed for easier HOC creation.\n+ // they need to be reactive so that HOCs using them are always updated\n+ var parentData = parentVnode && parentVnode.data;\n+ /* istanbul ignore else */\n+ if (process.env.NODE_ENV !== 'production') {\n+ defineReactive$$1(vm, '$attrs', parentData && parentData.attrs, function () {\n+ !isUpdatingChildComponent && warn(\"$attrs is readonly.\", vm);\n+ }, true);\n+ defineReactive$$1(vm, '$listeners', vm.$options._parentListeners, function () {\n+ !isUpdatingChildComponent && warn(\"$listeners is readonly.\", vm);\n+ }, true);\n+ } else {\n+ defineReactive$$1(vm, '$attrs', parentData && parentData.attrs, null, true);\n+ defineReactive$$1(vm, '$listeners', vm.$options._parentListeners, null, true);\n+ }\n }\n \n function renderMixin (Vue) {\n@@ -3895,7 +4155,7 @@ function renderMixin (Vue) {\n // code size.\n Vue.prototype._o = markOnce;\n Vue.prototype._n = toNumber;\n- Vue.prototype._s = _toString;\n+ Vue.prototype._s = toString;\n Vue.prototype._l = renderList;\n Vue.prototype._t = renderSlot;\n Vue.prototype._q = looseEqual;\n@@ -3907,6 +4167,7 @@ function renderMixin (Vue) {\n Vue.prototype._v = createTextVNode;\n Vue.prototype._e = createEmptyVNode;\n Vue.prototype._u = resolveScopedSlots;\n+ Vue.prototype._g = bindObjectListeners;\n }\n \n /* */\n@@ -4048,7 +4309,8 @@ function dedupe (latest, extended, sealed) {\n \n function Vue$2 (options) {\n if (process.env.NODE_ENV !== 'production' &&\n- !(this instanceof Vue$2)) {\n+ !(this instanceof Vue$2)\n+ ) {\n warn('Vue is a constructor and should be called with the `new` keyword');\n }\n this._init(options);\n@@ -4064,10 +4326,11 @@ renderMixin(Vue$2);\n \n function initUse (Vue) {\n Vue.use = function (plugin) {\n- /* istanbul ignore if */\n- if (plugin.installed) {\n- return\n+ var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));\n+ if (installedPlugins.indexOf(plugin) > -1) {\n+ return this\n }\n+\n // additional parameters\n var args = toArray(arguments, 1);\n args.unshift(this);\n@@ -4076,7 +4339,7 @@ function initUse (Vue) {\n } else if (typeof plugin === 'function') {\n plugin.apply(null, args);\n }\n- plugin.installed = true;\n+ installedPlugins.push(plugin);\n return this\n };\n }\n@@ -4086,6 +4349,7 @@ function initUse (Vue) {\n function initMixin$1 (Vue) {\n Vue.mixin = function (mixin) {\n this.options = mergeOptions(this.options, mixin);\n+ return this\n };\n }\n \n@@ -4226,14 +4490,16 @@ function initAssetRegisters (Vue) {\n \n /* */\n \n-var patternTypes = [String, RegExp];\n+var patternTypes = [String, RegExp, Array];\n \n function getComponentName (opts) {\n return opts && (opts.Ctor.options.name || opts.tag)\n }\n \n function matches (pattern, name) {\n- if (typeof pattern === 'string') {\n+ if (Array.isArray(pattern)) {\n+ return pattern.indexOf(name) > -1\n+ } else if (typeof pattern === 'string') {\n return pattern.split(',').indexOf(name) > -1\n } else if (isRegExp(pattern)) {\n return pattern.test(name)\n@@ -4377,7 +4643,14 @@ Object.defineProperty(Vue$2.prototype, '$isServer', {\n get: isServerRendering\n });\n \n-Vue$2.version = '2.3.0-beta.1';\n+Object.defineProperty(Vue$2.prototype, '$ssrContext', {\n+ get: function get () {\n+ /* istanbul ignore next */\n+ return this.$vnode && this.$vnode.ssrContext\n+ }\n+});\n+\n+Vue$2.version = '2.4.2';\n \n /* globals renderer */\n // renderer is injected by weex factory wrapper\n@@ -4508,10 +4781,11 @@ function registerRef (vnode, isRemoval) {\n }\n } else {\n if (vnode.data.refInFor) {\n- if (Array.isArray(refs[key]) && refs[key].indexOf(ref) < 0) {\n- refs[key].push(ref);\n- } else {\n+ if (!Array.isArray(refs[key])) {\n refs[key] = [ref];\n+ } else if (refs[key].indexOf(ref) < 0) {\n+ // $flow-disable-line\n+ refs[key].push(ref);\n }\n } else {\n refs[key] = ref;\n@@ -4539,11 +4813,18 @@ var hooks = ['create', 'activate', 'update', 'remove', 'destroy'];\n \n function sameVnode (a, b) {\n return (\n- a.key === b.key &&\n- a.tag === b.tag &&\n- a.isComment === b.isComment &&\n- isDef(a.data) === isDef(b.data) &&\n- sameInputType(a, b)\n+ a.key === b.key && (\n+ (\n+ a.tag === b.tag &&\n+ a.isComment === b.isComment &&\n+ isDef(a.data) === isDef(b.data) &&\n+ sameInputType(a, b)\n+ ) || (\n+ isTrue(a.isAsyncPlaceholder) &&\n+ a.asyncFactory === b.asyncFactory &&\n+ isUndef(b.asyncFactory.error)\n+ )\n+ )\n )\n }\n \n@@ -4696,6 +4977,7 @@ function createPatchFunction (backend) {\n function initComponent (vnode, insertedVnodeQueue) {\n if (isDef(vnode.data.pendingInsert)) {\n insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);\n+ vnode.data.pendingInsert = null;\n }\n vnode.elm = vnode.componentInstance.$el;\n if (isPatchable(vnode)) {\n@@ -4732,11 +5014,11 @@ function createPatchFunction (backend) {\n insert(parentElm, vnode.elm, refElm);\n }\n \n- function insert (parent, elm, ref) {\n+ function insert (parent, elm, ref$$1) {\n if (isDef(parent)) {\n- if (isDef(ref)) {\n- if (ref.parentNode === parent) {\n- nodeOps.insertBefore(parent, elm, ref);\n+ if (isDef(ref$$1)) {\n+ if (ref$$1.parentNode === parent) {\n+ nodeOps.insertBefore(parent, elm, ref$$1);\n }\n } else {\n nodeOps.appendChild(parent, elm);\n@@ -4786,8 +5068,9 @@ function createPatchFunction (backend) {\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n- i !== vnode.context &&\n- isDef(i = i.$options._scopeId)) {\n+ i !== vnode.context &&\n+ isDef(i = i.$options._scopeId)\n+ ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }\n@@ -4912,7 +5195,7 @@ function createPatchFunction (backend) {\n if (sameVnode(elmToMove, newStartVnode)) {\n patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);\n oldCh[idxInOld] = undefined;\n- canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm);\n+ canMove && nodeOps.insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);\n newStartVnode = newCh[++newStartIdx];\n } else {\n // same key but different element. treat as new element\n@@ -4934,24 +5217,37 @@ function createPatchFunction (backend) {\n if (oldVnode === vnode) {\n return\n }\n+\n+ var elm = vnode.elm = oldVnode.elm;\n+\n+ if (isTrue(oldVnode.isAsyncPlaceholder)) {\n+ if (isDef(vnode.asyncFactory.resolved)) {\n+ hydrate(oldVnode.elm, vnode, insertedVnodeQueue);\n+ } else {\n+ vnode.isAsyncPlaceholder = true;\n+ }\n+ return\n+ }\n+\n // reuse element for static trees.\n // note we only do this if the vnode is cloned -\n // if the new node is not cloned it means the render functions have been\n // reset by the hot-reload-api and we need to do a proper re-render.\n if (isTrue(vnode.isStatic) &&\n- isTrue(oldVnode.isStatic) &&\n- vnode.key === oldVnode.key &&\n- (isTrue(vnode.isCloned) || isTrue(vnode.isOnce))) {\n- vnode.elm = oldVnode.elm;\n+ isTrue(oldVnode.isStatic) &&\n+ vnode.key === oldVnode.key &&\n+ (isTrue(vnode.isCloned) || isTrue(vnode.isOnce))\n+ ) {\n vnode.componentInstance = oldVnode.componentInstance;\n return\n }\n+\n var i;\n var data = vnode.data;\n if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {\n i(oldVnode, vnode);\n }\n- var elm = vnode.elm = oldVnode.elm;\n+\n var oldCh = oldVnode.children;\n var ch = vnode.children;\n if (isDef(data) && isPatchable(vnode)) {\n@@ -4996,6 +5292,11 @@ function createPatchFunction (backend) {\n \n // Note: this is a browser-only function so we can assume elms are DOM nodes.\n function hydrate (elm, vnode, insertedVnodeQueue) {\n+ if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) {\n+ vnode.elm = elm;\n+ vnode.isAsyncPlaceholder = true;\n+ return true\n+ }\n if (process.env.NODE_ENV !== 'production') {\n if (!assertNodeMatch(elm, vnode)) {\n return false\n@@ -5032,8 +5333,9 @@ function createPatchFunction (backend) {\n // longer than the virtual children list.\n if (!childrenMatch || childNode) {\n if (process.env.NODE_ENV !== 'production' &&\n- typeof console !== 'undefined' &&\n- !bailed) {\n+ typeof console !== 'undefined' &&\n+ !bailed\n+ ) {\n bailed = true;\n console.warn('Parent: ', elm);\n console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);\n@@ -5313,8 +5615,10 @@ function updateClass (oldVnode, vnode) {\n \n var data = vnode.data;\n var oldData = oldVnode.data;\n- if (!data.staticClass && !data.class &&\n- (!oldData || (!oldData.staticClass && !oldData.class))) {\n+ if (!data.staticClass &&\n+ !data.class &&\n+ (!oldData || (!oldData.staticClass && !oldData.class))\n+ ) {\n return\n }\n \n@@ -5632,9 +5936,10 @@ function enter (_, vnode) {\n var parent = el.parentNode;\n var pendingNode = parent && parent._pending && parent._pending[vnode.key];\n if (pendingNode &&\n- pendingNode.context === vnode.context &&\n- pendingNode.tag === vnode.tag &&\n- pendingNode.elm._leaveCb) {\n+ pendingNode.context === vnode.context &&\n+ pendingNode.tag === vnode.tag &&\n+ pendingNode.elm._leaveCb\n+ ) {\n pendingNode.elm._leaveCb();\n }\n enterHook && enterHook(el, cb);\n@@ -5893,6 +6198,10 @@ function isSameChild (child, oldChild) {\n return oldChild.key === child.key && oldChild.tag === child.tag\n }\n \n+function isAsyncPlaceholder (node) {\n+ return node.isComment && node.asyncFactory\n+}\n+\n var Transition$1 = {\n name: 'transition',\n props: transitionProps,\n@@ -5901,13 +6210,13 @@ var Transition$1 = {\n render: function render (h) {\n var this$1 = this;\n \n- var children = this.$slots.default;\n+ var children = this.$options._renderChildren;\n if (!children) {\n return\n }\n \n // filter out text nodes (possible whitespaces)\n- children = children.filter(function (c) { return c.tag; });\n+ children = children.filter(function (c) { return c.tag || isAsyncPlaceholder(c); });\n /* istanbul ignore if */\n if (!children.length) {\n return\n@@ -5926,7 +6235,8 @@ var Transition$1 = {\n \n // warn invalid mode\n if (process.env.NODE_ENV !== 'production' &&\n- mode && mode !== 'in-out' && mode !== 'out-in') {\n+ mode && mode !== 'in-out' && mode !== 'out-in'\n+ ) {\n warn(\n 'invalid <transition> mode: ' + mode,\n this.$parent\n@@ -5958,7 +6268,9 @@ var Transition$1 = {\n // during entering.\n var id = \"__transition-\" + (this._uid) + \"-\";\n child.key = child.key == null\n- ? id + child.tag\n+ ? child.isComment\n+ ? id + 'comment'\n+ : id + child.tag\n : isPrimitive(child.key)\n ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key)\n : child.key;\n@@ -5973,7 +6285,12 @@ var Transition$1 = {\n child.data.show = true;\n }\n \n- if (oldChild && oldChild.data && !isSameChild(child, oldChild)) {\n+ if (\n+ oldChild &&\n+ oldChild.data &&\n+ !isSameChild(child, oldChild) &&\n+ !isAsyncPlaceholder(oldChild)\n+ ) {\n // replace old child transition data with fresh one\n // important for dynamic transitions!\n var oldData = oldChild && (oldChild.data.transition = extend({}, data));\n@@ -5987,6 +6304,9 @@ var Transition$1 = {\n });\n return placeholder(h, rawChild)\n } else if (mode === 'in-out') {\n+ if (isAsyncPlaceholder(child)) {\n+ return oldRawChild\n+ }\n var delayedLeave;\n var performLeave = function () { delayedLeave(); };\n mergeVNodeHook(data, 'afterEnter', performLeave);",
"filename": "packages/weex-vue-framework/factory.js",
"status": "modified"
},
{
"diff": "@@ -34,7 +34,7 @@ function init (cfg) {\n renderer.Document = cfg.Document;\n renderer.Element = cfg.Element;\n renderer.Comment = cfg.Comment;\n- renderer.sendTasks = cfg.sendTasks;\n+ renderer.compileBundle = cfg.compileBundle;\n }\n \n /**\n@@ -47,7 +47,7 @@ function reset () {\n delete renderer.Document;\n delete renderer.Element;\n delete renderer.Comment;\n- delete renderer.sendTasks;\n+ delete renderer.compileBundle;\n }\n \n /**\n@@ -82,18 +82,9 @@ function createInstance (\n // Virtual-DOM object.\n var document = new renderer.Document(instanceId, config.bundleUrl);\n \n- // All function/callback of parameters before sent to native\n- // will be converted as an id. So `callbacks` is used to store\n- // these real functions. When a callback invoked and won't be\n- // called again, it should be removed from here automatically.\n- var callbacks = [];\n-\n- // The latest callback id, incremental.\n- var callbackId = 1;\n-\n var instance = instances[instanceId] = {\n instanceId: instanceId, config: config, data: data,\n- document: document, callbacks: callbacks, callbackId: callbackId\n+ document: document\n };\n \n // Prepare native module getter and HTML5 Timer APIs.\n@@ -104,6 +95,7 @@ function createInstance (\n var weexInstanceVar = {\n config: config,\n document: document,\n+ supports: supports,\n requireModule: moduleGetter\n };\n Object.freeze(weexInstanceVar);\n@@ -118,11 +110,16 @@ function createInstance (\n weex: weexInstanceVar,\n // deprecated\n __weex_require_module__: weexInstanceVar.requireModule // eslint-disable-line\n- }, timerAPIs);\n- callFunction(instanceVars, appCode);\n+ }, timerAPIs, env.services);\n+\n+ if (!callFunctionNative(instanceVars, appCode)) {\n+ // If failed to compile functionBody on native side,\n+ // fallback to 'callFunction()'.\n+ callFunction(instanceVars, appCode);\n+ }\n \n // Send `createFinish` signal to native.\n- renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'createFinish', args: [] }], -1);\n+ instance.document.taskCenter.send('dom', { action: 'createFinish' }, []);\n }\n \n /**\n@@ -133,6 +130,7 @@ function createInstance (\n function destroyInstance (instanceId) {\n var instance = instances[instanceId];\n if (instance && instance.app instanceof instance.Vue) {\n+ instance.document.destroy();\n instance.app.$destroy();\n }\n delete instances[instanceId];\n@@ -154,7 +152,7 @@ function refreshInstance (instanceId, data) {\n instance.Vue.set(instance.app, key, data[key]);\n }\n // Finally `refreshFinish` signal needed.\n- renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'refreshFinish', args: [] }], -1);\n+ instance.document.taskCenter.send('dom', { action: 'refreshFinish' }, []);\n }\n \n /**\n@@ -169,49 +167,57 @@ function getRoot (instanceId) {\n return instance.app.$el.toJSON()\n }\n \n+var jsHandlers = {\n+ fireEvent: function (id) {\n+ var args = [], len = arguments.length - 1;\n+ while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];\n+\n+ return fireEvent.apply(void 0, [ instances[id] ].concat( args ))\n+ },\n+ callback: function (id) {\n+ var args = [], len = arguments.length - 1;\n+ while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];\n+\n+ return callback.apply(void 0, [ instances[id] ].concat( args ))\n+ }\n+};\n+\n+function fireEvent (instance, nodeId, type, e, domChanges) {\n+ var el = instance.document.getRef(nodeId);\n+ if (el) {\n+ return instance.document.fireEvent(el, type, e, domChanges)\n+ }\n+ return new Error((\"invalid element reference \\\"\" + nodeId + \"\\\"\"))\n+}\n+\n+function callback (instance, callbackId, data, ifKeepAlive) {\n+ var result = instance.document.taskCenter.callback(callbackId, data, ifKeepAlive);\n+ instance.document.taskCenter.send('dom', { action: 'updateFinish' }, []);\n+ return result\n+}\n+\n /**\n- * Receive tasks from native. Generally there are two types of tasks:\n- * 1. `fireEvent`: an device actions or user actions from native.\n- * 2. `callback`: invoke function which sent to native as a parameter before.\n- * @param {string} instanceId\n- * @param {array} tasks\n+ * Accept calls from native (event or callback).\n+ *\n+ * @param {string} id\n+ * @param {array} tasks list with `method` and `args`\n */\n-function receiveTasks (instanceId, tasks) {\n- var instance = instances[instanceId];\n- if (!instance || !(instance.app instanceof instance.Vue)) {\n- return new Error((\"receiveTasks: instance \" + instanceId + \" not found!\"))\n- }\n- var callbacks = instance.callbacks;\n- var document = instance.document;\n- tasks.forEach(function (task) {\n- // `fireEvent` case: find the event target and fire.\n- if (task.method === 'fireEvent') {\n- var ref = task.args;\n- var nodeId = ref[0];\n- var type = ref[1];\n- var e = ref[2];\n- var domChanges = ref[3];\n- var el = document.getRef(nodeId);\n- document.fireEvent(el, type, e, domChanges);\n- }\n- // `callback` case: find the callback by id and call it.\n- if (task.method === 'callback') {\n- var ref$1 = task.args;\n- var callbackId = ref$1[0];\n- var data = ref$1[1];\n- var ifKeepAlive = ref$1[2];\n- var callback = callbacks[callbackId];\n- if (typeof callback === 'function') {\n- callback(data);\n- // Remove the callback from `callbacks` if it won't called again.\n- if (typeof ifKeepAlive === 'undefined' || ifKeepAlive === false) {\n- callbacks[callbackId] = undefined;\n- }\n+function receiveTasks (id, tasks) {\n+ var instance = instances[id];\n+ if (instance && Array.isArray(tasks)) {\n+ var results = [];\n+ tasks.forEach(function (task) {\n+ var handler = jsHandlers[task.method];\n+ var args = [].concat( task.args );\n+ /* istanbul ignore else */\n+ if (typeof handler === 'function') {\n+ args.unshift(id);\n+ results.push(handler.apply(void 0, args));\n }\n- }\n- });\n- // Finally `updateFinish` signal needed.\n- renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'updateFinish', args: [] }], -1);\n+ });\n+ return results\n+ }\n+ return new Error((\"invalid instance id \\\"\" + id + \"\\\" or tasks\"))\n }\n \n /**\n@@ -235,6 +241,18 @@ function registerModules (newModules) {\n for (var name in newModules) loop( name );\n }\n \n+/**\n+ * Check whether the module or the method has been registered.\n+ * @param {String} module name\n+ * @param {String} method name (optional)\n+ */\n+function isRegisteredModule (name, method) {\n+ if (typeof method === 'string') {\n+ return !!(modules[name] && modules[name][method])\n+ }\n+ return !!modules[name]\n+}\n+\n /**\n * Register native components information.\n * @param {array} newComponents\n@@ -254,6 +272,35 @@ function registerComponents (newComponents) {\n }\n }\n \n+/**\n+ * Check whether the component has been registered.\n+ * @param {String} component name\n+ */\n+function isRegisteredComponent (name) {\n+ return !!components[name]\n+}\n+\n+/**\n+ * Detects whether Weex supports specific features.\n+ * @param {String} condition\n+ */\n+function supports (condition) {\n+ if (typeof condition !== 'string') { return null }\n+\n+ var res = condition.match(/^@(\\w+)\\/(\\w+)(\\.(\\w+))?$/i);\n+ if (res) {\n+ var type = res[1];\n+ var name = res[2];\n+ var method = res[4];\n+ switch (type) {\n+ case 'module': return isRegisteredModule(name, method)\n+ case 'component': return isRegisteredComponent(name)\n+ }\n+ }\n+\n+ return null\n+}\n+\n /**\n * Create a fresh instance of Vue for each Weex instance.\n */\n@@ -314,9 +361,7 @@ function createVueModuleInstance (instanceId, moduleGetter) {\n * Generate native module getter. Each native module has several\n * methods to call. And all the behaviors is instance-related. So\n * this getter will return a set of methods which additionally\n- * send current instance id to native when called. Also the args\n- * will be normalized into \"safe\" value. For example function arg\n- * will be converted into a callback id.\n+ * send current instance id to native when called.\n * @param {string} instanceId\n * @return {function}\n */\n@@ -326,15 +371,23 @@ function genModuleGetter (instanceId) {\n var nativeModule = modules[name] || [];\n var output = {};\n var loop = function ( methodName ) {\n- output[methodName] = function () {\n- var args = [], len = arguments.length;\n- while ( len-- ) args[ len ] = arguments[ len ];\n-\n- var finalArgs = args.map(function (value) {\n- return normalize(value, instance)\n- });\n- renderer.sendTasks(instanceId + '', [{ module: name, method: methodName, args: finalArgs }], -1);\n- };\n+ Object.defineProperty(output, methodName, {\n+ enumerable: true,\n+ configurable: true,\n+ get: function proxyGetter () {\n+ return function () {\n+ var args = [], len = arguments.length;\n+ while ( len-- ) args[ len ] = arguments[ len ];\n+\n+ return instance.document.taskCenter.send('module', { module: name, method: methodName }, args)\n+ }\n+ },\n+ set: function proxySetter (val) {\n+ if (typeof val === 'function') {\n+ return instance.document.taskCenter.send('module', { module: name, method: methodName }, [val])\n+ }\n+ }\n+ });\n };\n \n for (var methodName in nativeModule) loop( methodName );\n@@ -362,8 +415,9 @@ function getInstanceTimer (instanceId, moduleGetter) {\n var handler = function () {\n args[0].apply(args, args.slice(2));\n };\n+\n timer.setTimeout(handler, args[1]);\n- return instance.callbackId.toString()\n+ return instance.document.taskCenter.callbackManager.lastCallbackId.toString()\n },\n setInterval: function () {\n var args = [], len = arguments.length;\n@@ -372,8 +426,9 @@ function getInstanceTimer (instanceId, moduleGetter) {\n var handler = function () {\n args[0].apply(args, args.slice(2));\n };\n+\n timer.setInterval(handler, args[1]);\n- return instance.callbackId.toString()\n+ return instance.document.taskCenter.callbackManager.lastCallbackId.toString()\n },\n clearTimeout: function (n) {\n timer.clearTimeout(n);\n@@ -405,52 +460,55 @@ function callFunction (globalObjects, body) {\n }\n \n /**\n- * Convert all type of values into \"safe\" format to send to native.\n- * 1. A `function` will be converted into callback id.\n- * 2. An `Element` object will be converted into `ref`.\n- * The `instance` param is used to generate callback id and store\n- * function if necessary.\n- * @param {any} v\n- * @param {object} instance\n- * @return {any}\n+ * Call a new function generated on the V8 native side.\n+ *\n+ * This function helps speed up bundle compiling. Normally, the V8\n+ * engine needs to download, parse, and compile a bundle on every\n+ * visit. If 'compileBundle()' is available on native side,\n+ * the downloding, parsing, and compiling steps would be skipped.\n+ * @param {object} globalObjects\n+ * @param {string} body\n+ * @return {boolean}\n */\n-function normalize (v, instance) {\n- var type = typof(v);\n-\n- switch (type) {\n- case 'undefined':\n- case 'null':\n- return ''\n- case 'regexp':\n- return v.toString()\n- case 'date':\n- return v.toISOString()\n- case 'number':\n- case 'string':\n- case 'boolean':\n- case 'array':\n- case 'object':\n- if (v instanceof renderer.Element) {\n- return v.ref\n- }\n- return v\n- case 'function':\n- instance.callbacks[++instance.callbackId] = v;\n- return instance.callbackId.toString()\n- default:\n- return JSON.stringify(v)\n+function callFunctionNative (globalObjects, body) {\n+ if (typeof renderer.compileBundle !== 'function') {\n+ return false\n }\n-}\n \n-/**\n- * Get the exact type of an object by `toString()`. For example call\n- * `toString()` on an array will be returned `[object Array]`.\n- * @param {any} v\n- * @return {string}\n- */\n-function typof (v) {\n- var s = Object.prototype.toString.call(v);\n- return s.substring(8, s.length - 1).toLowerCase()\n+ var fn = void 0;\n+ var isNativeCompileOk = false;\n+ var script = '(function (';\n+ var globalKeys = [];\n+ var globalValues = [];\n+ for (var key in globalObjects) {\n+ globalKeys.push(key);\n+ globalValues.push(globalObjects[key]);\n+ }\n+ for (var i = 0; i < globalKeys.length - 1; ++i) {\n+ script += globalKeys[i];\n+ script += ',';\n+ }\n+ script += globalKeys[globalKeys.length - 1];\n+ script += ') {';\n+ script += body;\n+ script += '} )';\n+\n+ try {\n+ var weex = globalObjects.weex || {};\n+ var config = weex.config || {};\n+ fn = renderer.compileBundle(script,\n+ config.bundleUrl,\n+ config.bundleDigest,\n+ config.codeCachePath);\n+ if (fn && typeof fn === 'function') {\n+ fn.apply(void 0, globalValues);\n+ isNativeCompileOk = true;\n+ }\n+ } catch (e) {\n+ console.error(e);\n+ }\n+\n+ return isNativeCompileOk\n }\n \n exports.init = init;\n@@ -461,4 +519,7 @@ exports.refreshInstance = refreshInstance;\n exports.getRoot = getRoot;\n exports.receiveTasks = receiveTasks;\n exports.registerModules = registerModules;\n+exports.isRegisteredModule = isRegisteredModule;\n exports.registerComponents = registerComponents;\n+exports.isRegisteredComponent = isRegisteredComponent;\n+exports.supports = supports;",
"filename": "packages/weex-vue-framework/index.js",
"status": "modified"
},
{
"diff": "@@ -1,6 +1,6 @@\n {\n \"name\": \"weex-vue-framework\",\n- \"version\": \"2.1.9-weex.1\",\n+ \"version\": \"2.4.2-weex.1\",\n \"description\": \"Vue 2.0 Framework for Weex\",\n \"main\": \"index.js\",\n \"repository\": {",
"filename": "packages/weex-vue-framework/package.json",
"status": "modified"
},
{
"diff": "@@ -79,7 +79,7 @@ export function renderMixin (Vue: Class<Component>) {\n if (vm._isMounted) {\n // clone slot nodes on re-renders\n for (const key in vm.$slots) {\n- vm.$slots[key] = cloneVNodes(vm.$slots[key])\n+ vm.$slots[key] = cloneVNodes(vm.$slots[key], true /* deep cloning */)\n }\n }\n ",
"filename": "src/core/instance/render.js",
"status": "modified"
},
{
"diff": "@@ -17,7 +17,7 @@ export const isAndroid = UA && UA.indexOf('android') > 0\n export const isIOS = UA && /iphone|ipad|ipod|ios/.test(UA)\n export const isChrome = UA && /chrome\\/\\d+/.test(UA) && !isEdge\n \n-// Firefix has a \"watch\" function on Object.prototype...\n+// Firefox has a \"watch\" function on Object.prototype...\n export const nativeWatch = ({}).watch\n \n export let supportsPassive = false",
"filename": "src/core/util/env.js",
"status": "modified"
},
{
"diff": "@@ -98,11 +98,18 @@ export function cloneVNode (vnode: VNode): VNode {\n return cloned\n }\n \n-export function cloneVNodes (vnodes: Array<VNode>): Array<VNode> {\n+function deepCloneVNode (vnode: VNode): VNode {\n+ const cloned = cloneVNode(vnode)\n+ if (vnode.children) cloned.children = cloneVNodes(vnode.children, true)\n+ return cloned\n+}\n+\n+export function cloneVNodes (vnodes: Array<VNode>, deep?: boolean): Array<VNode> {\n const len = vnodes.length\n const res = new Array(len)\n+ const clone = deep ? deepCloneVNode : cloneVNode\n for (let i = 0; i < len; i++) {\n- res[i] = cloneVNode(vnodes[i])\n+ res[i] = clone(vnodes[i])\n }\n return res\n }",
"filename": "src/core/vdom/vnode.js",
"status": "modified"
},
{
"diff": "@@ -685,4 +685,42 @@ describe('Component slot', () => {\n }).$mount()\n expect(vm.$el.innerHTML).toBe('<div>default<span>foo</span></div>')\n })\n+\n+ it('should re-create nested components in slot when rerendering container', done => {\n+ const created = jasmine.createSpy()\n+ const destroyed = jasmine.createSpy()\n+ const vm = new Vue({\n+ template: `\n+ <div>\n+ <container ref=\"container\">\n+ <div>\n+ <child></child>\n+ </div>\n+ </container>\n+ </div>\n+ `,\n+ components: {\n+ container: {\n+ template:\n+ '<component :is=\"tag\"><slot></slot></component>',\n+ data () {\n+ return { tag: 'h1' }\n+ }\n+ },\n+ child: {\n+ template: '<span>foo</span>',\n+ created,\n+ destroyed\n+ }\n+ }\n+ }).$mount()\n+ expect(vm.$el.innerHTML).toBe('<h1><div><span>foo</span></div></h1>')\n+ expect(created.calls.count()).toBe(1)\n+ vm.$refs.container.tag = 'h2'\n+ waitForUpdate(() => {\n+ expect(vm.$el.innerHTML).toBe('<h2><div><span>foo</span></div></h2>')\n+ expect(created.calls.count()).toBe(2)\n+ expect(destroyed.calls.count()).toBe(1)\n+ }).then(done)\n+ })\n })",
"filename": "test/unit/features/component/component-slot.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.4.2\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/z11fe07p/2382/](https://jsfiddle.net/z11fe07p/2382/)\r\n\r\n### Steps to reproduce\r\n- open https://jsfiddle.net/z11fe07p/2382/\r\n- click the \"B\" button\r\n\r\n### What is expected?\r\nThe previous component (A) should disappear before component B appears\r\n\r\n### What is actually happening?\r\nComponents A and B are visible simultaneously\r\n\r\n---\r\nsee also issue #5760\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [],
"number": 6256,
"title": "out-in transition issue with async components in a <keep-alive> block"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [ ] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n#6256 ",
"number": 6369,
"review_comments": [
{
"body": "I'm not familiar with writing tests for async components. Feel free to point me out If I'm not in the right way testing it.😅",
"created_at": "2017-08-15T17:25:18Z"
}
],
"title": "fix(transition): consider async placeholder as valid child to return, fix #6256"
} | {
"commits": [
{
"message": "[release] weex-vue-framework@2.4.2-weex.1 (#6196)\n\n* build(release weex): ignore the file path of entries\r\n\r\n* [release] weex-vue-framework@2.4.2-weex.1"
},
{
"message": "fix-Firefox (#6359)"
},
{
"message": "fix(transition): consider async placeholder as valid child to return, fix #6256"
},
{
"message": "refactor: always check asyncPlaceholder in getFirstComponentChild"
}
],
"files": [
{
"diff": "@@ -31,7 +31,6 @@ if [[ $REPLY =~ ^[Yy]$ ]]; then\n cd -\n \n # commit\n- git add src/entries/weex*\n git add packages/weex*\n git commit -m \"[release] weex-vue-framework@$NEXT_VERSION\"\n fi",
"filename": "build/release-weex.sh",
"status": "modified"
},
{
"diff": "@@ -2,7 +2,9 @@\n \n Object.defineProperty(exports, '__esModule', { value: true });\n \n-var he = require('he');\n+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n+\n+var he = _interopDefault(require('he'));\n \n /* */\n \n@@ -14,6 +16,8 @@ var he = require('he');\n \n \n \n+\n+\n /**\n * Check if value is primitive\n */\n@@ -24,15 +28,29 @@ var he = require('he');\n * Objects from primitive values when we know the value\n * is a JSON-compliant type.\n */\n+function isObject (obj) {\n+ return obj !== null && typeof obj === 'object'\n+}\n \n+var _toString = Object.prototype.toString;\n \n /**\n * Strict object type check. Only returns true\n * for plain JavaScript objects.\n */\n+function isPlainObject (obj) {\n+ return _toString.call(obj) === '[object Object]'\n+}\n \n \n \n+/**\n+ * Check if val is a valid array index.\n+ */\n+function isValidArrayIndex (val) {\n+ var n = parseFloat(val);\n+ return n >= 0 && Math.floor(n) === n && isFinite(val)\n+}\n \n /**\n * Convert a value to a string that is actually rendered.\n@@ -69,11 +87,29 @@ function makeMap (\n var isBuiltInTag = makeMap('slot,component', true);\n \n /**\n- * Remove an item from an array\n+ * Check if a attribute is a reserved attribute.\n */\n+var isReservedAttribute = makeMap('key,ref,slot,is');\n \n+/**\n+ * Remove an item from an array\n+ */\n+function remove (arr, item) {\n+ if (arr.length) {\n+ var index = arr.indexOf(item);\n+ if (index > -1) {\n+ return arr.splice(index, 1)\n+ }\n+ }\n+}\n \n-\n+/**\n+ * Check whether the object has the property.\n+ */\n+var hasOwnProperty = Object.prototype.hasOwnProperty;\n+function hasOwn (obj, key) {\n+ return hasOwnProperty.call(obj, key)\n+}\n \n /**\n * Create a cached version of a pure function.\n@@ -128,13 +164,15 @@ function extend (to, _from) {\n \n /**\n * Perform no operation.\n+ * Stubbing args to make Flow happy without leaving useless transpiled code\n+ * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/)\n */\n-function noop () {}\n+function noop (a, b, c) {}\n \n /**\n * Always return false.\n */\n-var no = function () { return false; };\n+var no = function (a, b, c) { return false; };\n \n /**\n * Return same value\n@@ -243,6 +281,10 @@ var decodingMap = {\n var encodedAttr = /&(?:lt|gt|quot|amp);/g;\n var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g;\n \n+// #5992\n+var isIgnoreNewlineTag = makeMap('pre,textarea', true);\n+var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\\n'; };\n+\n function decodeAttr (value, shouldDecodeNewlines) {\n var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr;\n return value.replace(re, function (match) { return decodingMap[match]; })\n@@ -266,6 +308,9 @@ function parseHTML (html, options) {\n var commentEnd = html.indexOf('-->');\n \n if (commentEnd >= 0) {\n+ if (options.shouldKeepComment) {\n+ options.comment(html.substring(4, commentEnd));\n+ }\n advance(commentEnd + 3);\n continue\n }\n@@ -301,24 +346,27 @@ function parseHTML (html, options) {\n var startTagMatch = parseStartTag();\n if (startTagMatch) {\n handleStartTag(startTagMatch);\n+ if (shouldIgnoreFirstNewline(lastTag, html)) {\n+ advance(1);\n+ }\n continue\n }\n }\n \n- var text = (void 0), rest$1 = (void 0), next = (void 0);\n+ var text = (void 0), rest = (void 0), next = (void 0);\n if (textEnd >= 0) {\n- rest$1 = html.slice(textEnd);\n+ rest = html.slice(textEnd);\n while (\n- !endTag.test(rest$1) &&\n- !startTagOpen.test(rest$1) &&\n- !comment.test(rest$1) &&\n- !conditionalComment.test(rest$1)\n+ !endTag.test(rest) &&\n+ !startTagOpen.test(rest) &&\n+ !comment.test(rest) &&\n+ !conditionalComment.test(rest)\n ) {\n // < in plain text, be forgiving and treat it as text\n- next = rest$1.indexOf('<', 1);\n+ next = rest.indexOf('<', 1);\n if (next < 0) { break }\n textEnd += next;\n- rest$1 = html.slice(textEnd);\n+ rest = html.slice(textEnd);\n }\n text = html.substring(0, textEnd);\n advance(textEnd);\n@@ -333,23 +381,26 @@ function parseHTML (html, options) {\n options.chars(text);\n }\n } else {\n+ var endTagLength = 0;\n var stackedTag = lastTag.toLowerCase();\n var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\\\s\\\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));\n- var endTagLength = 0;\n- var rest = html.replace(reStackedTag, function (all, text, endTag) {\n+ var rest$1 = html.replace(reStackedTag, function (all, text, endTag) {\n endTagLength = endTag.length;\n if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {\n text = text\n .replace(/<!--([\\s\\S]*?)-->/g, '$1')\n .replace(/<!\\[CDATA\\[([\\s\\S]*?)]]>/g, '$1');\n }\n+ if (shouldIgnoreFirstNewline(stackedTag, text)) {\n+ text = text.slice(1);\n+ }\n if (options.chars) {\n options.chars(text);\n }\n return ''\n });\n- index += html.length - rest.length;\n- html = rest;\n+ index += html.length - rest$1.length;\n+ html = rest$1;\n parseEndTag(stackedTag, index - endTagLength, index);\n }\n \n@@ -406,7 +457,7 @@ function parseHTML (html, options) {\n }\n }\n \n- var unary = isUnaryTag$$1(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash;\n+ var unary = isUnaryTag$$1(tagName) || !!unarySlash;\n \n var l = match.attrs.length;\n var attrs = new Array(l);\n@@ -463,8 +514,9 @@ function parseHTML (html, options) {\n // Close all the open elements, up the stack\n for (var i = stack.length - 1; i >= pos; i--) {\n if (process.env.NODE_ENV !== 'production' &&\n- (i > pos || !tagName) &&\n- options.warn) {\n+ (i > pos || !tagName) &&\n+ options.warn\n+ ) {\n options.warn(\n (\"tag <\" + (stack[i].tag) + \"> has no matching end tag.\")\n );\n@@ -674,10 +726,7 @@ function genAssignmentCode (\n if (modelRs.idx === null) {\n return (value + \"=\" + assignment)\n } else {\n- return \"var $$exp = \" + (modelRs.exp) + \", $$idx = \" + (modelRs.idx) + \";\" +\n- \"if (!Array.isArray($$exp)){\" +\n- value + \"=\" + assignment + \"}\" +\n- \"else{$$exp.splice($$idx, 1, \" + assignment + \")}\"\n+ return (\"$set(\" + (modelRs.exp) + \", \" + (modelRs.idx) + \", \" + assignment + \")\")\n }\n }\n \n@@ -770,6 +819,12 @@ function parseString (chr) {\n }\n }\n \n+var ASSET_TYPES = [\n+ 'component',\n+ 'directive',\n+ 'filter'\n+];\n+\n var LIFECYCLE_HOOKS = [\n 'beforeCreate',\n 'created',\n@@ -816,6 +871,11 @@ var config = ({\n */\n errorHandler: null,\n \n+ /**\n+ * Warn handler for watcher warns\n+ */\n+ warnHandler: null,\n+\n /**\n * Ignore certain custom elements\n */\n@@ -866,9 +926,11 @@ var config = ({\n _lifecycleHooks: LIFECYCLE_HOOKS\n });\n \n+/* */\n+\n var warn$1 = noop;\n var tip = noop;\n-var formatComponentName;\n+var formatComponentName = (null); // work around flow check\n \n if (process.env.NODE_ENV !== 'production') {\n var hasConsole = typeof console !== 'undefined';\n@@ -878,10 +940,12 @@ if (process.env.NODE_ENV !== 'production') {\n .replace(/[-_]/g, ''); };\n \n warn$1 = function (msg, vm) {\n- if (hasConsole && (!config.silent)) {\n- console.error(\"[Vue warn]: \" + msg + (\n- vm ? generateComponentTrace(vm) : ''\n- ));\n+ var trace = vm ? generateComponentTrace(vm) : '';\n+\n+ if (config.warnHandler) {\n+ config.warnHandler.call(null, msg, vm, trace);\n+ } else if (hasConsole && (!config.silent)) {\n+ console.error((\"[Vue warn]: \" + msg + trace));\n }\n };\n \n@@ -957,6 +1021,8 @@ if (process.env.NODE_ENV !== 'production') {\n };\n }\n \n+/* */\n+\n function handleError (err, vm, info) {\n if (config.errorHandler) {\n config.errorHandler.call(null, err, vm, info);\n@@ -977,7 +1043,7 @@ function handleError (err, vm, info) {\n /* globals MutationObserver */\n \n // can we use __proto__?\n-\n+var hasProto = '__proto__' in {};\n \n // Browser environment sniffing\n var inBrowser = typeof window !== 'undefined';\n@@ -989,6 +1055,9 @@ var isAndroid = UA && UA.indexOf('android') > 0;\n var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);\n var isChrome = UA && /chrome\\/\\d+/.test(UA) && !isEdge;\n \n+// Firefix has a \"watch\" function on Object.prototype...\n+var nativeWatch = ({}).watch;\n+\n var supportsPassive = false;\n if (inBrowser) {\n try {\n@@ -998,7 +1067,7 @@ if (inBrowser) {\n /* istanbul ignore next */\n supportsPassive = true;\n }\n- } )); // https://github.com/facebook/flow/issues/285\n+ })); // https://github.com/facebook/flow/issues/285\n window.addEventListener('test-passive', null, opts);\n } catch (e) {}\n }\n@@ -1292,12 +1361,15 @@ function parse (\n options\n ) {\n warn = options.warn || baseWarn;\n- platformGetTagNamespace = options.getTagNamespace || no;\n- platformMustUseProp = options.mustUseProp || no;\n+\n platformIsPreTag = options.isPreTag || no;\n- preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');\n+ platformMustUseProp = options.mustUseProp || no;\n+ platformGetTagNamespace = options.getTagNamespace || no;\n+\n transforms = pluckModuleFunction(options.modules, 'transformNode');\n+ preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');\n postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');\n+\n delimiters = options.delimiters;\n \n var stack = [];\n@@ -1331,6 +1403,7 @@ function parse (\n isUnaryTag: options.isUnaryTag,\n canBeLeftOpenTag: options.canBeLeftOpenTag,\n shouldDecodeNewlines: options.shouldDecodeNewlines,\n+ shouldKeepComment: options.comments,\n start: function start (tag, attrs, unary) {\n // check namespace.\n // inherit parent ns if there is one\n@@ -1489,8 +1562,9 @@ function parse (\n // IE textarea placeholder bug\n /* istanbul ignore if */\n if (isIE &&\n- currentParent.tag === 'textarea' &&\n- currentParent.attrsMap.placeholder === text) {\n+ currentParent.tag === 'textarea' &&\n+ currentParent.attrsMap.placeholder === text\n+ ) {\n return\n }\n var children = currentParent.children;\n@@ -1513,6 +1587,13 @@ function parse (\n });\n }\n }\n+ },\n+ comment: function comment (text) {\n+ currentParent.children.push({\n+ type: 3,\n+ text: text,\n+ isComment: true\n+ });\n }\n });\n return root\n@@ -1714,7 +1795,9 @@ function processAttrs (el) {\n );\n }\n }\n- if (isProp || platformMustUseProp(el.tag, el.attrsMap.type, name)) {\n+ if (isProp || (\n+ !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name)\n+ )) {\n addProp(el, name, value);\n } else {\n addAttr(el, name, value);\n@@ -1889,6 +1972,15 @@ function markStatic (node) {\n node.static = false;\n }\n }\n+ if (node.ifConditions) {\n+ for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) {\n+ var block = node.ifConditions[i$1].block;\n+ markStatic(block);\n+ if (!block.static) {\n+ node.static = false;\n+ }\n+ }\n+ }\n }\n }\n \n@@ -1915,17 +2007,13 @@ function markStaticRoots (node, isInFor) {\n }\n }\n if (node.ifConditions) {\n- walkThroughConditionsBlocks(node.ifConditions, isInFor);\n+ for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) {\n+ markStaticRoots(node.ifConditions[i$1].block, isInFor);\n+ }\n }\n }\n }\n \n-function walkThroughConditionsBlocks (conditionBlocks, isInFor) {\n- for (var i = 1, len = conditionBlocks.length; i < len; i++) {\n- markStaticRoots(conditionBlocks[i].block, isInFor);\n- }\n-}\n-\n function isStatic (node) {\n if (node.type === 2) { // expression\n return false\n@@ -1994,17 +2082,17 @@ var modifierCode = {\n \n function genHandlers (\n events,\n- native,\n+ isNative,\n warn\n ) {\n- var res = native ? 'nativeOn:{' : 'on:{';\n+ var res = isNative ? 'nativeOn:{' : 'on:{';\n for (var name in events) {\n var handler = events[name];\n // #5330: warn click.right, since right clicks do not actually fire click events.\n if (process.env.NODE_ENV !== 'production' &&\n- name === 'click' &&\n- handler && handler.modifiers && handler.modifiers.right\n- ) {\n+ name === 'click' &&\n+ handler && handler.modifiers && handler.modifiers.right\n+ ) {\n warn(\n \"Use \\\"contextmenu\\\" instead of \\\"click.right\\\" since right clicks \" +\n \"do not actually fire \\\"click\\\" events.\"\n@@ -2080,99 +2168,639 @@ function genFilterCode (key) {\n \n /* */\n \n+var emptyObject = Object.freeze({});\n+\n+/**\n+ * Check if a string starts with $ or _\n+ */\n+\n+\n+/**\n+ * Define a property.\n+ */\n+function def (obj, key, val, enumerable) {\n+ Object.defineProperty(obj, key, {\n+ value: val,\n+ enumerable: !!enumerable,\n+ writable: true,\n+ configurable: true\n+ });\n+}\n+\n+/* */\n+\n+\n+var uid = 0;\n+\n+/**\n+ * A dep is an observable that can have multiple\n+ * directives subscribing to it.\n+ */\n+var Dep = function Dep () {\n+ this.id = uid++;\n+ this.subs = [];\n+};\n+\n+Dep.prototype.addSub = function addSub (sub) {\n+ this.subs.push(sub);\n+};\n+\n+Dep.prototype.removeSub = function removeSub (sub) {\n+ remove(this.subs, sub);\n+};\n+\n+Dep.prototype.depend = function depend () {\n+ if (Dep.target) {\n+ Dep.target.addDep(this);\n+ }\n+};\n+\n+Dep.prototype.notify = function notify () {\n+ // stabilize the subscriber list first\n+ var subs = this.subs.slice();\n+ for (var i = 0, l = subs.length; i < l; i++) {\n+ subs[i].update();\n+ }\n+};\n+\n+// the current target watcher being evaluated.\n+// this is globally unique because there could be only one\n+// watcher being evaluated at any time.\n+Dep.target = null;\n+\n+/*\n+ * not type checking this file because flow doesn't play well with\n+ * dynamically accessing methods on Array prototype\n+ */\n+\n+var arrayProto = Array.prototype;\n+var arrayMethods = Object.create(arrayProto);[\n+ 'push',\n+ 'pop',\n+ 'shift',\n+ 'unshift',\n+ 'splice',\n+ 'sort',\n+ 'reverse'\n+]\n+.forEach(function (method) {\n+ // cache original method\n+ var original = arrayProto[method];\n+ def(arrayMethods, method, function mutator () {\n+ var args = [], len = arguments.length;\n+ while ( len-- ) args[ len ] = arguments[ len ];\n+\n+ var result = original.apply(this, args);\n+ var ob = this.__ob__;\n+ var inserted;\n+ switch (method) {\n+ case 'push':\n+ case 'unshift':\n+ inserted = args;\n+ break\n+ case 'splice':\n+ inserted = args.slice(2);\n+ break\n+ }\n+ if (inserted) { ob.observeArray(inserted); }\n+ // notify change\n+ ob.dep.notify();\n+ return result\n+ });\n+});\n+\n+/* */\n+\n+var arrayKeys = Object.getOwnPropertyNames(arrayMethods);\n+\n+/**\n+ * By default, when a reactive property is set, the new value is\n+ * also converted to become reactive. However when passing down props,\n+ * we don't want to force conversion because the value may be a nested value\n+ * under a frozen data structure. Converting it would defeat the optimization.\n+ */\n+var observerState = {\n+ shouldConvert: true\n+};\n+\n+/**\n+ * Observer class that are attached to each observed\n+ * object. Once attached, the observer converts target\n+ * object's property keys into getter/setters that\n+ * collect dependencies and dispatches updates.\n+ */\n+var Observer = function Observer (value) {\n+ this.value = value;\n+ this.dep = new Dep();\n+ this.vmCount = 0;\n+ def(value, '__ob__', this);\n+ if (Array.isArray(value)) {\n+ var augment = hasProto\n+ ? protoAugment\n+ : copyAugment;\n+ augment(value, arrayMethods, arrayKeys);\n+ this.observeArray(value);\n+ } else {\n+ this.walk(value);\n+ }\n+};\n+\n+/**\n+ * Walk through each property and convert them into\n+ * getter/setters. This method should only be called when\n+ * value type is Object.\n+ */\n+Observer.prototype.walk = function walk (obj) {\n+ var keys = Object.keys(obj);\n+ for (var i = 0; i < keys.length; i++) {\n+ defineReactive$$1(obj, keys[i], obj[keys[i]]);\n+ }\n+};\n+\n+/**\n+ * Observe a list of Array items.\n+ */\n+Observer.prototype.observeArray = function observeArray (items) {\n+ for (var i = 0, l = items.length; i < l; i++) {\n+ observe(items[i]);\n+ }\n+};\n+\n+// helpers\n+\n+/**\n+ * Augment an target Object or Array by intercepting\n+ * the prototype chain using __proto__\n+ */\n+function protoAugment (target, src, keys) {\n+ /* eslint-disable no-proto */\n+ target.__proto__ = src;\n+ /* eslint-enable no-proto */\n+}\n+\n+/**\n+ * Augment an target Object or Array by defining\n+ * hidden properties.\n+ */\n+/* istanbul ignore next */\n+function copyAugment (target, src, keys) {\n+ for (var i = 0, l = keys.length; i < l; i++) {\n+ var key = keys[i];\n+ def(target, key, src[key]);\n+ }\n+}\n+\n+/**\n+ * Attempt to create an observer instance for a value,\n+ * returns the new observer if successfully observed,\n+ * or the existing observer if the value already has one.\n+ */\n+function observe (value, asRootData) {\n+ if (!isObject(value)) {\n+ return\n+ }\n+ var ob;\n+ if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {\n+ ob = value.__ob__;\n+ } else if (\n+ observerState.shouldConvert &&\n+ !isServerRendering() &&\n+ (Array.isArray(value) || isPlainObject(value)) &&\n+ Object.isExtensible(value) &&\n+ !value._isVue\n+ ) {\n+ ob = new Observer(value);\n+ }\n+ if (asRootData && ob) {\n+ ob.vmCount++;\n+ }\n+ return ob\n+}\n+\n+/**\n+ * Define a reactive property on an Object.\n+ */\n+function defineReactive$$1 (\n+ obj,\n+ key,\n+ val,\n+ customSetter,\n+ shallow\n+) {\n+ var dep = new Dep();\n+\n+ var property = Object.getOwnPropertyDescriptor(obj, key);\n+ if (property && property.configurable === false) {\n+ return\n+ }\n+\n+ // cater for pre-defined getter/setters\n+ var getter = property && property.get;\n+ var setter = property && property.set;\n+\n+ var childOb = !shallow && observe(val);\n+ Object.defineProperty(obj, key, {\n+ enumerable: true,\n+ configurable: true,\n+ get: function reactiveGetter () {\n+ var value = getter ? getter.call(obj) : val;\n+ if (Dep.target) {\n+ dep.depend();\n+ if (childOb) {\n+ childOb.dep.depend();\n+ }\n+ if (Array.isArray(value)) {\n+ dependArray(value);\n+ }\n+ }\n+ return value\n+ },\n+ set: function reactiveSetter (newVal) {\n+ var value = getter ? getter.call(obj) : val;\n+ /* eslint-disable no-self-compare */\n+ if (newVal === value || (newVal !== newVal && value !== value)) {\n+ return\n+ }\n+ /* eslint-enable no-self-compare */\n+ if (process.env.NODE_ENV !== 'production' && customSetter) {\n+ customSetter();\n+ }\n+ if (setter) {\n+ setter.call(obj, newVal);\n+ } else {\n+ val = newVal;\n+ }\n+ childOb = !shallow && observe(newVal);\n+ dep.notify();\n+ }\n+ });\n+}\n+\n+/**\n+ * Set a property on an object. Adds the new property and\n+ * triggers change notification if the property doesn't\n+ * already exist.\n+ */\n+function set (target, key, val) {\n+ if (Array.isArray(target) && isValidArrayIndex(key)) {\n+ target.length = Math.max(target.length, key);\n+ target.splice(key, 1, val);\n+ return val\n+ }\n+ if (hasOwn(target, key)) {\n+ target[key] = val;\n+ return val\n+ }\n+ var ob = (target).__ob__;\n+ if (target._isVue || (ob && ob.vmCount)) {\n+ process.env.NODE_ENV !== 'production' && warn$1(\n+ 'Avoid adding reactive properties to a Vue instance or its root $data ' +\n+ 'at runtime - declare it upfront in the data option.'\n+ );\n+ return val\n+ }\n+ if (!ob) {\n+ target[key] = val;\n+ return val\n+ }\n+ defineReactive$$1(ob.value, key, val);\n+ ob.dep.notify();\n+ return val\n+}\n+\n+/**\n+ * Delete a property and trigger change if necessary.\n+ */\n+\n+\n+/**\n+ * Collect dependencies on array elements when the array is touched, since\n+ * we cannot intercept array element access like property getters.\n+ */\n+function dependArray (value) {\n+ for (var e = (void 0), i = 0, l = value.length; i < l; i++) {\n+ e = value[i];\n+ e && e.__ob__ && e.__ob__.dep.depend();\n+ if (Array.isArray(e)) {\n+ dependArray(e);\n+ }\n+ }\n+}\n+\n+/* */\n+\n+/**\n+ * Option overwriting strategies are functions that handle\n+ * how to merge a parent option value and a child option\n+ * value into the final value.\n+ */\n+var strats = config.optionMergeStrategies;\n+\n+/**\n+ * Options with restrictions\n+ */\n+if (process.env.NODE_ENV !== 'production') {\n+ strats.el = strats.propsData = function (parent, child, vm, key) {\n+ if (!vm) {\n+ warn$1(\n+ \"option \\\"\" + key + \"\\\" can only be used during instance \" +\n+ 'creation with the `new` keyword.'\n+ );\n+ }\n+ return defaultStrat(parent, child)\n+ };\n+}\n+\n+/**\n+ * Helper that recursively merges two data objects together.\n+ */\n+function mergeData (to, from) {\n+ if (!from) { return to }\n+ var key, toVal, fromVal;\n+ var keys = Object.keys(from);\n+ for (var i = 0; i < keys.length; i++) {\n+ key = keys[i];\n+ toVal = to[key];\n+ fromVal = from[key];\n+ if (!hasOwn(to, key)) {\n+ set(to, key, fromVal);\n+ } else if (isPlainObject(toVal) && isPlainObject(fromVal)) {\n+ mergeData(toVal, fromVal);\n+ }\n+ }\n+ return to\n+}\n+\n+/**\n+ * Data\n+ */\n+function mergeDataOrFn (\n+ parentVal,\n+ childVal,\n+ vm\n+) {\n+ if (!vm) {\n+ // in a Vue.extend merge, both should be functions\n+ if (!childVal) {\n+ return parentVal\n+ }\n+ if (!parentVal) {\n+ return childVal\n+ }\n+ // when parentVal & childVal are both present,\n+ // we need to return a function that returns the\n+ // merged result of both functions... no need to\n+ // check if parentVal is a function here because\n+ // it has to be a function to pass previous merges.\n+ return function mergedDataFn () {\n+ return mergeData(\n+ typeof childVal === 'function' ? childVal.call(this) : childVal,\n+ typeof parentVal === 'function' ? parentVal.call(this) : parentVal\n+ )\n+ }\n+ } else if (parentVal || childVal) {\n+ return function mergedInstanceDataFn () {\n+ // instance merge\n+ var instanceData = typeof childVal === 'function'\n+ ? childVal.call(vm)\n+ : childVal;\n+ var defaultData = typeof parentVal === 'function'\n+ ? parentVal.call(vm)\n+ : undefined;\n+ if (instanceData) {\n+ return mergeData(instanceData, defaultData)\n+ } else {\n+ return defaultData\n+ }\n+ }\n+ }\n+}\n+\n+strats.data = function (\n+ parentVal,\n+ childVal,\n+ vm\n+) {\n+ if (!vm) {\n+ if (childVal && typeof childVal !== 'function') {\n+ process.env.NODE_ENV !== 'production' && warn$1(\n+ 'The \"data\" option should be a function ' +\n+ 'that returns a per-instance value in component ' +\n+ 'definitions.',\n+ vm\n+ );\n+\n+ return parentVal\n+ }\n+ return mergeDataOrFn.call(this, parentVal, childVal)\n+ }\n+\n+ return mergeDataOrFn(parentVal, childVal, vm)\n+};\n+\n+/**\n+ * Hooks and props are merged as arrays.\n+ */\n+function mergeHook (\n+ parentVal,\n+ childVal\n+) {\n+ return childVal\n+ ? parentVal\n+ ? parentVal.concat(childVal)\n+ : Array.isArray(childVal)\n+ ? childVal\n+ : [childVal]\n+ : parentVal\n+}\n+\n+LIFECYCLE_HOOKS.forEach(function (hook) {\n+ strats[hook] = mergeHook;\n+});\n+\n+/**\n+ * Assets\n+ *\n+ * When a vm is present (instance creation), we need to do\n+ * a three-way merge between constructor options, instance\n+ * options and parent options.\n+ */\n+function mergeAssets (parentVal, childVal) {\n+ var res = Object.create(parentVal || null);\n+ return childVal\n+ ? extend(res, childVal)\n+ : res\n+}\n+\n+ASSET_TYPES.forEach(function (type) {\n+ strats[type + 's'] = mergeAssets;\n+});\n+\n+/**\n+ * Watchers.\n+ *\n+ * Watchers hashes should not overwrite one\n+ * another, so we merge them as arrays.\n+ */\n+strats.watch = function (parentVal, childVal) {\n+ // work around Firefox's Object.prototype.watch...\n+ if (parentVal === nativeWatch) { parentVal = undefined; }\n+ if (childVal === nativeWatch) { childVal = undefined; }\n+ /* istanbul ignore if */\n+ if (!childVal) { return Object.create(parentVal || null) }\n+ if (!parentVal) { return childVal }\n+ var ret = {};\n+ extend(ret, parentVal);\n+ for (var key in childVal) {\n+ var parent = ret[key];\n+ var child = childVal[key];\n+ if (parent && !Array.isArray(parent)) {\n+ parent = [parent];\n+ }\n+ ret[key] = parent\n+ ? parent.concat(child)\n+ : Array.isArray(child) ? child : [child];\n+ }\n+ return ret\n+};\n+\n+/**\n+ * Other object hashes.\n+ */\n+strats.props =\n+strats.methods =\n+strats.inject =\n+strats.computed = function (parentVal, childVal) {\n+ if (!parentVal) { return childVal }\n+ var ret = Object.create(null);\n+ extend(ret, parentVal);\n+ if (childVal) { extend(ret, childVal); }\n+ return ret\n+};\n+strats.provide = mergeDataOrFn;\n+\n+/**\n+ * Default strategy.\n+ */\n+var defaultStrat = function (parentVal, childVal) {\n+ return childVal === undefined\n+ ? parentVal\n+ : childVal\n+};\n+\n+/**\n+ * Merge two option objects into a new one.\n+ * Core utility used in both instantiation and inheritance.\n+ */\n+\n+\n+/**\n+ * Resolve an asset.\n+ * This function is used because child instances need access\n+ * to assets defined in its ancestor chain.\n+ */\n+\n+/* */\n+\n+/* */\n+\n+/* */\n+\n+function on (el, dir) {\n+ if (process.env.NODE_ENV !== 'production' && dir.modifiers) {\n+ warn$1(\"v-on without argument does not support modifiers.\");\n+ }\n+ el.wrapListeners = function (code) { return (\"_g(\" + code + \",\" + (dir.value) + \")\"); };\n+}\n+\n+/* */\n+\n function bind$1 (el, dir) {\n el.wrapData = function (code) {\n- return (\"_b(\" + code + \",'\" + (el.tag) + \"',\" + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + \")\")\n+ return (\"_b(\" + code + \",'\" + (el.tag) + \"',\" + (dir.value) + \",\" + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + \")\")\n };\n }\n \n /* */\n \n var baseDirectives = {\n+ on: on,\n bind: bind$1,\n cloak: noop\n };\n \n /* */\n \n-// configurable state\n-var warn$2;\n-var transforms$1;\n-var dataGenFns;\n-var platformDirectives;\n-var isPlatformReservedTag$1;\n-var staticRenderFns;\n-var onceCount;\n-var currentOptions;\n+var CodegenState = function CodegenState (options) {\n+ this.options = options;\n+ this.warn = options.warn || baseWarn;\n+ this.transforms = pluckModuleFunction(options.modules, 'transformCode');\n+ this.dataGenFns = pluckModuleFunction(options.modules, 'genData');\n+ this.directives = extend(extend({}, baseDirectives), options.directives);\n+ var isReservedTag = options.isReservedTag || no;\n+ this.maybeComponent = function (el) { return !isReservedTag(el.tag); };\n+ this.onceId = 0;\n+ this.staticRenderFns = [];\n+};\n+\n+\n \n function generate (\n ast,\n options\n ) {\n- // save previous staticRenderFns so generate calls can be nested\n- var prevStaticRenderFns = staticRenderFns;\n- var currentStaticRenderFns = staticRenderFns = [];\n- var prevOnceCount = onceCount;\n- onceCount = 0;\n- currentOptions = options;\n- warn$2 = options.warn || baseWarn;\n- transforms$1 = pluckModuleFunction(options.modules, 'transformCode');\n- dataGenFns = pluckModuleFunction(options.modules, 'genData');\n- platformDirectives = options.directives || {};\n- isPlatformReservedTag$1 = options.isReservedTag || no;\n- var code = ast ? genElement(ast) : '_c(\"div\")';\n- staticRenderFns = prevStaticRenderFns;\n- onceCount = prevOnceCount;\n+ var state = new CodegenState(options);\n+ var code = ast ? genElement(ast, state) : '_c(\"div\")';\n return {\n render: (\"with(this){return \" + code + \"}\"),\n- staticRenderFns: currentStaticRenderFns\n+ staticRenderFns: state.staticRenderFns\n }\n }\n \n-function genElement (el) {\n+function genElement (el, state) {\n if (el.staticRoot && !el.staticProcessed) {\n- return genStatic(el)\n+ return genStatic(el, state)\n } else if (el.once && !el.onceProcessed) {\n- return genOnce(el)\n+ return genOnce(el, state)\n } else if (el.for && !el.forProcessed) {\n- return genFor(el)\n+ return genFor(el, state)\n } else if (el.if && !el.ifProcessed) {\n- return genIf(el)\n+ return genIf(el, state)\n } else if (el.tag === 'template' && !el.slotTarget) {\n- return genChildren(el) || 'void 0'\n+ return genChildren(el, state) || 'void 0'\n } else if (el.tag === 'slot') {\n- return genSlot(el)\n+ return genSlot(el, state)\n } else {\n // component or element\n var code;\n if (el.component) {\n- code = genComponent(el.component, el);\n+ code = genComponent(el.component, el, state);\n } else {\n- var data = el.plain ? undefined : genData(el);\n+ var data = el.plain ? undefined : genData(el, state);\n \n- var children = el.inlineTemplate ? null : genChildren(el, true);\n+ var children = el.inlineTemplate ? null : genChildren(el, state, true);\n code = \"_c('\" + (el.tag) + \"'\" + (data ? (\",\" + data) : '') + (children ? (\",\" + children) : '') + \")\";\n }\n // module transforms\n- for (var i = 0; i < transforms$1.length; i++) {\n- code = transforms$1[i](el, code);\n+ for (var i = 0; i < state.transforms.length; i++) {\n+ code = state.transforms[i](el, code);\n }\n return code\n }\n }\n \n // hoist static sub-trees out\n-function genStatic (el) {\n+function genStatic (el, state) {\n el.staticProcessed = true;\n- staticRenderFns.push((\"with(this){return \" + (genElement(el)) + \"}\"));\n- return (\"_m(\" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + \")\")\n+ state.staticRenderFns.push((\"with(this){return \" + (genElement(el, state)) + \"}\"));\n+ return (\"_m(\" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + \")\")\n }\n \n // v-once\n-function genOnce (el) {\n+function genOnce (el, state) {\n el.onceProcessed = true;\n if (el.if && !el.ifProcessed) {\n- return genIf(el)\n+ return genIf(el, state)\n } else if (el.staticInFor) {\n var key = '';\n var parent = el.parent;\n@@ -2184,51 +2812,72 @@ function genOnce (el) {\n parent = parent.parent;\n }\n if (!key) {\n- process.env.NODE_ENV !== 'production' && warn$2(\n+ process.env.NODE_ENV !== 'production' && state.warn(\n \"v-once can only be used inside v-for that is keyed. \"\n );\n- return genElement(el)\n+ return genElement(el, state)\n }\n- return (\"_o(\" + (genElement(el)) + \",\" + (onceCount++) + (key ? (\",\" + key) : \"\") + \")\")\n+ return (\"_o(\" + (genElement(el, state)) + \",\" + (state.onceId++) + (key ? (\",\" + key) : \"\") + \")\")\n } else {\n- return genStatic(el)\n+ return genStatic(el, state)\n }\n }\n \n-function genIf (el) {\n+function genIf (\n+ el,\n+ state,\n+ altGen,\n+ altEmpty\n+) {\n el.ifProcessed = true; // avoid recursion\n- return genIfConditions(el.ifConditions.slice())\n+ return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty)\n }\n \n-function genIfConditions (conditions) {\n+function genIfConditions (\n+ conditions,\n+ state,\n+ altGen,\n+ altEmpty\n+) {\n if (!conditions.length) {\n- return '_e()'\n+ return altEmpty || '_e()'\n }\n \n var condition = conditions.shift();\n if (condition.exp) {\n- return (\"(\" + (condition.exp) + \")?\" + (genTernaryExp(condition.block)) + \":\" + (genIfConditions(conditions)))\n+ return (\"(\" + (condition.exp) + \")?\" + (genTernaryExp(condition.block)) + \":\" + (genIfConditions(conditions, state, altGen, altEmpty)))\n } else {\n return (\"\" + (genTernaryExp(condition.block)))\n }\n \n // v-if with v-once should generate code like (a)?_m(0):_m(1)\n function genTernaryExp (el) {\n- return el.once ? genOnce(el) : genElement(el)\n+ return altGen\n+ ? altGen(el, state)\n+ : el.once\n+ ? genOnce(el, state)\n+ : genElement(el, state)\n }\n }\n \n-function genFor (el) {\n+function genFor (\n+ el,\n+ state,\n+ altGen,\n+ altHelper\n+) {\n var exp = el.for;\n var alias = el.alias;\n var iterator1 = el.iterator1 ? (\",\" + (el.iterator1)) : '';\n var iterator2 = el.iterator2 ? (\",\" + (el.iterator2)) : '';\n \n- if (\n- process.env.NODE_ENV !== 'production' &&\n- maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key\n+ if (process.env.NODE_ENV !== 'production' &&\n+ state.maybeComponent(el) &&\n+ el.tag !== 'slot' &&\n+ el.tag !== 'template' &&\n+ !el.key\n ) {\n- warn$2(\n+ state.warn(\n \"<\" + (el.tag) + \" v-for=\\\"\" + alias + \" in \" + exp + \"\\\">: component lists rendered with \" +\n \"v-for should have explicit keys. \" +\n \"See https://vuejs.org/guide/list.html#key for more info.\",\n@@ -2237,18 +2886,18 @@ function genFor (el) {\n }\n \n el.forProcessed = true; // avoid recursion\n- return \"_l((\" + exp + \"),\" +\n+ return (altHelper || '_l') + \"((\" + exp + \"),\" +\n \"function(\" + alias + iterator1 + iterator2 + \"){\" +\n- \"return \" + (genElement(el)) +\n+ \"return \" + ((altGen || genElement)(el, state)) +\n '})'\n }\n \n-function genData (el) {\n+function genData (el, state) {\n var data = '{';\n \n // directives first.\n // directives may mutate the el's other properties before they are generated.\n- var dirs = genDirectives(el);\n+ var dirs = genDirectives(el, state);\n if (dirs) { data += dirs + ','; }\n \n // key\n@@ -2271,8 +2920,8 @@ function genData (el) {\n data += \"tag:\\\"\" + (el.tag) + \"\\\",\";\n }\n // module data generation functions\n- for (var i = 0; i < dataGenFns.length; i++) {\n- data += dataGenFns[i](el);\n+ for (var i = 0; i < state.dataGenFns.length; i++) {\n+ data += state.dataGenFns[i](el);\n }\n // attributes\n if (el.attrs) {\n@@ -2284,26 +2933,26 @@ function genData (el) {\n }\n // event handlers\n if (el.events) {\n- data += (genHandlers(el.events, false, warn$2)) + \",\";\n+ data += (genHandlers(el.events, false, state.warn)) + \",\";\n }\n if (el.nativeEvents) {\n- data += (genHandlers(el.nativeEvents, true, warn$2)) + \",\";\n+ data += (genHandlers(el.nativeEvents, true, state.warn)) + \",\";\n }\n // slot target\n if (el.slotTarget) {\n data += \"slot:\" + (el.slotTarget) + \",\";\n }\n // scoped slots\n if (el.scopedSlots) {\n- data += (genScopedSlots(el.scopedSlots)) + \",\";\n+ data += (genScopedSlots(el.scopedSlots, state)) + \",\";\n }\n // component v-model\n if (el.model) {\n data += \"model:{value:\" + (el.model.value) + \",callback:\" + (el.model.callback) + \",expression:\" + (el.model.expression) + \"},\";\n }\n // inline-template\n if (el.inlineTemplate) {\n- var inlineTemplate = genInlineTemplate(el);\n+ var inlineTemplate = genInlineTemplate(el, state);\n if (inlineTemplate) {\n data += inlineTemplate + \",\";\n }\n@@ -2313,10 +2962,14 @@ function genData (el) {\n if (el.wrapData) {\n data = el.wrapData(data);\n }\n+ // v-on data wrap\n+ if (el.wrapListeners) {\n+ data = el.wrapListeners(data);\n+ }\n return data\n }\n \n-function genDirectives (el) {\n+function genDirectives (el, state) {\n var dirs = el.directives;\n if (!dirs) { return }\n var res = 'directives:[';\n@@ -2325,11 +2978,11 @@ function genDirectives (el) {\n for (i = 0, l = dirs.length; i < l; i++) {\n dir = dirs[i];\n needRuntime = true;\n- var gen = platformDirectives[dir.name] || baseDirectives[dir.name];\n+ var gen = state.directives[dir.name];\n if (gen) {\n // compile-time directive that manipulates AST.\n // returns true if it also needs a runtime counterpart.\n- needRuntime = !!gen(el, dir, warn$2);\n+ needRuntime = !!gen(el, dir, state.warn);\n }\n if (needRuntime) {\n hasRuntime = true;\n@@ -2341,51 +2994,92 @@ function genDirectives (el) {\n }\n }\n \n-function genInlineTemplate (el) {\n+function genInlineTemplate (el, state) {\n var ast = el.children[0];\n if (process.env.NODE_ENV !== 'production' && (\n el.children.length > 1 || ast.type !== 1\n )) {\n- warn$2('Inline-template components must have exactly one child element.');\n+ state.warn('Inline-template components must have exactly one child element.');\n }\n if (ast.type === 1) {\n- var inlineRenderFns = generate(ast, currentOptions);\n+ var inlineRenderFns = generate(ast, state.options);\n return (\"inlineTemplate:{render:function(){\" + (inlineRenderFns.render) + \"},staticRenderFns:[\" + (inlineRenderFns.staticRenderFns.map(function (code) { return (\"function(){\" + code + \"}\"); }).join(',')) + \"]}\")\n }\n }\n \n-function genScopedSlots (slots) {\n- return (\"scopedSlots:_u([\" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + \"])\")\n+function genScopedSlots (\n+ slots,\n+ state\n+) {\n+ return (\"scopedSlots:_u([\" + (Object.keys(slots).map(function (key) {\n+ return genScopedSlot(key, slots[key], state)\n+ }).join(',')) + \"])\")\n }\n \n-function genScopedSlot (key, el) {\n- return \"[\" + key + \",function(\" + (String(el.attrsMap.scope)) + \"){\" +\n+function genScopedSlot (\n+ key,\n+ el,\n+ state\n+) {\n+ if (el.for && !el.forProcessed) {\n+ return genForScopedSlot(key, el, state)\n+ }\n+ return \"{key:\" + key + \",fn:function(\" + (String(el.attrsMap.scope)) + \"){\" +\n \"return \" + (el.tag === 'template'\n- ? genChildren(el) || 'void 0'\n- : genElement(el)) + \"}]\"\n+ ? genChildren(el, state) || 'void 0'\n+ : genElement(el, state)) + \"}}\"\n }\n \n-function genChildren (el, checkSkip) {\n+function genForScopedSlot (\n+ key,\n+ el,\n+ state\n+) {\n+ var exp = el.for;\n+ var alias = el.alias;\n+ var iterator1 = el.iterator1 ? (\",\" + (el.iterator1)) : '';\n+ var iterator2 = el.iterator2 ? (\",\" + (el.iterator2)) : '';\n+ el.forProcessed = true; // avoid recursion\n+ return \"_l((\" + exp + \"),\" +\n+ \"function(\" + alias + iterator1 + iterator2 + \"){\" +\n+ \"return \" + (genScopedSlot(key, el, state)) +\n+ '})'\n+}\n+\n+function genChildren (\n+ el,\n+ state,\n+ checkSkip,\n+ altGenElement,\n+ altGenNode\n+) {\n var children = el.children;\n if (children.length) {\n var el$1 = children[0];\n // optimize single v-for\n if (children.length === 1 &&\n- el$1.for &&\n- el$1.tag !== 'template' &&\n- el$1.tag !== 'slot') {\n- return genElement(el$1)\n+ el$1.for &&\n+ el$1.tag !== 'template' &&\n+ el$1.tag !== 'slot'\n+ ) {\n+ return (altGenElement || genElement)(el$1, state)\n }\n- var normalizationType = checkSkip ? getNormalizationType(children) : 0;\n- return (\"[\" + (children.map(genNode).join(',')) + \"]\" + (normalizationType ? (\",\" + normalizationType) : ''))\n+ var normalizationType = checkSkip\n+ ? getNormalizationType(children, state.maybeComponent)\n+ : 0;\n+ var gen = altGenNode || genNode;\n+ return (\"[\" + (children.map(function (c) { return gen(c, state); }).join(',')) + \"]\" + (normalizationType ? (\",\" + normalizationType) : ''))\n }\n }\n \n // determine the normalization needed for the children array.\n // 0: no normalization needed\n // 1: simple normalization needed (possible 1-level deep nested array)\n // 2: full normalization needed\n-function getNormalizationType (children) {\n+function getNormalizationType (\n+ children,\n+ maybeComponent\n+) {\n var res = 0;\n for (var i = 0; i < children.length; i++) {\n var el = children[i];\n@@ -2409,13 +3103,11 @@ function needsNormalization (el) {\n return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'\n }\n \n-function maybeComponent (el) {\n- return !isPlatformReservedTag$1(el.tag)\n-}\n-\n-function genNode (node) {\n+function genNode (node, state) {\n if (node.type === 1) {\n- return genElement(node)\n+ return genElement(node, state)\n+ } if (node.type === 3 && node.isComment) {\n+ return genComment(node)\n } else {\n return genText(node)\n }\n@@ -2427,9 +3119,13 @@ function genText (text) {\n : transformSpecialNewlines(JSON.stringify(text.text))) + \")\")\n }\n \n-function genSlot (el) {\n+function genComment (comment) {\n+ return (\"_e(\" + (JSON.stringify(comment.text)) + \")\")\n+}\n+\n+function genSlot (el, state) {\n var slotName = el.slotName || '\"default\"';\n- var children = genChildren(el);\n+ var children = genChildren(el, state);\n var res = \"_t(\" + slotName + (children ? (\",\" + children) : '');\n var attrs = el.attrs && (\"{\" + (el.attrs.map(function (a) { return ((camelize(a.name)) + \":\" + (a.value)); }).join(',')) + \"}\");\n var bind$$1 = el.attrsMap['v-bind'];\n@@ -2446,9 +3142,13 @@ function genSlot (el) {\n }\n \n // componentName is el.component, take it as argument to shun flow's pessimistic refinement\n-function genComponent (componentName, el) {\n- var children = el.inlineTemplate ? null : genChildren(el, true);\n- return (\"_c(\" + componentName + \",\" + (genData(el)) + (children ? (\",\" + children) : '') + \")\")\n+function genComponent (\n+ componentName,\n+ el,\n+ state\n+) {\n+ var children = el.inlineTemplate ? null : genChildren(el, state, true);\n+ return (\"_c(\" + componentName + \",\" + (genData(el, state)) + (children ? (\",\" + children) : '') + \")\")\n }\n \n function genProps (props) {\n@@ -2566,21 +3266,7 @@ function checkExpression (exp, text, errors) {\n \n /* */\n \n-function baseCompile (\n- template,\n- options\n-) {\n- var ast = parse(template.trim(), options);\n- optimize(ast, options);\n- var code = generate(ast, options);\n- return {\n- ast: ast,\n- render: code.render,\n- staticRenderFns: code.staticRenderFns\n- }\n-}\n-\n-function makeFunction (code, errors) {\n+function createFunction (code, errors) {\n try {\n return new Function(code)\n } catch (err) {\n@@ -2589,50 +3275,10 @@ function makeFunction (code, errors) {\n }\n }\n \n-function createCompiler (baseOptions) {\n- var functionCompileCache = Object.create(null);\n-\n- function compile (\n- template,\n- options\n- ) {\n- var finalOptions = Object.create(baseOptions);\n- var errors = [];\n- var tips = [];\n- finalOptions.warn = function (msg, tip$$1) {\n- (tip$$1 ? tips : errors).push(msg);\n- };\n-\n- if (options) {\n- // merge custom modules\n- if (options.modules) {\n- finalOptions.modules = (baseOptions.modules || []).concat(options.modules);\n- }\n- // merge custom directives\n- if (options.directives) {\n- finalOptions.directives = extend(\n- Object.create(baseOptions.directives),\n- options.directives\n- );\n- }\n- // copy other options\n- for (var key in options) {\n- if (key !== 'modules' && key !== 'directives') {\n- finalOptions[key] = options[key];\n- }\n- }\n- }\n-\n- var compiled = baseCompile(template, finalOptions);\n- if (process.env.NODE_ENV !== 'production') {\n- errors.push.apply(errors, detectErrors(compiled.ast));\n- }\n- compiled.errors = errors;\n- compiled.tips = tips;\n- return compiled\n- }\n+function createCompileToFunctionFn (compile) {\n+ var cache = Object.create(null);\n \n- function compileToFunctions (\n+ return function compileToFunctions (\n template,\n options,\n vm\n@@ -2661,8 +3307,8 @@ function createCompiler (baseOptions) {\n var key = options.delimiters\n ? String(options.delimiters) + template\n : template;\n- if (functionCompileCache[key]) {\n- return functionCompileCache[key]\n+ if (cache[key]) {\n+ return cache[key]\n }\n \n // compile\n@@ -2685,12 +3331,10 @@ function createCompiler (baseOptions) {\n // turn code into functions\n var res = {};\n var fnGenErrors = [];\n- res.render = makeFunction(compiled.render, fnGenErrors);\n- var l = compiled.staticRenderFns.length;\n- res.staticRenderFns = new Array(l);\n- for (var i = 0; i < l; i++) {\n- res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i], fnGenErrors);\n- }\n+ res.render = createFunction(compiled.render, fnGenErrors);\n+ res.staticRenderFns = compiled.staticRenderFns.map(function (code) {\n+ return createFunction(code, fnGenErrors)\n+ });\n \n // check function generation errors.\n // this should only happen if there is a bug in the compiler itself.\n@@ -2711,17 +3355,83 @@ function createCompiler (baseOptions) {\n }\n }\n \n- return (functionCompileCache[key] = res)\n+ return (cache[key] = res)\n }\n+}\n \n- return {\n- compile: compile,\n- compileToFunctions: compileToFunctions\n+/* */\n+\n+function createCompilerCreator (baseCompile) {\n+ return function createCompiler (baseOptions) {\n+ function compile (\n+ template,\n+ options\n+ ) {\n+ var finalOptions = Object.create(baseOptions);\n+ var errors = [];\n+ var tips = [];\n+ finalOptions.warn = function (msg, tip) {\n+ (tip ? tips : errors).push(msg);\n+ };\n+\n+ if (options) {\n+ // merge custom modules\n+ if (options.modules) {\n+ finalOptions.modules =\n+ (baseOptions.modules || []).concat(options.modules);\n+ }\n+ // merge custom directives\n+ if (options.directives) {\n+ finalOptions.directives = extend(\n+ Object.create(baseOptions.directives),\n+ options.directives\n+ );\n+ }\n+ // copy other options\n+ for (var key in options) {\n+ if (key !== 'modules' && key !== 'directives') {\n+ finalOptions[key] = options[key];\n+ }\n+ }\n+ }\n+\n+ var compiled = baseCompile(template, finalOptions);\n+ if (process.env.NODE_ENV !== 'production') {\n+ errors.push.apply(errors, detectErrors(compiled.ast));\n+ }\n+ compiled.errors = errors;\n+ compiled.tips = tips;\n+ return compiled\n+ }\n+\n+ return {\n+ compile: compile,\n+ compileToFunctions: createCompileToFunctionFn(compile)\n+ }\n }\n }\n \n /* */\n \n+// `createCompilerCreator` allows creating compilers that use alternative\n+// parser/optimizer/codegen, e.g the SSR optimizing compiler.\n+// Here we just export a default compiler using the default parts.\n+var createCompiler = createCompilerCreator(function baseCompile (\n+ template,\n+ options\n+) {\n+ var ast = parse(template.trim(), options);\n+ optimize(ast, options);\n+ var code = generate(ast, options);\n+ return {\n+ ast: ast,\n+ render: code.render,\n+ staticRenderFns: code.staticRenderFns\n+ }\n+});\n+\n+/* */\n+\n function transformNode (el, options) {\n var warn = options.warn || baseWarn;\n var staticClass = getAndRemoveAttr(el, 'class');\n@@ -2860,7 +3570,7 @@ var style = {\n \n var normalize$1 = cached(camelize);\n \n-function normalizeKeyName (str) {\n+function normalizeKeyName (str) {\n if (str.match(/^v\\-/)) {\n return str.replace(/(v-[a-z\\-]+\\:)([a-z\\-]+)$/i, function ($, directive, prop) {\n return directive + normalize$1(prop)",
"filename": "packages/weex-template-compiler/build.js",
"status": "modified"
},
{
"diff": "@@ -1,6 +1,6 @@\n {\n \"name\": \"weex-template-compiler\",\n- \"version\": \"2.1.9-weex.1\",\n+ \"version\": \"2.4.2-weex.1\",\n \"description\": \"Weex template compiler for Vue 2.0\",\n \"main\": \"index.js\",\n \"repository\": {",
"filename": "packages/weex-template-compiler/package.json",
"status": "modified"
},
{
"diff": "@@ -18,11 +18,19 @@ function isTrue (v) {\n return v === true\n }\n \n+function isFalse (v) {\n+ return v === false\n+}\n+\n /**\n * Check if value is primitive\n */\n function isPrimitive (value) {\n- return typeof value === 'string' || typeof value === 'number'\n+ return (\n+ typeof value === 'string' ||\n+ typeof value === 'number' ||\n+ typeof value === 'boolean'\n+ )\n }\n \n /**\n@@ -34,24 +42,32 @@ function isObject (obj) {\n return obj !== null && typeof obj === 'object'\n }\n \n-var toString = Object.prototype.toString;\n+var _toString = Object.prototype.toString;\n \n /**\n * Strict object type check. Only returns true\n * for plain JavaScript objects.\n */\n function isPlainObject (obj) {\n- return toString.call(obj) === '[object Object]'\n+ return _toString.call(obj) === '[object Object]'\n }\n \n function isRegExp (v) {\n- return toString.call(v) === '[object RegExp]'\n+ return _toString.call(v) === '[object RegExp]'\n+}\n+\n+/**\n+ * Check if val is a valid array index.\n+ */\n+function isValidArrayIndex (val) {\n+ var n = parseFloat(val);\n+ return n >= 0 && Math.floor(n) === n && isFinite(val)\n }\n \n /**\n * Convert a value to a string that is actually rendered.\n */\n-function _toString (val) {\n+function toString (val) {\n return val == null\n ? ''\n : typeof val === 'object'\n@@ -91,6 +107,11 @@ function makeMap (\n */\n var isBuiltInTag = makeMap('slot,component', true);\n \n+/**\n+ * Check if a attribute is a reserved attribute.\n+ */\n+var isReservedAttribute = makeMap('key,ref,slot,is');\n+\n /**\n * Remove an item from an array\n */\n@@ -203,13 +224,15 @@ function toObject (arr) {\n \n /**\n * Perform no operation.\n+ * Stubbing args to make Flow happy without leaving useless transpiled code\n+ * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/)\n */\n-function noop () {}\n+function noop (a, b, c) {}\n \n /**\n * Always return false.\n */\n-var no = function () { return false; };\n+var no = function (a, b, c) { return false; };\n \n /**\n * Return same value\n@@ -226,14 +249,30 @@ var identity = function (_) { return _; };\n * if they are plain objects, do they have the same shape?\n */\n function looseEqual (a, b) {\n+ if (a === b) { return true }\n var isObjectA = isObject(a);\n var isObjectB = isObject(b);\n if (isObjectA && isObjectB) {\n try {\n- return JSON.stringify(a) === JSON.stringify(b)\n+ var isArrayA = Array.isArray(a);\n+ var isArrayB = Array.isArray(b);\n+ if (isArrayA && isArrayB) {\n+ return a.length === b.length && a.every(function (e, i) {\n+ return looseEqual(e, b[i])\n+ })\n+ } else if (!isArrayA && !isArrayB) {\n+ var keysA = Object.keys(a);\n+ var keysB = Object.keys(b);\n+ return keysA.length === keysB.length && keysA.every(function (key) {\n+ return looseEqual(a[key], b[key])\n+ })\n+ } else {\n+ /* istanbul ignore next */\n+ return false\n+ }\n } catch (e) {\n- // possible circular reference\n- return a === b\n+ /* istanbul ignore next */\n+ return false\n }\n } else if (!isObjectA && !isObjectB) {\n return String(a) === String(b)\n@@ -316,6 +355,11 @@ var config = ({\n */\n errorHandler: null,\n \n+ /**\n+ * Warn handler for watcher warns\n+ */\n+ warnHandler: null,\n+\n /**\n * Ignore certain custom elements\n */\n@@ -408,9 +452,11 @@ function parsePath (path) {\n }\n }\n \n+/* */\n+\n var warn = noop;\n var tip = noop;\n-var formatComponentName;\n+var formatComponentName = (null); // work around flow check\n \n if (process.env.NODE_ENV !== 'production') {\n var hasConsole = typeof console !== 'undefined';\n@@ -420,10 +466,12 @@ if (process.env.NODE_ENV !== 'production') {\n .replace(/[-_]/g, ''); };\n \n warn = function (msg, vm) {\n- if (hasConsole && (!config.silent)) {\n- console.error(\"[Vue warn]: \" + msg + (\n- vm ? generateComponentTrace(vm) : ''\n- ));\n+ var trace = vm ? generateComponentTrace(vm) : '';\n+\n+ if (config.warnHandler) {\n+ config.warnHandler.call(null, msg, vm, trace);\n+ } else if (hasConsole && (!config.silent)) {\n+ console.error((\"[Vue warn]: \" + msg + trace));\n }\n };\n \n@@ -499,6 +547,8 @@ if (process.env.NODE_ENV !== 'production') {\n };\n }\n \n+/* */\n+\n function handleError (err, vm, info) {\n if (config.errorHandler) {\n config.errorHandler.call(null, err, vm, info);\n@@ -531,6 +581,9 @@ var isAndroid = UA && UA.indexOf('android') > 0;\n var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);\n var isChrome = UA && /chrome\\/\\d+/.test(UA) && !isEdge;\n \n+// Firefix has a \"watch\" function on Object.prototype...\n+var nativeWatch = ({}).watch;\n+\n var supportsPassive = false;\n if (inBrowser) {\n try {\n@@ -540,7 +593,7 @@ if (inBrowser) {\n /* istanbul ignore next */\n supportsPassive = true;\n }\n- } )); // https://github.com/facebook/flow/issues/285\n+ })); // https://github.com/facebook/flow/issues/285\n window.addEventListener('test-passive', null, opts);\n } catch (e) {}\n }\n@@ -755,22 +808,14 @@ var arrayMethods = Object.create(arrayProto);[\n // cache original method\n var original = arrayProto[method];\n def(arrayMethods, method, function mutator () {\n- var arguments$1 = arguments;\n+ var args = [], len = arguments.length;\n+ while ( len-- ) args[ len ] = arguments[ len ];\n \n- // avoid leaking arguments:\n- // http://jsperf.com/closure-with-arguments\n- var i = arguments.length;\n- var args = new Array(i);\n- while (i--) {\n- args[i] = arguments$1[i];\n- }\n var result = original.apply(this, args);\n var ob = this.__ob__;\n var inserted;\n switch (method) {\n case 'push':\n- inserted = args;\n- break\n case 'unshift':\n inserted = args;\n break\n@@ -796,8 +841,7 @@ var arrayKeys = Object.getOwnPropertyNames(arrayMethods);\n * under a frozen data structure. Converting it would defeat the optimization.\n */\n var observerState = {\n- shouldConvert: true,\n- isSettingProps: false\n+ shouldConvert: true\n };\n \n /**\n@@ -849,7 +893,7 @@ Observer.prototype.observeArray = function observeArray (items) {\n * Augment an target Object or Array by intercepting\n * the prototype chain using __proto__\n */\n-function protoAugment (target, src) {\n+function protoAugment (target, src, keys) {\n /* eslint-disable no-proto */\n target.__proto__ = src;\n /* eslint-enable no-proto */\n@@ -901,7 +945,8 @@ function defineReactive$$1 (\n obj,\n key,\n val,\n- customSetter\n+ customSetter,\n+ shallow\n ) {\n var dep = new Dep();\n \n@@ -914,7 +959,7 @@ function defineReactive$$1 (\n var getter = property && property.get;\n var setter = property && property.set;\n \n- var childOb = observe(val);\n+ var childOb = !shallow && observe(val);\n Object.defineProperty(obj, key, {\n enumerable: true,\n configurable: true,\n@@ -946,7 +991,7 @@ function defineReactive$$1 (\n } else {\n val = newVal;\n }\n- childOb = observe(newVal);\n+ childOb = !shallow && observe(newVal);\n dep.notify();\n }\n });\n@@ -958,7 +1003,7 @@ function defineReactive$$1 (\n * already exist.\n */\n function set (target, key, val) {\n- if (Array.isArray(target) && typeof key === 'number') {\n+ if (Array.isArray(target) && isValidArrayIndex(key)) {\n target.length = Math.max(target.length, key);\n target.splice(key, 1, val);\n return val\n@@ -967,7 +1012,7 @@ function set (target, key, val) {\n target[key] = val;\n return val\n }\n- var ob = (target ).__ob__;\n+ var ob = (target).__ob__;\n if (target._isVue || (ob && ob.vmCount)) {\n process.env.NODE_ENV !== 'production' && warn(\n 'Avoid adding reactive properties to a Vue instance or its root $data ' +\n@@ -988,11 +1033,11 @@ function set (target, key, val) {\n * Delete a property and trigger change if necessary.\n */\n function del (target, key) {\n- if (Array.isArray(target) && typeof key === 'number') {\n+ if (Array.isArray(target) && isValidArrayIndex(key)) {\n target.splice(key, 1);\n return\n }\n- var ob = (target ).__ob__;\n+ var ob = (target).__ob__;\n if (target._isVue || (ob && ob.vmCount)) {\n process.env.NODE_ENV !== 'production' && warn(\n 'Avoid deleting properties on a Vue instance or its root $data ' +\n@@ -1071,7 +1116,7 @@ function mergeData (to, from) {\n /**\n * Data\n */\n-strats.data = function (\n+function mergeDataOrFn (\n parentVal,\n childVal,\n vm\n@@ -1081,15 +1126,6 @@ strats.data = function (\n if (!childVal) {\n return parentVal\n }\n- if (typeof childVal !== 'function') {\n- process.env.NODE_ENV !== 'production' && warn(\n- 'The \"data\" option should be a function ' +\n- 'that returns a per-instance value in component ' +\n- 'definitions.',\n- vm\n- );\n- return parentVal\n- }\n if (!parentVal) {\n return childVal\n }\n@@ -1100,8 +1136,8 @@ strats.data = function (\n // it has to be a function to pass previous merges.\n return function mergedDataFn () {\n return mergeData(\n- childVal.call(this),\n- parentVal.call(this)\n+ typeof childVal === 'function' ? childVal.call(this) : childVal,\n+ typeof parentVal === 'function' ? parentVal.call(this) : parentVal\n )\n }\n } else if (parentVal || childVal) {\n@@ -1120,6 +1156,28 @@ strats.data = function (\n }\n }\n }\n+}\n+\n+strats.data = function (\n+ parentVal,\n+ childVal,\n+ vm\n+) {\n+ if (!vm) {\n+ if (childVal && typeof childVal !== 'function') {\n+ process.env.NODE_ENV !== 'production' && warn(\n+ 'The \"data\" option should be a function ' +\n+ 'that returns a per-instance value in component ' +\n+ 'definitions.',\n+ vm\n+ );\n+\n+ return parentVal\n+ }\n+ return mergeDataOrFn.call(this, parentVal, childVal)\n+ }\n+\n+ return mergeDataOrFn(parentVal, childVal, vm)\n };\n \n /**\n@@ -1167,6 +1225,9 @@ ASSET_TYPES.forEach(function (type) {\n * another, so we merge them as arrays.\n */\n strats.watch = function (parentVal, childVal) {\n+ // work around Firefox's Object.prototype.watch...\n+ if (parentVal === nativeWatch) { parentVal = undefined; }\n+ if (childVal === nativeWatch) { childVal = undefined; }\n /* istanbul ignore if */\n if (!childVal) { return Object.create(parentVal || null) }\n if (!parentVal) { return childVal }\n@@ -1180,7 +1241,7 @@ strats.watch = function (parentVal, childVal) {\n }\n ret[key] = parent\n ? parent.concat(child)\n- : [child];\n+ : Array.isArray(child) ? child : [child];\n }\n return ret\n };\n@@ -1190,14 +1251,15 @@ strats.watch = function (parentVal, childVal) {\n */\n strats.props =\n strats.methods =\n+strats.inject =\n strats.computed = function (parentVal, childVal) {\n- if (!childVal) { return Object.create(parentVal || null) }\n if (!parentVal) { return childVal }\n var ret = Object.create(null);\n extend(ret, parentVal);\n- extend(ret, childVal);\n+ if (childVal) { extend(ret, childVal); }\n return ret\n };\n+strats.provide = mergeDataOrFn;\n \n /**\n * Default strategy.\n@@ -1255,6 +1317,19 @@ function normalizeProps (options) {\n options.props = res;\n }\n \n+/**\n+ * Normalize all injections into Object-based format\n+ */\n+function normalizeInject (options) {\n+ var inject = options.inject;\n+ if (Array.isArray(inject)) {\n+ var normalized = options.inject = {};\n+ for (var i = 0; i < inject.length; i++) {\n+ normalized[inject[i]] = inject[i];\n+ }\n+ }\n+}\n+\n /**\n * Normalize raw function directives into object format.\n */\n@@ -1288,6 +1363,7 @@ function mergeOptions (\n }\n \n normalizeProps(child);\n+ normalizeInject(child);\n normalizeDirectives(child);\n var extendsFrom = child.extends;\n if (extendsFrom) {\n@@ -1405,7 +1481,8 @@ function getPropDefaultValue (vm, prop, key) {\n // return previous default value to avoid unnecessary watcher trigger\n if (vm && vm.$options.propsData &&\n vm.$options.propsData[key] === undefined &&\n- vm._props[key] !== undefined) {\n+ vm._props[key] !== undefined\n+ ) {\n return vm._props[key]\n }\n // call factory function for non-Function types\n@@ -1511,6 +1588,8 @@ function isType (type, fn) {\n return false\n }\n \n+/* */\n+\n /* not type checking this file because flow doesn't play well with Proxy */\n \n var initProxy;\n@@ -1617,7 +1696,8 @@ var VNode = function VNode (\n text,\n elm,\n context,\n- componentOptions\n+ componentOptions,\n+ asyncFactory\n ) {\n this.tag = tag;\n this.data = data;\n@@ -1637,6 +1717,9 @@ var VNode = function VNode (\n this.isComment = false;\n this.isCloned = false;\n this.isOnce = false;\n+ this.asyncFactory = asyncFactory;\n+ this.asyncMeta = undefined;\n+ this.isAsyncPlaceholder = false;\n };\n \n var prototypeAccessors = { child: {} };\n@@ -1649,9 +1732,11 @@ prototypeAccessors.child.get = function () {\n \n Object.defineProperties( VNode.prototype, prototypeAccessors );\n \n-var createEmptyVNode = function () {\n+var createEmptyVNode = function (text) {\n+ if ( text === void 0 ) text = '';\n+\n var node = new VNode();\n- node.text = '';\n+ node.text = text;\n node.isComment = true;\n return node\n };\n@@ -1672,11 +1757,13 @@ function cloneVNode (vnode) {\n vnode.text,\n vnode.elm,\n vnode.context,\n- vnode.componentOptions\n+ vnode.componentOptions,\n+ vnode.asyncFactory\n );\n cloned.ns = vnode.ns;\n cloned.isStatic = vnode.isStatic;\n cloned.key = vnode.key;\n+ cloned.isComment = vnode.isComment;\n cloned.isCloned = true;\n return cloned\n }\n@@ -1713,8 +1800,9 @@ function createFnInvoker (fns) {\n \n var fns = invoker.fns;\n if (Array.isArray(fns)) {\n- for (var i = 0; i < fns.length; i++) {\n- fns[i].apply(null, arguments$1);\n+ var cloned = fns.slice();\n+ for (var i = 0; i < cloned.length; i++) {\n+ cloned[i].apply(null, arguments$1);\n }\n } else {\n // return handler return value for single handlers\n@@ -1895,6 +1983,10 @@ function normalizeChildren (children) {\n : undefined\n }\n \n+function isTextNode (node) {\n+ return isDef(node) && isDef(node.text) && isFalse(node.isComment)\n+}\n+\n function normalizeArrayChildren (children, nestedIndex) {\n var res = [];\n var i, c, last;\n@@ -1906,19 +1998,26 @@ function normalizeArrayChildren (children, nestedIndex) {\n if (Array.isArray(c)) {\n res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + \"_\" + i)));\n } else if (isPrimitive(c)) {\n- if (isDef(last) && isDef(last.text)) {\n+ if (isTextNode(last)) {\n+ // merge adjacent text nodes\n+ // this is necessary for SSR hydration because text nodes are\n+ // essentially merged when rendered to HTML strings\n (last).text += String(c);\n } else if (c !== '') {\n // convert primitive to vnode\n res.push(createTextVNode(c));\n }\n } else {\n- if (isDef(c.text) && isDef(last) && isDef(last.text)) {\n+ if (isTextNode(c) && isTextNode(last)) {\n+ // merge adjacent text nodes\n res[res.length - 1] = createTextVNode(last.text + c.text);\n } else {\n // default key for nested array children (likely generated by v-for)\n- if (isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) {\n- c.key = \"__vlist\" + ((nestedIndex)) + \"_\" + i + \"__\";\n+ if (isTrue(children._isVList) &&\n+ isDef(c.tag) &&\n+ isUndef(c.key) &&\n+ isDef(nestedIndex)) {\n+ c.key = \"__vlist\" + nestedIndex + \"_\" + i + \"__\";\n }\n res.push(c);\n }\n@@ -1930,11 +2029,27 @@ function normalizeArrayChildren (children, nestedIndex) {\n /* */\n \n function ensureCtor (comp, base) {\n+ if (comp.__esModule && comp.default) {\n+ comp = comp.default;\n+ }\n return isObject(comp)\n ? base.extend(comp)\n : comp\n }\n \n+function createAsyncPlaceholder (\n+ factory,\n+ data,\n+ context,\n+ children,\n+ tag\n+) {\n+ var node = createEmptyVNode();\n+ node.asyncFactory = factory;\n+ node.asyncMeta = { data: data, context: context, children: children, tag: tag };\n+ return node\n+}\n+\n function resolveAsyncComponent (\n factory,\n baseCtor,\n@@ -2017,11 +2132,13 @@ function resolveAsyncComponent (\n \n if (isDef(res.timeout)) {\n setTimeout(function () {\n- reject(\n- process.env.NODE_ENV !== 'production'\n- ? (\"timeout (\" + (res.timeout) + \"ms)\")\n- : null\n- );\n+ if (isUndef(factory.resolved)) {\n+ reject(\n+ process.env.NODE_ENV !== 'production'\n+ ? (\"timeout (\" + (res.timeout) + \"ms)\")\n+ : null\n+ );\n+ }\n }, res.timeout);\n }\n }\n@@ -2174,7 +2291,11 @@ function eventsMixin (Vue) {\n cbs = cbs.length > 1 ? toArray(cbs) : cbs;\n var args = toArray(arguments, 1);\n for (var i = 0, l = cbs.length; i < l; i++) {\n- cbs[i].apply(vm, args);\n+ try {\n+ cbs[i].apply(vm, args);\n+ } catch (e) {\n+ handleError(e, vm, (\"event handler for \\\"\" + event + \"\\\"\"));\n+ }\n }\n }\n return vm\n@@ -2200,7 +2321,8 @@ function resolveSlots (\n // named slots should only be respected if the vnode was rendered in the\n // same context.\n if ((child.context === context || child.functionalContext === context) &&\n- child.data && child.data.slot != null) {\n+ child.data && child.data.slot != null\n+ ) {\n var name = child.data.slot;\n var slot = (slots[name] || (slots[name] = []));\n if (child.tag === 'template') {\n@@ -2224,18 +2346,24 @@ function isWhitespace (node) {\n }\n \n function resolveScopedSlots (\n- fns\n+ fns, // see flow/vnode\n+ res\n ) {\n- var res = {};\n+ res = res || {};\n for (var i = 0; i < fns.length; i++) {\n- res[fns[i][0]] = fns[i][1];\n+ if (Array.isArray(fns[i])) {\n+ resolveScopedSlots(fns[i], res);\n+ } else {\n+ res[fns[i].key] = fns[i].fn;\n+ }\n }\n return res\n }\n \n /* */\n \n var activeInstance = null;\n+var isUpdatingChildComponent = false;\n \n function initLifecycle (vm) {\n var options = vm.$options;\n@@ -2283,6 +2411,9 @@ function lifecycleMixin (Vue) {\n vm.$options._parentElm,\n vm.$options._refElm\n );\n+ // no need for the ref nodes after initial patch\n+ // this prevents keeping a detached DOM tree in memory (#5851)\n+ vm.$options._parentElm = vm.$options._refElm = null;\n } else {\n // updates\n vm.$el = vm.__patch__(prevVnode, vnode);\n@@ -2347,8 +2478,6 @@ function lifecycleMixin (Vue) {\n if (vm.$el) {\n vm.$el.__vue__ = null;\n }\n- // remove reference to DOM nodes (prevents leak)\n- vm.$options._parentElm = vm.$options._refElm = null;\n };\n }\n \n@@ -2424,6 +2553,10 @@ function updateChildComponent (\n parentVnode,\n renderChildren\n ) {\n+ if (process.env.NODE_ENV !== 'production') {\n+ isUpdatingChildComponent = true;\n+ }\n+\n // determine whether component has slot children\n // we need to do this before overwriting $options._renderChildren\n var hasChildren = !!(\n@@ -2435,30 +2568,32 @@ function updateChildComponent (\n \n vm.$options._parentVnode = parentVnode;\n vm.$vnode = parentVnode; // update vm's placeholder node without re-render\n+\n if (vm._vnode) { // update child tree's parent\n vm._vnode.parent = parentVnode;\n }\n vm.$options._renderChildren = renderChildren;\n \n+ // update $attrs and $listensers hash\n+ // these are also reactive so they may trigger child update if the child\n+ // used them during render\n+ vm.$attrs = parentVnode.data && parentVnode.data.attrs;\n+ vm.$listeners = listeners;\n+\n // update props\n if (propsData && vm.$options.props) {\n observerState.shouldConvert = false;\n- if (process.env.NODE_ENV !== 'production') {\n- observerState.isSettingProps = true;\n- }\n var props = vm._props;\n var propKeys = vm.$options._propKeys || [];\n for (var i = 0; i < propKeys.length; i++) {\n var key = propKeys[i];\n props[key] = validateProp(key, vm.$options.props, propsData, vm);\n }\n observerState.shouldConvert = true;\n- if (process.env.NODE_ENV !== 'production') {\n- observerState.isSettingProps = false;\n- }\n // keep a copy of raw propsData\n vm.$options.propsData = propsData;\n }\n+\n // update listeners\n if (listeners) {\n var oldListeners = vm.$options._parentListeners;\n@@ -2470,6 +2605,10 @@ function updateChildComponent (\n vm.$slots = resolveSlots(renderChildren, parentVnode.context);\n vm.$forceUpdate();\n }\n+\n+ if (process.env.NODE_ENV !== 'production') {\n+ isUpdatingChildComponent = false;\n+ }\n }\n \n function isInInactiveTree (vm) {\n@@ -2546,7 +2685,7 @@ var index = 0;\n * Reset the scheduler's state.\n */\n function resetSchedulerState () {\n- queue.length = activatedChildren.length = 0;\n+ index = queue.length = activatedChildren.length = 0;\n has = {};\n if (process.env.NODE_ENV !== 'production') {\n circular = {};\n@@ -2603,7 +2742,7 @@ function flushSchedulerQueue () {\n \n // call component updated and activated hooks\n callActivatedHooks(activatedQueue);\n- callUpdateHooks(updatedQueue);\n+ callUpdatedHooks(updatedQueue);\n \n // devtool hook\n /* istanbul ignore if */\n@@ -2612,7 +2751,7 @@ function flushSchedulerQueue () {\n }\n }\n \n-function callUpdateHooks (queue) {\n+function callUpdatedHooks (queue) {\n var i = queue.length;\n while (i--) {\n var watcher = queue[i];\n@@ -2656,10 +2795,10 @@ function queueWatcher (watcher) {\n // if already flushing, splice the watcher based on its id\n // if already past its id, it will be run next immediately.\n var i = queue.length - 1;\n- while (i >= 0 && queue[i].id > watcher.id) {\n+ while (i > index && queue[i].id > watcher.id) {\n i--;\n }\n- queue.splice(Math.max(i, index) + 1, 0, watcher);\n+ queue.splice(i + 1, 0, watcher);\n }\n // queue the flush\n if (!waiting) {\n@@ -2733,22 +2872,23 @@ Watcher.prototype.get = function get () {\n pushTarget(this);\n var value;\n var vm = this.vm;\n- if (this.user) {\n- try {\n- value = this.getter.call(vm, vm);\n- } catch (e) {\n+ try {\n+ value = this.getter.call(vm, vm);\n+ } catch (e) {\n+ if (this.user) {\n handleError(e, vm, (\"getter for watcher \\\"\" + (this.expression) + \"\\\"\"));\n+ } else {\n+ throw e\n }\n- } else {\n- value = this.getter.call(vm, vm);\n- }\n- // \"touch\" every property so they are all tracked as\n- // dependencies for deep watching\n- if (this.deep) {\n- traverse(value);\n+ } finally {\n+ // \"touch\" every property so they are all tracked as\n+ // dependencies for deep watching\n+ if (this.deep) {\n+ traverse(value);\n+ }\n+ popTarget();\n+ this.cleanupDeps();\n }\n- popTarget();\n- this.cleanupDeps();\n return value\n };\n \n@@ -2941,14 +3081,20 @@ function initState (vm) {\n observe(vm._data = {}, true /* asRootData */);\n }\n if (opts.computed) { initComputed(vm, opts.computed); }\n- if (opts.watch) { initWatch(vm, opts.watch); }\n+ if (opts.watch && opts.watch !== nativeWatch) {\n+ initWatch(vm, opts.watch);\n+ }\n }\n \n-var isReservedProp = {\n- key: 1,\n- ref: 1,\n- slot: 1\n-};\n+function checkOptionType (vm, name) {\n+ var option = vm.$options[name];\n+ if (!isPlainObject(option)) {\n+ warn(\n+ (\"component option \\\"\" + name + \"\\\" should be an object.\"),\n+ vm\n+ );\n+ }\n+}\n \n function initProps (vm, propsOptions) {\n var propsData = vm.$options.propsData || {};\n@@ -2964,14 +3110,14 @@ function initProps (vm, propsOptions) {\n var value = validateProp(key, propsOptions, propsData, vm);\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n- if (isReservedProp[key] || config.isReservedAttr(key)) {\n+ if (isReservedAttribute(key) || config.isReservedAttr(key)) {\n warn(\n (\"\\\"\" + key + \"\\\" is a reserved attribute and cannot be used as component prop.\"),\n vm\n );\n }\n defineReactive$$1(props, key, value, function () {\n- if (vm.$parent && !observerState.isSettingProps) {\n+ if (vm.$parent && !isUpdatingChildComponent) {\n warn(\n \"Avoid mutating a prop directly since the value will be \" +\n \"overwritten whenever the parent component re-renders. \" +\n@@ -3012,16 +3158,26 @@ function initData (vm) {\n // proxy data on instance\n var keys = Object.keys(data);\n var props = vm.$options.props;\n+ var methods = vm.$options.methods;\n var i = keys.length;\n while (i--) {\n- if (props && hasOwn(props, keys[i])) {\n+ var key = keys[i];\n+ if (process.env.NODE_ENV !== 'production') {\n+ if (methods && hasOwn(methods, key)) {\n+ warn(\n+ (\"method \\\"\" + key + \"\\\" has already been defined as a data property.\"),\n+ vm\n+ );\n+ }\n+ }\n+ if (props && hasOwn(props, key)) {\n process.env.NODE_ENV !== 'production' && warn(\n- \"The data property \\\"\" + (keys[i]) + \"\\\" is already declared as a prop. \" +\n+ \"The data property \\\"\" + key + \"\\\" is already declared as a prop. \" +\n \"Use prop default value instead.\",\n vm\n );\n- } else if (!isReserved(keys[i])) {\n- proxy(vm, \"_data\", keys[i]);\n+ } else if (!isReserved(key)) {\n+ proxy(vm, \"_data\", key);\n }\n }\n // observe data\n@@ -3040,22 +3196,20 @@ function getData (data, vm) {\n var computedWatcherOptions = { lazy: true };\n \n function initComputed (vm, computed) {\n+ process.env.NODE_ENV !== 'production' && checkOptionType(vm, 'computed');\n var watchers = vm._computedWatchers = Object.create(null);\n \n for (var key in computed) {\n var userDef = computed[key];\n var getter = typeof userDef === 'function' ? userDef : userDef.get;\n- if (process.env.NODE_ENV !== 'production') {\n- if (getter === undefined) {\n- warn(\n- (\"No getter function has been defined for computed property \\\"\" + key + \"\\\".\"),\n- vm\n- );\n- getter = noop;\n- }\n+ if (process.env.NODE_ENV !== 'production' && getter == null) {\n+ warn(\n+ (\"Getter is missing for computed property \\\"\" + key + \"\\\".\"),\n+ vm\n+ );\n }\n // create internal watcher for the computed property.\n- watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions);\n+ watchers[key] = new Watcher(vm, getter || noop, noop, computedWatcherOptions);\n \n // component-defined computed properties are already defined on the\n // component prototype. We only need to define computed properties defined\n@@ -3086,6 +3240,15 @@ function defineComputed (target, key, userDef) {\n ? userDef.set\n : noop;\n }\n+ if (process.env.NODE_ENV !== 'production' &&\n+ sharedPropertyDefinition.set === noop) {\n+ sharedPropertyDefinition.set = function () {\n+ warn(\n+ (\"Computed property \\\"\" + key + \"\\\" was assigned to but it has no setter.\"),\n+ this\n+ );\n+ };\n+ }\n Object.defineProperty(target, key, sharedPropertyDefinition);\n }\n \n@@ -3105,6 +3268,7 @@ function createComputedGetter (key) {\n }\n \n function initMethods (vm, methods) {\n+ process.env.NODE_ENV !== 'production' && checkOptionType(vm, 'methods');\n var props = vm.$options.props;\n for (var key in methods) {\n vm[key] = methods[key] == null ? noop : bind(methods[key], vm);\n@@ -3127,6 +3291,7 @@ function initMethods (vm, methods) {\n }\n \n function initWatch (vm, watch) {\n+ process.env.NODE_ENV !== 'production' && checkOptionType(vm, 'watch');\n for (var key in watch) {\n var handler = watch[key];\n if (Array.isArray(handler)) {\n@@ -3139,16 +3304,20 @@ function initWatch (vm, watch) {\n }\n }\n \n-function createWatcher (vm, key, handler) {\n- var options;\n+function createWatcher (\n+ vm,\n+ keyOrFn,\n+ handler,\n+ options\n+) {\n if (isPlainObject(handler)) {\n options = handler;\n handler = handler.handler;\n }\n if (typeof handler === 'string') {\n handler = vm[handler];\n }\n- vm.$watch(key, handler, options);\n+ return vm.$watch(keyOrFn, handler, options)\n }\n \n function stateMixin (Vue) {\n@@ -3183,6 +3352,9 @@ function stateMixin (Vue) {\n options\n ) {\n var vm = this;\n+ if (isPlainObject(cb)) {\n+ return createWatcher(vm, expOrFn, cb, options)\n+ }\n options = options || {};\n options.user = true;\n var watcher = new Watcher(vm, expOrFn, cb, options);\n@@ -3209,6 +3381,7 @@ function initProvide (vm) {\n function initInjections (vm) {\n var result = resolveInject(vm.$options.inject, vm);\n if (result) {\n+ observerState.shouldConvert = false;\n Object.keys(result).forEach(function (key) {\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n@@ -3224,24 +3397,21 @@ function initInjections (vm) {\n defineReactive$$1(vm, key, result[key]);\n }\n });\n+ observerState.shouldConvert = true;\n }\n }\n \n function resolveInject (inject, vm) {\n if (inject) {\n // inject is :any because flow is not smart enough to figure out cached\n- // isArray here\n- var isArray = Array.isArray(inject);\n var result = Object.create(null);\n- var keys = isArray\n- ? inject\n- : hasSymbol\n+ var keys = hasSymbol\n ? Reflect.ownKeys(inject)\n : Object.keys(inject);\n \n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n- var provideKey = isArray ? key : inject[key];\n+ var provideKey = inject[key];\n var source = vm;\n while (source) {\n if (source._provided && provideKey in source._provided) {\n@@ -3250,6 +3420,9 @@ function resolveInject (inject, vm) {\n }\n source = source.$parent;\n }\n+ if (process.env.NODE_ENV !== 'production' && !source) {\n+ warn((\"Injection \\\"\" + key + \"\\\" not found\"), vm);\n+ }\n }\n return result\n }\n@@ -3268,7 +3441,7 @@ function createFunctionalComponent (\n var propOptions = Ctor.options.props;\n if (isDef(propOptions)) {\n for (var key in propOptions) {\n- props[key] = validateProp(key, propOptions, propsData);\n+ props[key] = validateProp(key, propOptions, propsData || {});\n }\n } else {\n if (isDef(data.attrs)) { mergeProps(props, data.attrs); }\n@@ -3289,6 +3462,7 @@ function createFunctionalComponent (\n });\n if (vnode instanceof VNode) {\n vnode.functionalContext = context;\n+ vnode.functionalOptions = Ctor.options;\n if (data.slot) {\n (vnode.data || (vnode.data = {})).slot = data.slot;\n }\n@@ -3402,21 +3576,30 @@ function createComponent (\n }\n \n // async component\n+ var asyncFactory;\n if (isUndef(Ctor.cid)) {\n- Ctor = resolveAsyncComponent(Ctor, baseCtor, context);\n+ asyncFactory = Ctor;\n+ Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context);\n if (Ctor === undefined) {\n- // return nothing if this is indeed an async component\n- // wait for the callback to trigger parent update.\n- return\n+ // return a placeholder node for async component, which is rendered\n+ // as a comment node but preserves all the raw information for the node.\n+ // the information will be used for async server-rendering and hydration.\n+ return createAsyncPlaceholder(\n+ asyncFactory,\n+ data,\n+ context,\n+ children,\n+ tag\n+ )\n }\n }\n \n+ data = data || {};\n+\n // resolve constructor options in case global mixins are applied after\n // component constructor creation\n resolveConstructorOptions(Ctor);\n \n- data = data || {};\n-\n // transform component v-model data into props & events\n if (isDef(data.model)) {\n transformModel(Ctor.options, data);\n@@ -3434,12 +3617,19 @@ function createComponent (\n // child component listeners instead of DOM listeners\n var listeners = data.on;\n // replace with listeners with .native modifier\n+ // so it gets processed during parent component patch.\n data.on = data.nativeOn;\n \n if (isTrue(Ctor.options.abstract)) {\n // abstract components do not keep anything\n- // other than props & listeners\n+ // other than props & listeners & slot\n+\n+ // work around flow\n+ var slot = data.slot;\n data = {};\n+ if (slot) {\n+ data.slot = slot;\n+ }\n }\n \n // merge component management hooks onto the placeholder node\n@@ -3450,7 +3640,8 @@ function createComponent (\n var vnode = new VNode(\n (\"vue-component-\" + (Ctor.cid) + (name ? (\"-\" + name) : '')),\n data, undefined, undefined, undefined, context,\n- { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }\n+ { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children },\n+ asyncFactory\n );\n return vnode\n }\n@@ -3555,13 +3746,28 @@ function _createElement (\n );\n return createEmptyVNode()\n }\n+ // object syntax in v-bind\n+ if (isDef(data) && isDef(data.is)) {\n+ tag = data.is;\n+ }\n if (!tag) {\n // in case of component :is set to falsy value\n return createEmptyVNode()\n }\n+ // warn against non-primitive key\n+ if (process.env.NODE_ENV !== 'production' &&\n+ isDef(data) && isDef(data.key) && !isPrimitive(data.key)\n+ ) {\n+ warn(\n+ 'Avoid using non-primitive value as key, ' +\n+ 'use string/number value instead.',\n+ context\n+ );\n+ }\n // support single function children as default scoped slot\n if (Array.isArray(children) &&\n- typeof children[0] === 'function') {\n+ typeof children[0] === 'function'\n+ ) {\n data = data || {};\n data.scopedSlots = { default: children[0] };\n children.length = 0;\n@@ -3597,7 +3803,7 @@ function _createElement (\n // direct component options / constructor\n vnode = createComponent(tag, data, context, children);\n }\n- if (vnode !== undefined) {\n+ if (isDef(vnode)) {\n if (ns) { applyNS(vnode, ns); }\n return vnode\n } else {\n@@ -3611,7 +3817,7 @@ function applyNS (vnode, ns) {\n // use default namespace inside foreignObject\n return\n }\n- if (Array.isArray(vnode.children)) {\n+ if (isDef(vnode.children)) {\n for (var i = 0, l = vnode.children.length; i < l; i++) {\n var child = vnode.children[i];\n if (isDef(child.tag) && isUndef(child.ns)) {\n@@ -3649,6 +3855,9 @@ function renderList (\n ret[i] = render(val[key], key, i);\n }\n }\n+ if (isDef(ret)) {\n+ (ret)._isVList = true;\n+ }\n return ret\n }\n \n@@ -3667,7 +3876,7 @@ function renderSlot (\n if (scopedSlotFn) { // scoped slot\n props = props || {};\n if (bindObject) {\n- extend(props, bindObject);\n+ props = extend(extend({}, bindObject), props);\n }\n return scopedSlotFn(props) || fallback\n } else {\n@@ -3721,7 +3930,8 @@ function bindObjectProps (\n data,\n tag,\n value,\n- asProp\n+ asProp,\n+ isSync\n ) {\n if (value) {\n if (!isObject(value)) {\n@@ -3734,8 +3944,12 @@ function bindObjectProps (\n value = toObject(value);\n }\n var hash;\n- for (var key in value) {\n- if (key === 'class' || key === 'style') {\n+ var loop = function ( key ) {\n+ if (\n+ key === 'class' ||\n+ key === 'style' ||\n+ isReservedAttribute(key)\n+ ) {\n hash = data;\n } else {\n var type = data.attrs && data.attrs.type;\n@@ -3745,8 +3959,17 @@ function bindObjectProps (\n }\n if (!(key in hash)) {\n hash[key] = value[key];\n+\n+ if (isSync) {\n+ var on = data.on || (data.on = {});\n+ on[(\"update:\" + key)] = function ($event) {\n+ value[key] = $event;\n+ };\n+ }\n }\n- }\n+ };\n+\n+ for (var key in value) loop( key );\n }\n }\n return data\n@@ -3813,6 +4036,27 @@ function markStaticNode (node, key, isOnce) {\n \n /* */\n \n+function bindObjectListeners (data, value) {\n+ if (value) {\n+ if (!isPlainObject(value)) {\n+ process.env.NODE_ENV !== 'production' && warn(\n+ 'v-on without argument expects an Object value',\n+ this\n+ );\n+ } else {\n+ var on = data.on = data.on ? extend({}, data.on) : {};\n+ for (var key in value) {\n+ var existing = on[key];\n+ var ours = value[key];\n+ on[key] = existing ? [].concat(ours, existing) : ours;\n+ }\n+ }\n+ }\n+ return data\n+}\n+\n+/* */\n+\n function initRender (vm) {\n vm._vnode = null; // the root of the child tree\n vm._staticTrees = null;\n@@ -3828,6 +4072,22 @@ function initRender (vm) {\n // normalization is always applied for the public version, used in\n // user-written render functions.\n vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };\n+\n+ // $attrs & $listeners are exposed for easier HOC creation.\n+ // they need to be reactive so that HOCs using them are always updated\n+ var parentData = parentVnode && parentVnode.data;\n+ /* istanbul ignore else */\n+ if (process.env.NODE_ENV !== 'production') {\n+ defineReactive$$1(vm, '$attrs', parentData && parentData.attrs, function () {\n+ !isUpdatingChildComponent && warn(\"$attrs is readonly.\", vm);\n+ }, true);\n+ defineReactive$$1(vm, '$listeners', vm.$options._parentListeners, function () {\n+ !isUpdatingChildComponent && warn(\"$listeners is readonly.\", vm);\n+ }, true);\n+ } else {\n+ defineReactive$$1(vm, '$attrs', parentData && parentData.attrs, null, true);\n+ defineReactive$$1(vm, '$listeners', vm.$options._parentListeners, null, true);\n+ }\n }\n \n function renderMixin (Vue) {\n@@ -3895,7 +4155,7 @@ function renderMixin (Vue) {\n // code size.\n Vue.prototype._o = markOnce;\n Vue.prototype._n = toNumber;\n- Vue.prototype._s = _toString;\n+ Vue.prototype._s = toString;\n Vue.prototype._l = renderList;\n Vue.prototype._t = renderSlot;\n Vue.prototype._q = looseEqual;\n@@ -3907,6 +4167,7 @@ function renderMixin (Vue) {\n Vue.prototype._v = createTextVNode;\n Vue.prototype._e = createEmptyVNode;\n Vue.prototype._u = resolveScopedSlots;\n+ Vue.prototype._g = bindObjectListeners;\n }\n \n /* */\n@@ -4048,7 +4309,8 @@ function dedupe (latest, extended, sealed) {\n \n function Vue$2 (options) {\n if (process.env.NODE_ENV !== 'production' &&\n- !(this instanceof Vue$2)) {\n+ !(this instanceof Vue$2)\n+ ) {\n warn('Vue is a constructor and should be called with the `new` keyword');\n }\n this._init(options);\n@@ -4064,10 +4326,11 @@ renderMixin(Vue$2);\n \n function initUse (Vue) {\n Vue.use = function (plugin) {\n- /* istanbul ignore if */\n- if (plugin.installed) {\n- return\n+ var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));\n+ if (installedPlugins.indexOf(plugin) > -1) {\n+ return this\n }\n+\n // additional parameters\n var args = toArray(arguments, 1);\n args.unshift(this);\n@@ -4076,7 +4339,7 @@ function initUse (Vue) {\n } else if (typeof plugin === 'function') {\n plugin.apply(null, args);\n }\n- plugin.installed = true;\n+ installedPlugins.push(plugin);\n return this\n };\n }\n@@ -4086,6 +4349,7 @@ function initUse (Vue) {\n function initMixin$1 (Vue) {\n Vue.mixin = function (mixin) {\n this.options = mergeOptions(this.options, mixin);\n+ return this\n };\n }\n \n@@ -4226,14 +4490,16 @@ function initAssetRegisters (Vue) {\n \n /* */\n \n-var patternTypes = [String, RegExp];\n+var patternTypes = [String, RegExp, Array];\n \n function getComponentName (opts) {\n return opts && (opts.Ctor.options.name || opts.tag)\n }\n \n function matches (pattern, name) {\n- if (typeof pattern === 'string') {\n+ if (Array.isArray(pattern)) {\n+ return pattern.indexOf(name) > -1\n+ } else if (typeof pattern === 'string') {\n return pattern.split(',').indexOf(name) > -1\n } else if (isRegExp(pattern)) {\n return pattern.test(name)\n@@ -4377,7 +4643,14 @@ Object.defineProperty(Vue$2.prototype, '$isServer', {\n get: isServerRendering\n });\n \n-Vue$2.version = '2.3.0-beta.1';\n+Object.defineProperty(Vue$2.prototype, '$ssrContext', {\n+ get: function get () {\n+ /* istanbul ignore next */\n+ return this.$vnode && this.$vnode.ssrContext\n+ }\n+});\n+\n+Vue$2.version = '2.4.2';\n \n /* globals renderer */\n // renderer is injected by weex factory wrapper\n@@ -4508,10 +4781,11 @@ function registerRef (vnode, isRemoval) {\n }\n } else {\n if (vnode.data.refInFor) {\n- if (Array.isArray(refs[key]) && refs[key].indexOf(ref) < 0) {\n- refs[key].push(ref);\n- } else {\n+ if (!Array.isArray(refs[key])) {\n refs[key] = [ref];\n+ } else if (refs[key].indexOf(ref) < 0) {\n+ // $flow-disable-line\n+ refs[key].push(ref);\n }\n } else {\n refs[key] = ref;\n@@ -4539,11 +4813,18 @@ var hooks = ['create', 'activate', 'update', 'remove', 'destroy'];\n \n function sameVnode (a, b) {\n return (\n- a.key === b.key &&\n- a.tag === b.tag &&\n- a.isComment === b.isComment &&\n- isDef(a.data) === isDef(b.data) &&\n- sameInputType(a, b)\n+ a.key === b.key && (\n+ (\n+ a.tag === b.tag &&\n+ a.isComment === b.isComment &&\n+ isDef(a.data) === isDef(b.data) &&\n+ sameInputType(a, b)\n+ ) || (\n+ isTrue(a.isAsyncPlaceholder) &&\n+ a.asyncFactory === b.asyncFactory &&\n+ isUndef(b.asyncFactory.error)\n+ )\n+ )\n )\n }\n \n@@ -4696,6 +4977,7 @@ function createPatchFunction (backend) {\n function initComponent (vnode, insertedVnodeQueue) {\n if (isDef(vnode.data.pendingInsert)) {\n insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);\n+ vnode.data.pendingInsert = null;\n }\n vnode.elm = vnode.componentInstance.$el;\n if (isPatchable(vnode)) {\n@@ -4732,11 +5014,11 @@ function createPatchFunction (backend) {\n insert(parentElm, vnode.elm, refElm);\n }\n \n- function insert (parent, elm, ref) {\n+ function insert (parent, elm, ref$$1) {\n if (isDef(parent)) {\n- if (isDef(ref)) {\n- if (ref.parentNode === parent) {\n- nodeOps.insertBefore(parent, elm, ref);\n+ if (isDef(ref$$1)) {\n+ if (ref$$1.parentNode === parent) {\n+ nodeOps.insertBefore(parent, elm, ref$$1);\n }\n } else {\n nodeOps.appendChild(parent, elm);\n@@ -4786,8 +5068,9 @@ function createPatchFunction (backend) {\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n- i !== vnode.context &&\n- isDef(i = i.$options._scopeId)) {\n+ i !== vnode.context &&\n+ isDef(i = i.$options._scopeId)\n+ ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }\n@@ -4912,7 +5195,7 @@ function createPatchFunction (backend) {\n if (sameVnode(elmToMove, newStartVnode)) {\n patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);\n oldCh[idxInOld] = undefined;\n- canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm);\n+ canMove && nodeOps.insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);\n newStartVnode = newCh[++newStartIdx];\n } else {\n // same key but different element. treat as new element\n@@ -4934,24 +5217,37 @@ function createPatchFunction (backend) {\n if (oldVnode === vnode) {\n return\n }\n+\n+ var elm = vnode.elm = oldVnode.elm;\n+\n+ if (isTrue(oldVnode.isAsyncPlaceholder)) {\n+ if (isDef(vnode.asyncFactory.resolved)) {\n+ hydrate(oldVnode.elm, vnode, insertedVnodeQueue);\n+ } else {\n+ vnode.isAsyncPlaceholder = true;\n+ }\n+ return\n+ }\n+\n // reuse element for static trees.\n // note we only do this if the vnode is cloned -\n // if the new node is not cloned it means the render functions have been\n // reset by the hot-reload-api and we need to do a proper re-render.\n if (isTrue(vnode.isStatic) &&\n- isTrue(oldVnode.isStatic) &&\n- vnode.key === oldVnode.key &&\n- (isTrue(vnode.isCloned) || isTrue(vnode.isOnce))) {\n- vnode.elm = oldVnode.elm;\n+ isTrue(oldVnode.isStatic) &&\n+ vnode.key === oldVnode.key &&\n+ (isTrue(vnode.isCloned) || isTrue(vnode.isOnce))\n+ ) {\n vnode.componentInstance = oldVnode.componentInstance;\n return\n }\n+\n var i;\n var data = vnode.data;\n if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {\n i(oldVnode, vnode);\n }\n- var elm = vnode.elm = oldVnode.elm;\n+\n var oldCh = oldVnode.children;\n var ch = vnode.children;\n if (isDef(data) && isPatchable(vnode)) {\n@@ -4996,6 +5292,11 @@ function createPatchFunction (backend) {\n \n // Note: this is a browser-only function so we can assume elms are DOM nodes.\n function hydrate (elm, vnode, insertedVnodeQueue) {\n+ if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) {\n+ vnode.elm = elm;\n+ vnode.isAsyncPlaceholder = true;\n+ return true\n+ }\n if (process.env.NODE_ENV !== 'production') {\n if (!assertNodeMatch(elm, vnode)) {\n return false\n@@ -5032,8 +5333,9 @@ function createPatchFunction (backend) {\n // longer than the virtual children list.\n if (!childrenMatch || childNode) {\n if (process.env.NODE_ENV !== 'production' &&\n- typeof console !== 'undefined' &&\n- !bailed) {\n+ typeof console !== 'undefined' &&\n+ !bailed\n+ ) {\n bailed = true;\n console.warn('Parent: ', elm);\n console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);\n@@ -5313,8 +5615,10 @@ function updateClass (oldVnode, vnode) {\n \n var data = vnode.data;\n var oldData = oldVnode.data;\n- if (!data.staticClass && !data.class &&\n- (!oldData || (!oldData.staticClass && !oldData.class))) {\n+ if (!data.staticClass &&\n+ !data.class &&\n+ (!oldData || (!oldData.staticClass && !oldData.class))\n+ ) {\n return\n }\n \n@@ -5632,9 +5936,10 @@ function enter (_, vnode) {\n var parent = el.parentNode;\n var pendingNode = parent && parent._pending && parent._pending[vnode.key];\n if (pendingNode &&\n- pendingNode.context === vnode.context &&\n- pendingNode.tag === vnode.tag &&\n- pendingNode.elm._leaveCb) {\n+ pendingNode.context === vnode.context &&\n+ pendingNode.tag === vnode.tag &&\n+ pendingNode.elm._leaveCb\n+ ) {\n pendingNode.elm._leaveCb();\n }\n enterHook && enterHook(el, cb);\n@@ -5893,6 +6198,10 @@ function isSameChild (child, oldChild) {\n return oldChild.key === child.key && oldChild.tag === child.tag\n }\n \n+function isAsyncPlaceholder (node) {\n+ return node.isComment && node.asyncFactory\n+}\n+\n var Transition$1 = {\n name: 'transition',\n props: transitionProps,\n@@ -5901,13 +6210,13 @@ var Transition$1 = {\n render: function render (h) {\n var this$1 = this;\n \n- var children = this.$slots.default;\n+ var children = this.$options._renderChildren;\n if (!children) {\n return\n }\n \n // filter out text nodes (possible whitespaces)\n- children = children.filter(function (c) { return c.tag; });\n+ children = children.filter(function (c) { return c.tag || isAsyncPlaceholder(c); });\n /* istanbul ignore if */\n if (!children.length) {\n return\n@@ -5926,7 +6235,8 @@ var Transition$1 = {\n \n // warn invalid mode\n if (process.env.NODE_ENV !== 'production' &&\n- mode && mode !== 'in-out' && mode !== 'out-in') {\n+ mode && mode !== 'in-out' && mode !== 'out-in'\n+ ) {\n warn(\n 'invalid <transition> mode: ' + mode,\n this.$parent\n@@ -5958,7 +6268,9 @@ var Transition$1 = {\n // during entering.\n var id = \"__transition-\" + (this._uid) + \"-\";\n child.key = child.key == null\n- ? id + child.tag\n+ ? child.isComment\n+ ? id + 'comment'\n+ : id + child.tag\n : isPrimitive(child.key)\n ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key)\n : child.key;\n@@ -5973,7 +6285,12 @@ var Transition$1 = {\n child.data.show = true;\n }\n \n- if (oldChild && oldChild.data && !isSameChild(child, oldChild)) {\n+ if (\n+ oldChild &&\n+ oldChild.data &&\n+ !isSameChild(child, oldChild) &&\n+ !isAsyncPlaceholder(oldChild)\n+ ) {\n // replace old child transition data with fresh one\n // important for dynamic transitions!\n var oldData = oldChild && (oldChild.data.transition = extend({}, data));\n@@ -5987,6 +6304,9 @@ var Transition$1 = {\n });\n return placeholder(h, rawChild)\n } else if (mode === 'in-out') {\n+ if (isAsyncPlaceholder(child)) {\n+ return oldRawChild\n+ }\n var delayedLeave;\n var performLeave = function () { delayedLeave(); };\n mergeVNodeHook(data, 'afterEnter', performLeave);",
"filename": "packages/weex-vue-framework/factory.js",
"status": "modified"
},
{
"diff": "@@ -34,7 +34,7 @@ function init (cfg) {\n renderer.Document = cfg.Document;\n renderer.Element = cfg.Element;\n renderer.Comment = cfg.Comment;\n- renderer.sendTasks = cfg.sendTasks;\n+ renderer.compileBundle = cfg.compileBundle;\n }\n \n /**\n@@ -47,7 +47,7 @@ function reset () {\n delete renderer.Document;\n delete renderer.Element;\n delete renderer.Comment;\n- delete renderer.sendTasks;\n+ delete renderer.compileBundle;\n }\n \n /**\n@@ -82,18 +82,9 @@ function createInstance (\n // Virtual-DOM object.\n var document = new renderer.Document(instanceId, config.bundleUrl);\n \n- // All function/callback of parameters before sent to native\n- // will be converted as an id. So `callbacks` is used to store\n- // these real functions. When a callback invoked and won't be\n- // called again, it should be removed from here automatically.\n- var callbacks = [];\n-\n- // The latest callback id, incremental.\n- var callbackId = 1;\n-\n var instance = instances[instanceId] = {\n instanceId: instanceId, config: config, data: data,\n- document: document, callbacks: callbacks, callbackId: callbackId\n+ document: document\n };\n \n // Prepare native module getter and HTML5 Timer APIs.\n@@ -104,6 +95,7 @@ function createInstance (\n var weexInstanceVar = {\n config: config,\n document: document,\n+ supports: supports,\n requireModule: moduleGetter\n };\n Object.freeze(weexInstanceVar);\n@@ -118,11 +110,16 @@ function createInstance (\n weex: weexInstanceVar,\n // deprecated\n __weex_require_module__: weexInstanceVar.requireModule // eslint-disable-line\n- }, timerAPIs);\n- callFunction(instanceVars, appCode);\n+ }, timerAPIs, env.services);\n+\n+ if (!callFunctionNative(instanceVars, appCode)) {\n+ // If failed to compile functionBody on native side,\n+ // fallback to 'callFunction()'.\n+ callFunction(instanceVars, appCode);\n+ }\n \n // Send `createFinish` signal to native.\n- renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'createFinish', args: [] }], -1);\n+ instance.document.taskCenter.send('dom', { action: 'createFinish' }, []);\n }\n \n /**\n@@ -133,6 +130,7 @@ function createInstance (\n function destroyInstance (instanceId) {\n var instance = instances[instanceId];\n if (instance && instance.app instanceof instance.Vue) {\n+ instance.document.destroy();\n instance.app.$destroy();\n }\n delete instances[instanceId];\n@@ -154,7 +152,7 @@ function refreshInstance (instanceId, data) {\n instance.Vue.set(instance.app, key, data[key]);\n }\n // Finally `refreshFinish` signal needed.\n- renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'refreshFinish', args: [] }], -1);\n+ instance.document.taskCenter.send('dom', { action: 'refreshFinish' }, []);\n }\n \n /**\n@@ -169,49 +167,57 @@ function getRoot (instanceId) {\n return instance.app.$el.toJSON()\n }\n \n+var jsHandlers = {\n+ fireEvent: function (id) {\n+ var args = [], len = arguments.length - 1;\n+ while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];\n+\n+ return fireEvent.apply(void 0, [ instances[id] ].concat( args ))\n+ },\n+ callback: function (id) {\n+ var args = [], len = arguments.length - 1;\n+ while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];\n+\n+ return callback.apply(void 0, [ instances[id] ].concat( args ))\n+ }\n+};\n+\n+function fireEvent (instance, nodeId, type, e, domChanges) {\n+ var el = instance.document.getRef(nodeId);\n+ if (el) {\n+ return instance.document.fireEvent(el, type, e, domChanges)\n+ }\n+ return new Error((\"invalid element reference \\\"\" + nodeId + \"\\\"\"))\n+}\n+\n+function callback (instance, callbackId, data, ifKeepAlive) {\n+ var result = instance.document.taskCenter.callback(callbackId, data, ifKeepAlive);\n+ instance.document.taskCenter.send('dom', { action: 'updateFinish' }, []);\n+ return result\n+}\n+\n /**\n- * Receive tasks from native. Generally there are two types of tasks:\n- * 1. `fireEvent`: an device actions or user actions from native.\n- * 2. `callback`: invoke function which sent to native as a parameter before.\n- * @param {string} instanceId\n- * @param {array} tasks\n+ * Accept calls from native (event or callback).\n+ *\n+ * @param {string} id\n+ * @param {array} tasks list with `method` and `args`\n */\n-function receiveTasks (instanceId, tasks) {\n- var instance = instances[instanceId];\n- if (!instance || !(instance.app instanceof instance.Vue)) {\n- return new Error((\"receiveTasks: instance \" + instanceId + \" not found!\"))\n- }\n- var callbacks = instance.callbacks;\n- var document = instance.document;\n- tasks.forEach(function (task) {\n- // `fireEvent` case: find the event target and fire.\n- if (task.method === 'fireEvent') {\n- var ref = task.args;\n- var nodeId = ref[0];\n- var type = ref[1];\n- var e = ref[2];\n- var domChanges = ref[3];\n- var el = document.getRef(nodeId);\n- document.fireEvent(el, type, e, domChanges);\n- }\n- // `callback` case: find the callback by id and call it.\n- if (task.method === 'callback') {\n- var ref$1 = task.args;\n- var callbackId = ref$1[0];\n- var data = ref$1[1];\n- var ifKeepAlive = ref$1[2];\n- var callback = callbacks[callbackId];\n- if (typeof callback === 'function') {\n- callback(data);\n- // Remove the callback from `callbacks` if it won't called again.\n- if (typeof ifKeepAlive === 'undefined' || ifKeepAlive === false) {\n- callbacks[callbackId] = undefined;\n- }\n+function receiveTasks (id, tasks) {\n+ var instance = instances[id];\n+ if (instance && Array.isArray(tasks)) {\n+ var results = [];\n+ tasks.forEach(function (task) {\n+ var handler = jsHandlers[task.method];\n+ var args = [].concat( task.args );\n+ /* istanbul ignore else */\n+ if (typeof handler === 'function') {\n+ args.unshift(id);\n+ results.push(handler.apply(void 0, args));\n }\n- }\n- });\n- // Finally `updateFinish` signal needed.\n- renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'updateFinish', args: [] }], -1);\n+ });\n+ return results\n+ }\n+ return new Error((\"invalid instance id \\\"\" + id + \"\\\" or tasks\"))\n }\n \n /**\n@@ -235,6 +241,18 @@ function registerModules (newModules) {\n for (var name in newModules) loop( name );\n }\n \n+/**\n+ * Check whether the module or the method has been registered.\n+ * @param {String} module name\n+ * @param {String} method name (optional)\n+ */\n+function isRegisteredModule (name, method) {\n+ if (typeof method === 'string') {\n+ return !!(modules[name] && modules[name][method])\n+ }\n+ return !!modules[name]\n+}\n+\n /**\n * Register native components information.\n * @param {array} newComponents\n@@ -254,6 +272,35 @@ function registerComponents (newComponents) {\n }\n }\n \n+/**\n+ * Check whether the component has been registered.\n+ * @param {String} component name\n+ */\n+function isRegisteredComponent (name) {\n+ return !!components[name]\n+}\n+\n+/**\n+ * Detects whether Weex supports specific features.\n+ * @param {String} condition\n+ */\n+function supports (condition) {\n+ if (typeof condition !== 'string') { return null }\n+\n+ var res = condition.match(/^@(\\w+)\\/(\\w+)(\\.(\\w+))?$/i);\n+ if (res) {\n+ var type = res[1];\n+ var name = res[2];\n+ var method = res[4];\n+ switch (type) {\n+ case 'module': return isRegisteredModule(name, method)\n+ case 'component': return isRegisteredComponent(name)\n+ }\n+ }\n+\n+ return null\n+}\n+\n /**\n * Create a fresh instance of Vue for each Weex instance.\n */\n@@ -314,9 +361,7 @@ function createVueModuleInstance (instanceId, moduleGetter) {\n * Generate native module getter. Each native module has several\n * methods to call. And all the behaviors is instance-related. So\n * this getter will return a set of methods which additionally\n- * send current instance id to native when called. Also the args\n- * will be normalized into \"safe\" value. For example function arg\n- * will be converted into a callback id.\n+ * send current instance id to native when called.\n * @param {string} instanceId\n * @return {function}\n */\n@@ -326,15 +371,23 @@ function genModuleGetter (instanceId) {\n var nativeModule = modules[name] || [];\n var output = {};\n var loop = function ( methodName ) {\n- output[methodName] = function () {\n- var args = [], len = arguments.length;\n- while ( len-- ) args[ len ] = arguments[ len ];\n-\n- var finalArgs = args.map(function (value) {\n- return normalize(value, instance)\n- });\n- renderer.sendTasks(instanceId + '', [{ module: name, method: methodName, args: finalArgs }], -1);\n- };\n+ Object.defineProperty(output, methodName, {\n+ enumerable: true,\n+ configurable: true,\n+ get: function proxyGetter () {\n+ return function () {\n+ var args = [], len = arguments.length;\n+ while ( len-- ) args[ len ] = arguments[ len ];\n+\n+ return instance.document.taskCenter.send('module', { module: name, method: methodName }, args)\n+ }\n+ },\n+ set: function proxySetter (val) {\n+ if (typeof val === 'function') {\n+ return instance.document.taskCenter.send('module', { module: name, method: methodName }, [val])\n+ }\n+ }\n+ });\n };\n \n for (var methodName in nativeModule) loop( methodName );\n@@ -362,8 +415,9 @@ function getInstanceTimer (instanceId, moduleGetter) {\n var handler = function () {\n args[0].apply(args, args.slice(2));\n };\n+\n timer.setTimeout(handler, args[1]);\n- return instance.callbackId.toString()\n+ return instance.document.taskCenter.callbackManager.lastCallbackId.toString()\n },\n setInterval: function () {\n var args = [], len = arguments.length;\n@@ -372,8 +426,9 @@ function getInstanceTimer (instanceId, moduleGetter) {\n var handler = function () {\n args[0].apply(args, args.slice(2));\n };\n+\n timer.setInterval(handler, args[1]);\n- return instance.callbackId.toString()\n+ return instance.document.taskCenter.callbackManager.lastCallbackId.toString()\n },\n clearTimeout: function (n) {\n timer.clearTimeout(n);\n@@ -405,52 +460,55 @@ function callFunction (globalObjects, body) {\n }\n \n /**\n- * Convert all type of values into \"safe\" format to send to native.\n- * 1. A `function` will be converted into callback id.\n- * 2. An `Element` object will be converted into `ref`.\n- * The `instance` param is used to generate callback id and store\n- * function if necessary.\n- * @param {any} v\n- * @param {object} instance\n- * @return {any}\n+ * Call a new function generated on the V8 native side.\n+ *\n+ * This function helps speed up bundle compiling. Normally, the V8\n+ * engine needs to download, parse, and compile a bundle on every\n+ * visit. If 'compileBundle()' is available on native side,\n+ * the downloding, parsing, and compiling steps would be skipped.\n+ * @param {object} globalObjects\n+ * @param {string} body\n+ * @return {boolean}\n */\n-function normalize (v, instance) {\n- var type = typof(v);\n-\n- switch (type) {\n- case 'undefined':\n- case 'null':\n- return ''\n- case 'regexp':\n- return v.toString()\n- case 'date':\n- return v.toISOString()\n- case 'number':\n- case 'string':\n- case 'boolean':\n- case 'array':\n- case 'object':\n- if (v instanceof renderer.Element) {\n- return v.ref\n- }\n- return v\n- case 'function':\n- instance.callbacks[++instance.callbackId] = v;\n- return instance.callbackId.toString()\n- default:\n- return JSON.stringify(v)\n+function callFunctionNative (globalObjects, body) {\n+ if (typeof renderer.compileBundle !== 'function') {\n+ return false\n }\n-}\n \n-/**\n- * Get the exact type of an object by `toString()`. For example call\n- * `toString()` on an array will be returned `[object Array]`.\n- * @param {any} v\n- * @return {string}\n- */\n-function typof (v) {\n- var s = Object.prototype.toString.call(v);\n- return s.substring(8, s.length - 1).toLowerCase()\n+ var fn = void 0;\n+ var isNativeCompileOk = false;\n+ var script = '(function (';\n+ var globalKeys = [];\n+ var globalValues = [];\n+ for (var key in globalObjects) {\n+ globalKeys.push(key);\n+ globalValues.push(globalObjects[key]);\n+ }\n+ for (var i = 0; i < globalKeys.length - 1; ++i) {\n+ script += globalKeys[i];\n+ script += ',';\n+ }\n+ script += globalKeys[globalKeys.length - 1];\n+ script += ') {';\n+ script += body;\n+ script += '} )';\n+\n+ try {\n+ var weex = globalObjects.weex || {};\n+ var config = weex.config || {};\n+ fn = renderer.compileBundle(script,\n+ config.bundleUrl,\n+ config.bundleDigest,\n+ config.codeCachePath);\n+ if (fn && typeof fn === 'function') {\n+ fn.apply(void 0, globalValues);\n+ isNativeCompileOk = true;\n+ }\n+ } catch (e) {\n+ console.error(e);\n+ }\n+\n+ return isNativeCompileOk\n }\n \n exports.init = init;\n@@ -461,4 +519,7 @@ exports.refreshInstance = refreshInstance;\n exports.getRoot = getRoot;\n exports.receiveTasks = receiveTasks;\n exports.registerModules = registerModules;\n+exports.isRegisteredModule = isRegisteredModule;\n exports.registerComponents = registerComponents;\n+exports.isRegisteredComponent = isRegisteredComponent;\n+exports.supports = supports;",
"filename": "packages/weex-vue-framework/index.js",
"status": "modified"
},
{
"diff": "@@ -1,6 +1,6 @@\n {\n \"name\": \"weex-vue-framework\",\n- \"version\": \"2.1.9-weex.1\",\n+ \"version\": \"2.4.2-weex.1\",\n \"description\": \"Vue 2.0 Framework for Weex\",\n \"main\": \"index.js\",\n \"repository\": {",
"filename": "packages/weex-vue-framework/package.json",
"status": "modified"
},
{
"diff": "@@ -17,7 +17,7 @@ export const isAndroid = UA && UA.indexOf('android') > 0\n export const isIOS = UA && /iphone|ipad|ipod|ios/.test(UA)\n export const isChrome = UA && /chrome\\/\\d+/.test(UA) && !isEdge\n \n-// Firefix has a \"watch\" function on Object.prototype...\n+// Firefox has a \"watch\" function on Object.prototype...\n export const nativeWatch = ({}).watch\n \n export let supportsPassive = false",
"filename": "src/core/util/env.js",
"status": "modified"
},
{
"diff": "@@ -1,12 +1,13 @@\n /* @flow */\n \n import { isDef } from 'shared/util'\n+import { isAsyncPlaceholder } from './is-async-placeholder'\n \n export function getFirstComponentChild (children: ?Array<VNode>): ?VNode {\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length; i++) {\n const c = children[i]\n- if (isDef(c) && isDef(c.componentOptions)) {\n+ if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) {\n return c\n }\n }",
"filename": "src/core/vdom/helpers/get-first-component-child.js",
"status": "modified"
},
{
"diff": "@@ -6,3 +6,4 @@ export * from './update-listeners'\n export * from './normalize-children'\n export * from './resolve-async-component'\n export * from './get-first-component-child'\n+export * from './is-async-placeholder'",
"filename": "src/core/vdom/helpers/index.js",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,5 @@\n+/* @flow */\n+\n+export function isAsyncPlaceholder (node: VNode): boolean {\n+ return node.isComment && node.asyncFactory\n+}",
"filename": "src/core/vdom/helpers/is-async-placeholder.js",
"status": "added"
},
{
"diff": "@@ -5,7 +5,11 @@\n \n import { warn } from 'core/util/index'\n import { camelize, extend, isPrimitive } from 'shared/util'\n-import { mergeVNodeHook, getFirstComponentChild } from 'core/vdom/helpers/index'\n+import {\n+ mergeVNodeHook,\n+ isAsyncPlaceholder,\n+ getFirstComponentChild\n+} from 'core/vdom/helpers/index'\n \n export const transitionProps = {\n name: String,\n@@ -72,10 +76,6 @@ function isSameChild (child: VNode, oldChild: VNode): boolean {\n return oldChild.key === child.key && oldChild.tag === child.tag\n }\n \n-function isAsyncPlaceholder (node: VNode): boolean {\n- return node.isComment && node.asyncFactory\n-}\n-\n export default {\n name: 'transition',\n props: transitionProps,",
"filename": "src/platforms/web/runtime/components/transition.js",
"status": "modified"
},
{
"diff": "@@ -862,5 +862,89 @@ describe('Component keep-alive', () => {\n )\n }).then(done)\n })\n+\n+ it('async components with transition-mode out-in', done => {\n+ const barResolve = jasmine.createSpy('bar resolved')\n+ let next\n+ const foo = (resolve) => {\n+ setTimeout(() => {\n+ resolve(one)\n+ Vue.nextTick(next)\n+ }, duration / 2)\n+ }\n+ const bar = (resolve) => {\n+ setTimeout(() => {\n+ resolve(two)\n+ barResolve()\n+ }, duration / 2)\n+ }\n+ components = {\n+ foo,\n+ bar\n+ }\n+ const vm = new Vue({\n+ template: `<div>\n+ <transition name=\"test\" mode=\"out-in\" @after-enter=\"afterEnter\" @after-leave=\"afterLeave\">\n+ <keep-alive>\n+ <component :is=\"view\" class=\"test\"></component>\n+ </keep-alive>\n+ </transition>\n+ </div>`,\n+ data: {\n+ view: 'foo'\n+ },\n+ components,\n+ methods: {\n+ afterEnter () {\n+ next()\n+ },\n+ afterLeave () {\n+ next()\n+ }\n+ }\n+ }).$mount(el)\n+ expect(vm.$el.textContent).toBe('')\n+ next = () => {\n+ assertHookCalls(one, [1, 1, 1, 0, 0])\n+ assertHookCalls(two, [0, 0, 0, 0, 0])\n+ waitForUpdate(() => {\n+ expect(vm.$el.innerHTML).toBe(\n+ '<div class=\"test test-enter test-enter-active\">one</div>'\n+ )\n+ }).thenWaitFor(nextFrame).then(() => {\n+ expect(vm.$el.innerHTML).toBe(\n+ '<div class=\"test test-enter-active test-enter-to\">one</div>'\n+ )\n+ }).thenWaitFor(_next => { next = _next }).then(() => {\n+ // foo afterEnter get called\n+ expect(vm.$el.innerHTML).toBe('<div class=\"test\">one</div>')\n+ vm.view = 'bar'\n+ }).thenWaitFor(nextFrame).then(() => {\n+ assertHookCalls(one, [1, 1, 1, 1, 0])\n+ assertHookCalls(two, [0, 0, 0, 0, 0])\n+ expect(vm.$el.innerHTML).toBe(\n+ '<div class=\"test test-leave-active test-leave-to\">one</div><!---->'\n+ )\n+ }).thenWaitFor(_next => { next = _next }).then(() => {\n+ // foo afterLeave get called\n+ // and bar has already been resolved before afterLeave get called\n+ expect(barResolve.calls.count()).toBe(1)\n+ expect(vm.$el.innerHTML).toBe('<!---->')\n+ }).thenWaitFor(nextFrame).then(() => {\n+ expect(vm.$el.innerHTML).toBe(\n+ '<div class=\"test test-enter test-enter-active\">two</div>'\n+ )\n+ assertHookCalls(one, [1, 1, 1, 1, 0])\n+ assertHookCalls(two, [1, 1, 1, 0, 0])\n+ }).thenWaitFor(nextFrame).then(() => {\n+ expect(vm.$el.innerHTML).toBe(\n+ '<div class=\"test test-enter-active test-enter-to\">two</div>'\n+ )\n+ }).thenWaitFor(_next => { next = _next }).then(() => {\n+ // bar afterEnter get called\n+ expect(vm.$el.innerHTML).toBe('<div class=\"test\">two</div>')\n+ }).then(done)\n+ }\n+ })\n }\n })",
"filename": "test/unit/features/component/component-keep-alive.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.4.1\r\n\r\n### Reproduction link\r\n[https://codepen.io/anon/pen/dREmrV](https://codepen.io/anon/pen/dREmrV)\r\n\r\n### Steps to reproduce\r\nUsing the new `comments: true` property on a vue instance does not understand block comments, and it also errors when single quotes `'` are used within inline comments.\r\n\r\nThis is particularly annoying in Drupal development when debugging templates, since the template debug output is done using block comments and contains single quotes. See codepen example for a typical Drupal comment block output.\r\n\r\n### What is expected?\r\nComments should be rendered correctly within the outputted HTML.\r\n\r\n### What is actually happening?\r\nVueJS fails to render the instance and throws an exception when trying to parse the comments.\r\n\r\n---\r\nI believe this would happen when using Drupal 7 or 8 with development debugging turned on, when using Vue 2.4 .\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Looks only need to do a small changes\r\n\r\nin https://github.com/vuejs/vue/blob/dev/src/compiler/codegen/index.js#L445",
"created_at": "2017-07-18T17:41:12Z"
}
],
"number": 6150,
"title": "HTML block comments & single quotes not parsed correctly"
} | {
"body": "close #6150\r\n\r\n<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [ ] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n",
"number": 6156,
"review_comments": [],
"title": "fix(compile): generate comments with special character"
} | {
"commits": [
{
"message": "fix(compile): generate comments with special character\n\nclose #6150"
}
],
"files": [
{
"diff": "@@ -442,7 +442,7 @@ export function genText (text: ASTText | ASTExpression): string {\n }\n \n export function genComment (comment: ASTText): string {\n- return `_e('${comment.text}')`\n+ return `_e(${JSON.stringify(comment.text)})`\n }\n \n function genSlot (el: ASTElement, state: CodegenState): string {",
"filename": "src/compiler/codegen/index.js",
"status": "modified"
},
{
"diff": "@@ -479,7 +479,21 @@ describe('codegen', () => {\n comments: true\n }, baseOptions)\n const template = '<div><!--comment--></div>'\n- const generatedCode = `with(this){return _c('div',[_e('comment')])}`\n+ const generatedCode = `with(this){return _c('div',[_e(\"comment\")])}`\n+\n+ const ast = parse(template, options)\n+ optimize(ast, options)\n+ const res = generate(ast, options)\n+ expect(res.render).toBe(generatedCode)\n+ })\n+\n+ // #6150\n+ it('generate comments with special characters', () => {\n+ const options = extend({\n+ comments: true\n+ }, baseOptions)\n+ const template = '<div><!--\\n\\'comment\\'\\n--></div>'\n+ const generatedCode = `with(this){return _c('div',[_e(\"\\\\n'comment'\\\\n\")])}`\n \n const ast = parse(template, options)\n optimize(ast, options)",
"filename": "test/unit/modules/compiler/codegen.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.3.4\r\n\r\n### Reproduction\r\nHere what happens on F5 (reload) key:\r\n\r\n(It happens only once, the video is looped)\r\n\r\n\r\n### Steps to reproduce\r\nAdd a `<pre>` tag in App.vue of the vue-hackernews-2.0 demo:\r\n\r\n```\r\n<template>\r\n <div id=\"app\">\r\n <header class=\"header\">\r\n <pre style=\"background-color: #aaa\">\r\nfoobar\r\n </pre>\r\n <nav class=\"inner\">\r\n\r\n```\r\n\r\n### What is expected?\r\nclient-side and server-side have the same version for the `<pre>` tag\r\n\r\n### What is actually happening?\r\nclient and server side versions are not the same, then bailout ?, then `<pre>` tag content is flickering\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Thanks @FranckFreiburger , I try to reproduce the issue on Mac and windows, both ok. Will you please provide more information? And for `F5 key`, what do you mean it by that, F5 to reload the page?",
"created_at": "2017-07-01T00:22:46Z"
},
{
"body": "Windows 7, node v8.1.2, tested with latest Google Chrome & Firefox.\r\nAfter cloning vue-hackernews-2.0 demo, I just modified the `App.vue` to add the `<pre>` tag.\r\nThen I run `npm run dev`, and the first time the page is loaded, the issue happens (and the issue happens again on page reload)\r\n\r\nUsing google dev tools, \r\nWhen I pause the script execution just before the issue, the markup (in the dev tools Elements tab) is:\r\n```\r\n<pre style=\"background-color:#aaa;\">foobar\r\n\t\t</pre>\r\n```\r\n\r\nWhen I continue the script execution, the markup become:\r\n```\r\n<pre style=\"background-color:#aaa;\">\r\nfoobar\r\n\t\t</pre>\r\n```\r\n\r\nThe data from the network tab seems correct, the initial HTTP GET request contains: \r\n```\r\n<pre style=\"background-color:#aaa;\">\r\nfoobar\r\n\t\t</pre>\r\n```\r\n\r\n\r\nnote: the issue does not happens with `<div style=\"white-space:pre;\">` instead of `<pre>`\r\n",
"created_at": "2017-07-01T08:06:08Z"
},
{
"body": "Thanks, got it. I am trying to look into it.",
"created_at": "2017-07-02T23:38:39Z"
},
{
"body": "@FranckFreiburger This seems to be a bug. According to the specification https://www.w3.org/TR/html5/syntax.html#element-restrictions\r\n\r\n> A single newline may be placed immediately after the start tag of pre and textarea elements. If the element's contents are intended to start with a newline, two consecutive newlines thus need to be included by the author.\r\n\r\nThe `first` line break immediately following the pre tag is ignored, while the vue html compiler seems not.\r\n\r\nI'll try to fix it.\r\n",
"created_at": "2017-07-03T00:47:16Z"
}
],
"number": 5992,
"title": "ssr unexpected hydration bailout with <pre> tag"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [X] Bugfix\r\n- [ ] Feature\r\n- [X] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [X] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [X] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [ ] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [X] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [X] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\nfix #5992 ",
"number": 6022,
"review_comments": [
{
"body": "Not need to call `toLowerCase()` here, and it seems `<textarea>` will never reach to this function since `isPlainTextElement('textarea')` equals `true`.",
"created_at": "2017-07-03T16:44:39Z"
},
{
"body": "1. html5 tag names are case-insensitive, so we use lower case to compare\r\n2. isIgnoreFirstLf will be invoked when in textarea parse https://github.com/vuejs/vue/pull/6022/files#diff-084898b8c9f6d4d2833b18312180ef8fR172",
"created_at": "2017-07-04T00:28:00Z"
},
{
"body": "1. It'll call `toLowerCase()` when passing true to `makeMap` as the second param.\r\n2. I didn't notice those changes starting from line 172, my fault😂.",
"created_at": "2017-07-04T00:37:16Z"
},
{
"body": "👍 Thanks, I missed it, I'll update.",
"created_at": "2017-07-04T00:39:07Z"
},
{
"body": "Done.",
"created_at": "2017-07-04T00:41:30Z"
}
],
"title": "fix: the first LF following pre and textarea tag should be ignored, fix #5992"
} | {
"commits": [
{
"message": "fix: The first lf following the pre and textarea shuold be ignored."
},
{
"message": "test: add proper test case"
},
{
"message": "refactor: remove useless toLowerCase check"
},
{
"message": "Update html-parser.js"
},
{
"message": "Update parser.spec.js"
}
],
"files": [
{
"diff": "@@ -59,6 +59,10 @@ const decodingMap = {\n const encodedAttr = /&(?:lt|gt|quot|amp);/g\n const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g\n \n+// #5992\n+const isIgnoreNewlineTag = makeMap('pre,textarea', true)\n+const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\\n'\n+\n function decodeAttr (value, shouldDecodeNewlines) {\n const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr\n return value.replace(re, match => decodingMap[match])\n@@ -75,6 +79,9 @@ export function parseHTML (html, options) {\n last = html\n // Make sure we're not in a plaintext content element like script/style\n if (!lastTag || !isPlainTextElement(lastTag)) {\n+ if (shouldIgnoreFirstNewline(lastTag, html)) {\n+ advance(1)\n+ }\n let textEnd = html.indexOf('<')\n if (textEnd === 0) {\n // Comment:\n@@ -152,16 +159,19 @@ export function parseHTML (html, options) {\n options.chars(text)\n }\n } else {\n- var stackedTag = lastTag.toLowerCase()\n- var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\\\s\\\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))\n- var endTagLength = 0\n- var rest = html.replace(reStackedTag, function (all, text, endTag) {\n+ let endTagLength = 0\n+ const stackedTag = lastTag.toLowerCase()\n+ const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\\\s\\\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))\n+ const rest = html.replace(reStackedTag, function (all, text, endTag) {\n endTagLength = endTag.length\n if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {\n text = text\n .replace(/<!--([\\s\\S]*?)-->/g, '$1')\n .replace(/<!\\[CDATA\\[([\\s\\S]*?)]]>/g, '$1')\n }\n+ if (shouldIgnoreFirstNewline(stackedTag, text)) {\n+ text = text.slice(1)\n+ }\n if (options.chars) {\n options.chars(text)\n }",
"filename": "src/compiler/parser/html-parser.js",
"status": "modified"
},
{
"diff": "@@ -495,6 +495,21 @@ describe('parser', () => {\n expect(span.children[0].text).toBe(' ')\n })\n \n+ // #5992\n+ it('ignore the first newline in <pre> tag', function () {\n+ const options = extend({}, baseOptions)\n+ const ast = parse('<div><pre>\\nabc</pre>\\ndef<pre>\\n\\nabc</pre></div>', options)\n+ const pre = ast.children[0]\n+ expect(pre.children[0].type).toBe(3)\n+ expect(pre.children[0].text).toBe('abc')\n+ const text = ast.children[1]\n+ expect(text.type).toBe(3)\n+ expect(text.text).toBe('\\ndef')\n+ const pre2 = ast.children[2]\n+ expect(pre2.children[0].type).toBe(3)\n+ expect(pre2.children[0].text).toBe('\\nabc')\n+ })\n+\n it('forgivingly handle < in plain text', () => {\n const options = extend({}, baseOptions)\n const ast = parse('<p>1 < 2 < 3</p>', options)\n@@ -530,8 +545,7 @@ describe('parser', () => {\n expect(whitespace.children.length).toBe(1)\n expect(whitespace.children[0].type).toBe(3)\n // textarea is whitespace sensitive\n- expect(whitespace.children[0].text).toBe(`\n- <p>Test 1</p>\n+ expect(whitespace.children[0].text).toBe(` <p>Test 1</p>\n test2\n `)\n ",
"filename": "test/unit/modules/compiler/parser.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.3.0\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/oyf86mcp/](https://jsfiddle.net/oyf86mcp/)\r\n\r\n### Steps to reproduce\r\n1. Run the fiddle\r\n2. Uncheck the checkbox\r\n3. Click \"Shuffle\" button \r\n4. Check the checkbox\r\n5. Click \"Shuffle\" button\r\n\r\n### What is expected?\r\nAfter first \"Shuffle\" click (with an unchecked checkbox), list items are reordered with no transition animation.\r\n\r\nAfter second \"Shuffle\" click (with a checked checkbox), list items are reordered with a transition animation.\r\n\r\n### What is actually happening?\r\nAfter first \"Shuffle\" click (with an unchecked checkbox), list items are reordered with no transition animation.\r\n\r\nAfter second \"Shuffle\" click (with a checked checkbox), list items are still reordered with no transition animation.\r\n\r\n---\r\nFound via this question on StackOverflow:\r\nhttps://stackoverflow.com/questions/44850588/disable-transition-animation/44851948#44851948\r\n\r\nIf the list is shuffled before initially unchecking the checkbox, everything works as expected. I'm only seeing this when the list is initially shuffled when the `name` of the transition group is set to `\"disabled-list\"`.\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Thanks for reporting it! This shouldn't be happening indeed. I didn't dig further but you can workaround it for the moment by specifying a `:key=\"transitionName\"` on the transition-group element",
"created_at": "2017-07-02T22:04:05Z"
}
],
"number": 6006,
"title": "Transition group with dynamic name not correctly applying transition"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [x] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n\r\nfix #6006 \r\n",
"number": 6019,
"review_comments": [],
"title": "fix: transition group should work with dynamic name (#6006)"
} | {
"commits": [
{
"message": "fix: transition group should work with dynamic name (#6006)"
},
{
"message": "fix: improve remove class"
}
],
"files": [
{
"diff": "@@ -42,12 +42,20 @@ export function removeClass (el: HTMLElement, cls: ?string) {\n } else {\n el.classList.remove(cls)\n }\n+ if (!el.classList.length) {\n+ el.removeAttribute('class')\n+ }\n } else {\n let cur = ` ${el.getAttribute('class') || ''} `\n const tar = ' ' + cls + ' '\n while (cur.indexOf(tar) >= 0) {\n cur = cur.replace(tar, ' ')\n }\n- el.setAttribute('class', cur.trim())\n+ cur = cur.trim()\n+ if (cur) {\n+ el.setAttribute('class', cur)\n+ } else {\n+ el.removeAttribute('class')\n+ }\n }\n }",
"filename": "src/platforms/web/runtime/class-util.js",
"status": "modified"
},
{
"diff": "@@ -127,7 +127,7 @@ export default {\n if (!hasTransition) {\n return false\n }\n- if (this._hasMove != null) {\n+ if (this._hasMove) {\n return this._hasMove\n }\n // Detect whether an element with the move class applied has",
"filename": "src/platforms/web/runtime/components/transition-group.js",
"status": "modified"
},
{
"diff": "@@ -293,5 +293,52 @@ if (!isIE9) {\n }).$mount()\n expect('<transition-group> children must be keyed: <div>').toHaveBeenWarned()\n })\n+\n+ // Github issue #6006\n+ it('should work with dynamic name', done => {\n+ const vm = new Vue({\n+ template: `\n+ <div>\n+ <transition-group :name=\"name\">\n+ <div v-for=\"item in items\" :key=\"item\">{{ item }}</div>\n+ </transition-group>\n+ </div>\n+ `,\n+ data: {\n+ items: ['a', 'b', 'c'],\n+ name: 'group'\n+ }\n+ }).$mount(el)\n+\n+ vm.name = 'invalid-name'\n+ vm.items = ['b', 'c', 'a']\n+ waitForUpdate(() => {\n+ expect(vm.$el.innerHTML.replace(/\\s?style=\"\"(\\s?)/g, '$1')).toBe(\n+ `<span>` +\n+ `<div>b</div>` +\n+ `<div>c</div>` +\n+ `<div>a</div>` +\n+ `</span>`\n+ )\n+ vm.name = 'group'\n+ vm.items = ['a', 'b', 'c']\n+ }).thenWaitFor(nextFrame).then(() => {\n+ expect(vm.$el.innerHTML.replace(/\\s?style=\"\"(\\s?)/g, '$1')).toBe(\n+ `<span>` +\n+ `<div class=\"group-move\">a</div>` +\n+ `<div class=\"group-move\">b</div>` +\n+ `<div class=\"group-move\">c</div>` +\n+ `</span>`\n+ )\n+ }).thenWaitFor(duration * 2 + buffer).then(() => {\n+ expect(vm.$el.innerHTML.replace(/\\s?style=\"\"(\\s?)/g, '$1')).toBe(\n+ `<span>` +\n+ `<div>a</div>` +\n+ `<div>b</div>` +\n+ `<div>c</div>` +\n+ `</span>`\n+ )\n+ }).then(done)\n+ })\n })\n }",
"filename": "test/unit/features/transition/transition-group.spec.js",
"status": "modified"
},
{
"diff": "@@ -437,7 +437,7 @@ if (!isIE9) {\n expect(enterSpy).toHaveBeenCalled()\n expect(vm.$el.innerHTML).toBe('<div class=\"nope-enter nope-enter-active\">foo</div>')\n }).thenWaitFor(nextFrame).then(() => {\n- expect(vm.$el.innerHTML).toMatch(/<div( class=\"\")?>foo<\\/div>/)\n+ expect(vm.$el.innerHTML).toBe('<div>foo</div>')\n }).then(done)\n })\n ",
"filename": "test/unit/features/transition/transition.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\nvue@2.2.3\r\n\r\n### Reproduction link\r\n[https://github.com/freeozyl80/vue-memory-leak](https://github.com/freeozyl80/vue-memory-leak)\r\n\r\n### Steps to reproduce\r\n1. use Vue Server Render (renderToString);\r\n2. the vm in server has \"computed\" which define a test function without return.(yes ,this step is incorrect, just throw error and pause is ok, but then memory leak happend)\r\n3. memory leak happend.\r\n\r\n### What is expected?\r\nthrow error and pause \r\n\r\n### What is actually happening?\r\nthe vonde is going to run and create, but not destroyed and exit.\r\nIn heap snapshots, i found the vue$2 has created almost 4538\r\n\r\n---\r\njust look in 'https://github.com/freeozyl80/vue-memory-leak'\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "Hi, I have cloned your repository. Wrapping your code in a `while (true)` statement does not incur out of memory error. This probably means nothing wrong with library code.\r\n\r\nNote the memory consumption in your snapshot is under 200MB, which is fairly a low work load for server code. So it is reasonable V8 does not reclaim these memory. \r\n\r\nCan you provide more information?",
"created_at": "2017-06-26T14:56:12Z"
},
{
"body": "i tried use setInterval, interval of 20 ms. when i run in the server, the memory used by it is increasing\r\n\r\n\r\n\r\nby the way, 200MB is small number, but this happened on the production enviroment when the request almost 30millon per day, fortuneately, i found the reason and made the \"computed\"'s function correctly. but after that, i wonder why it happend? \r\nby the way, thanks for help",
"created_at": "2017-06-27T13:25:00Z"
},
{
"body": "Please update your code to illustrate the problem.",
"created_at": "2017-06-27T13:56:04Z"
},
{
"body": "alreay updated",
"created_at": "2017-06-28T02:43:46Z"
},
{
"body": "Ok, I reproduced it. And commenting out throw new Error does keep memory low.",
"created_at": "2017-06-28T03:14:14Z"
},
{
"body": "Reproducible in browser.\r\n\r\n```js\r\nvar timer = setInterval(function() {\r\n const vm = new Vue({\r\n computed: {\r\n \"test\": function() {\r\n throw 'erro happened';\r\n }\r\n }\r\n });\r\n try {\r\n vm.test\r\n } catch(e) {\r\n }\r\n\r\n}, 1);\r\n```",
"created_at": "2017-06-28T05:17:01Z"
}
],
"number": 5975,
"title": "Memory leak in Vue.js server-side when using \"computed\""
} | {
"body": "watcher.get should always clean up observee stack in order to prevent memory leak. Also, non-user\r\ndefined watch should rethrow error.\r\n\r\n#5975 ",
"number": 5988,
"review_comments": [],
"title": "fix: ensure cleanup in watcher.get"
} | {
"commits": [
{
"message": "fix: ensure cleanup in watcher.get\n\nwatcher.get should always clean up observee stack in order to prevent memory leak. Also, non-user\ndefined watch should rethrow error.\n\n#5975"
}
],
"files": [
{
"diff": "@@ -94,22 +94,23 @@ export default class Watcher {\n pushTarget(this)\n let value\n const vm = this.vm\n- if (this.user) {\n- try {\n- value = this.getter.call(vm, vm)\n- } catch (e) {\n+ try {\n+ value = this.getter.call(vm, vm)\n+ } catch (e) {\n+ if (this.user) {\n handleError(e, vm, `getter for watcher \"${this.expression}\"`)\n+ } else {\n+ throw e\n }\n- } else {\n- value = this.getter.call(vm, vm)\n- }\n- // \"touch\" every property so they are all tracked as\n- // dependencies for deep watching\n- if (this.deep) {\n- traverse(value)\n+ } finally {\n+ // \"touch\" every property so they are all tracked as\n+ // dependencies for deep watching\n+ if (this.deep) {\n+ traverse(value)\n+ }\n+ popTarget()\n+ this.cleanupDeps()\n }\n- popTarget()\n- this.cleanupDeps()\n return value\n }\n ",
"filename": "src/core/observer/watcher.js",
"status": "modified"
},
{
"diff": "@@ -193,4 +193,15 @@ describe('Options computed', () => {\n })\n expect(`computed property \"a\" is already defined as a prop`).toHaveBeenWarned()\n })\n+\n+ it('rethrow computed error', () => {\n+ const vm = new Vue({\n+ computed: {\n+ a: () => {\n+ throw new Error('rethrow')\n+ }\n+ }\n+ })\n+ expect(() => vm.a).toThrowError('rethrow')\n+ })\n })",
"filename": "test/unit/features/options/computed.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.3.2\r\n\r\n### Reproduction link\r\n[https://jsfiddle.net/gazugafan/a8kverza/2/](https://jsfiddle.net/gazugafan/a8kverza/2/)\r\n\r\n### Steps to reproduce\r\nChange the inputs marked \"Change Me\", then add a row. Any inputs following the v-for rows get re-created (and lose their value), while inputs above remain as they are. This only seems to happen when the inputs and v-for element are contained in a parent component's slot.\r\n\r\n### What is expected?\r\nAll inputs remain unchanged--regardless of what happens to the sibling v-for element.\r\n\r\n### What is actually happening?\r\nAny input elements following the v-for are re-created--resetting their value.\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "I'm not entirely sure, but this looks like a bug to me, because this only happens with the slot content.\r\nIn the mean time, `key`-ing the element in question helps: https://jsfiddle.net/a8kverza/3/",
"created_at": "2017-05-06T09:08:18Z"
},
{
"body": "I just ran into something similar. Although in my example, a `v-if` on a nested slot causes a sibling component to be recreated: https://jsfiddle.net/y0vgrwjy/1/\r\n\r\nProbably related?",
"created_at": "2017-05-06T23:12:12Z"
},
{
"body": "@nerdcave , I think it is related. the reason is what I describe in PR.\r\n\r\nyou will find it works well if you change `slot content` position like [this](https://jsfiddle.net/y0vgrwjy/3/)",
"created_at": "2017-05-07T12:51:55Z"
},
{
"body": "@pengchongfu, Also works if you add a `key` to `<my-data>`. Thanks for looking into it.",
"created_at": "2017-05-07T14:18:23Z"
},
{
"body": "@nerdcave ,you can also add a wrapper like [this](https://jsfiddle.net/y0vgrwjy/4/), the wrapper would be a placeholder so that the default `key` of `input` will not changed. ",
"created_at": "2017-05-07T14:45:42Z"
}
],
"number": 5618,
"title": "Elements unnecessarily re-created when an above v-for changes."
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [x] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [ ] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n\r\nin issue #5618 , then VNode in the first layer of the array don't get a key when father component call `normalizeChildren`,\r\nbut get a key when child component call `normalizeChildren`.\r\n\r\nthis leads to a changeable key, and component was re-created.",
"number": 5622,
"review_comments": [
{
"body": "I think here only need to determine whether `c` is created by `slot`, avoid to set `key `",
"created_at": "2017-05-07T16:58:58Z"
},
{
"body": "Let me fix it 🙂 ",
"created_at": "2017-05-07T17:24:58Z"
}
],
"title": "only set a key to VNode have similar shape, fix #5618"
} | {
"commits": [
{
"message": "only set a key to VNode have similar shape, fix #5618"
}
],
"files": [
{
"diff": "@@ -1,7 +1,7 @@\n /* @flow */\n \n import VNode, { createTextVNode } from 'core/vdom/vnode'\n-import { isDef, isUndef, isPrimitive } from 'shared/util'\n+import { isDef, isUndef, isPrimitive, isObject } from 'shared/util'\n \n // The template compiler attempts to minimize the need for normalization by\n // statically analyzing the template at compile time.\n@@ -45,7 +45,11 @@ function normalizeArrayChildren (children: any, nestedIndex?: string): Array<VNo\n last = res[res.length - 1]\n // nested\n if (Array.isArray(c)) {\n- res.push.apply(res, normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`))\n+ if (hasNestedIndex(c)) {\n+ res.push.apply(res, normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`))\n+ } else {\n+ res.push.apply(res, normalizeArrayChildren(c))\n+ }\n } else if (isPrimitive(c)) {\n if (isDef(last) && isDef(last.text)) {\n last.text += String(c)\n@@ -67,3 +71,21 @@ function normalizeArrayChildren (children: any, nestedIndex?: string): Array<VNo\n }\n return res\n }\n+\n+function hasNestedIndex (children: any): boolean {\n+ const length = children.length\n+ if (length <= 1) return true\n+ if (isObject(children[0]) === false || isUndef(children[0].tag) || isDef(children[0].key)) return false\n+ let i\n+ for (i = 1; i < length; i++) {\n+ if (isObject(children[i]) === false || similarVNode(children[0], children[i]) === false) return false\n+ }\n+ return true\n+}\n+\n+function similarVNode (a: VNode, b: VNode): boolean {\n+ return (\n+ a.tag === b.tag &&\n+ a.key === b.key\n+ )\n+}",
"filename": "src/core/vdom/helpers/normalize-children.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\r\n2.2.4\r\n\r\n### Reproduction Link\r\nhttps://jsfiddle.net/orzz/ucLrrnj4/8/\r\n\r\n### What is Expected?\r\nstate declare in root component should change and render to html\r\nsame code in vue version 2.0.0 worked as expected https://jsfiddle.net/orzz/k18o6e0f/1/\r\n\r\n### What is actually happening?\r\nstate changed in the callback emitted by child component is not worked as expected",
"comments": [
{
"body": "It will be a lot easier for anyone to help you out if you simply share your code instead of images of your code. You can base your demo off of [the Jsfiddle template included in the readme](https://jsfiddle.net/39epgLj0/), if it's easier for you.",
"created_at": "2017-03-14T12:11:22Z"
},
{
"body": "This may help you: https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats",
"created_at": "2017-03-14T12:14:46Z"
},
{
"body": "@posva if i watch the var named 'varieties' it worked well",
"created_at": "2017-03-14T12:47:48Z"
},
{
"body": "FYI, just pasting the code does not satisfy the requirement for a reproduction. Please follow the [Issue Reporting Guidelines](https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#issue-reporting-guidelines) and provide a minimal JSFiddle or JSBin containing a set of reproducible steps that can lead to the behavior you described.\r\n\r\n[Why is this required?](https://gist.github.com/Rich-Harris/88c5fc2ac6dc941b22e7996af05d70ff)",
"created_at": "2017-03-14T13:21:31Z"
},
{
"body": "@yyx990803 The reproduction jsfiddle is now interactive and I'm stumped as to why it behaves the way it does. :/\r\n\r\nMaybe it's my dizzy sunday head, btu this looks like a bug?!?",
"created_at": "2017-03-19T11:48:14Z"
},
{
"body": "The newly pushed watchers caused by state changes inside updated hooks haven't been called at all.\r\nIn core/observer/scheduler.js L83 to L86, the queue is cleared after all updated hooks have been called.",
"created_at": "2017-03-19T11:57:19Z"
},
{
"body": "Thanks all you guys",
"created_at": "2017-03-21T06:47:40Z"
}
],
"number": 5191,
"title": "no change triggered after reassigned state"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [ ] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [x] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [ ] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n#5191 ",
"number": 5233,
"review_comments": [],
"title": "fix no change triggered after reassigned state, Fix #5191"
} | {
"commits": [
{
"message": "trigger event after reassigned state - Fix #5191"
}
],
"files": [
{
"diff": "@@ -69,10 +69,14 @@ function flushSchedulerQueue () {\n }\n }\n \n+ // reset scheduler before updated hook called\n+ const oldQueue = queue.slice()\n+ resetSchedulerState()\n+\n // call updated hooks\n- index = queue.length\n+ index = oldQueue.length\n while (index--) {\n- watcher = queue[index]\n+ watcher = oldQueue[index]\n vm = watcher.vm\n if (vm._watcher === watcher && vm._isMounted) {\n callHook(vm, 'updated')\n@@ -84,8 +88,6 @@ function flushSchedulerQueue () {\n if (devtools && config.devtools) {\n devtools.emit('flush')\n }\n-\n- resetSchedulerState()\n }\n \n /**",
"filename": "src/core/observer/scheduler.js",
"status": "modified"
},
{
"diff": "@@ -144,4 +144,35 @@ describe('Scheduler', () => {\n expect(callOrder).toEqual([1, 2, 3])\n }).then(done)\n })\n+\n+ // Github issue #5191\n+ it('emit should work when updated hook called', done => {\n+ const el = document.createElement('div')\n+ const vm = new Vue({\n+ template: `<div><child @change=\"bar\" :foo=\"foo\"></child></div>`,\n+ data: {\n+ foo: 0\n+ },\n+ methods: {\n+ bar: spy\n+ },\n+ components: {\n+ child: {\n+ template: `<div>{{foo}}</div>`,\n+ props: ['foo'],\n+ updated () {\n+ this.$emit('change')\n+ }\n+ }\n+ }\n+ }).$mount(el)\n+ vm.$nextTick(() => {\n+ vm.foo = 1\n+ vm.$nextTick(() => {\n+ expect(vm.$el.innerHTML).toBe('<div>1</div>')\n+ expect(spy).toHaveBeenCalled()\n+ done()\n+ })\n+ })\n+ })\n })",
"filename": "test/unit/modules/observer/scheduler.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Version\r\n2.2.4\r\n\r\n### Reproduction link\r\n[http://codepen.io/anon/pen/VpyqEz?editors=1111](http://codepen.io/anon/pen/VpyqEz?editors=1111)\r\n\r\n### Steps to reproduce\r\nCreate a parent and child component\r\n\r\nSet the provide of the parent using vuex\r\n\r\nInject the provide of the parent to child\r\n\r\n### What is expected?\r\nMust be reactive\r\n\r\n### What is actually happening?\r\nNot Reactive\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "It actually doesn't depend on Vuex. It happens with plain Vue: http://codepen.io/anon/pen/EWoMLr?editors=1111\r\n\r\nUsing a single array, nothing is tracked. But if we display another injected property (in this case bar), both are updating accordingly",
"created_at": "2017-03-19T19:12:17Z"
}
],
"number": 5223,
"title": "Provide isn't reactive with a single array"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\n<!-- PULL REQUEST TEMPLATE -->\r\n<!-- (Update \"[ ]\" to \"[x]\" to check a box) -->\r\n\r\n**What kind of change does this PR introduce?** (check at least one)\r\n\r\n- [x] Bugfix\r\n- [ ] Feature\r\n- [ ] Code style update\r\n- [ ] Refactor\r\n- [ ] Build-related changes\r\n- [ ] Other, please describe:\r\n\r\n**Does this PR introduce a breaking change?** (check one)\r\n\r\n- [ ] Yes\r\n- [x] No\r\n\r\nIf yes, please describe the impact and migration path for existing applications:\r\n\r\n**The PR fulfills these requirements:**\r\n\r\n- [x] It's submitted to the `dev` branch for v2.x (or to a previous version branch), _not_ the `master` branch\r\n- [ ] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where \"xxx\" is the issue number)\r\n- [ ] All tests are passing: https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#development-setup\r\n- [ ] New/updated tests are included\r\n\r\nIf adding a **new feature**, the PR's description includes:\r\n- [x] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it)\r\n\r\n**Other information:**\r\n#5223 ",
"number": 5229,
"review_comments": [
{
"body": "make sure to prefix warnings with `process.env.NODE_ENV` check :)",
"created_at": "2017-03-21T04:59:53Z"
},
{
"body": "done",
"created_at": "2017-03-21T05:04:51Z"
}
],
"title": "fix provide isn't reactive with a single array, Fix #5223 "
} | {
"commits": [
{
"message": "fix provide isn't reactive with a single array - Fix #5223"
},
{
"message": "add warning when injections has been modified"
}
],
"files": [
{
"diff": "@@ -1,6 +1,8 @@\n /* @flow */\n \n import { hasSymbol } from 'core/util/env'\n+import { warn } from '../util/index'\n+import { defineReactive } from '../observer/index'\n \n export function initProvide (vm: Component) {\n const provide = vm.$options.provide\n@@ -29,7 +31,18 @@ export function initInjections (vm: Component) {\n let source = vm\n while (source) {\n if (source._provided && provideKey in source._provided) {\n- vm[key] = source._provided[provideKey]\n+ if (process.env.NODE_ENV !== 'production') {\n+ defineReactive(vm, key, source._provided[provideKey], () => {\n+ warn(\n+ `Avoid mutating a injections directly since the value will be ` +\n+ `overwritten whenever the provided component re-renders. ` +\n+ `injections being mutated: \"${key}\"`,\n+ vm\n+ )\n+ })\n+ } else {\n+ defineReactive(vm, key, source._provided[provideKey])\n+ }\n break\n }\n source = source.$parent",
"filename": "src/core/instance/inject.js",
"status": "modified"
},
{
"diff": "@@ -162,4 +162,59 @@ describe('Options provide/inject', () => {\n expect(vm.$el.textContent).toBe('123')\n })\n }\n+\n+ // Github issue #5223\n+ it('should work with reactive array', done => {\n+ const vm = new Vue({\n+ template: `<div><child></child></div>`,\n+ data () {\n+ return {\n+ foo: []\n+ }\n+ },\n+ provide () {\n+ return {\n+ foo: this.foo\n+ }\n+ },\n+ components: {\n+ child: {\n+ inject: ['foo'],\n+ template: `<span>{{foo.length}}</span>`\n+ }\n+ }\n+ }).$mount()\n+\n+ expect(vm.$el.innerHTML).toEqual(`<span>0</span>`)\n+ vm.foo.push(vm.foo.length)\n+ vm.$nextTick(() => {\n+ expect(vm.$el.innerHTML).toEqual(`<span>1</span>`)\n+ vm.foo.pop()\n+ vm.$nextTick(() => {\n+ expect(vm.$el.innerHTML).toEqual(`<span>0</span>`)\n+ done()\n+ })\n+ })\n+ })\n+\n+ it('should warn when injections has been modified', () => {\n+ const key = 'foo'\n+ const vm = new Vue({\n+ provide: {\n+ foo: 1\n+ }\n+ })\n+\n+ const child = new Vue({\n+ parent: vm,\n+ inject: ['foo']\n+ })\n+\n+ expect(child.foo).toBe(1)\n+ child.foo = 2\n+ expect(\n+ `Avoid mutating a injections directly since the value will be ` +\n+ `overwritten whenever the provided component re-renders. ` +\n+ `injections being mutated: \"${key}\"`).toHaveBeenWarned()\n+ })\n })",
"filename": "test/unit/features/options/inject.spec.js",
"status": "modified"
}
]
} |
{
"body": "## Version\r\n2.2.1\r\n\r\n## Reproduction Link\r\n[https://jsfiddle.net/agvmLg8t/1/](https://jsfiddle.net/agvmLg8t/1/)\r\n\r\n## Steps to Reproduce\r\n- View generated output\r\n\r\n## What is expected?\r\nProvided falsy values should be injectable.\r\n\r\n## What is actually happening?\r\nCheck in [inject.js#L16](https://github.com/vuejs/vue/blob/f916bcf37105903290ad2353db9a9436536d6859/src/core/instance/inject.js#L16) prevents injection of falsy values.\r\n\r\n<!-- generated by vue-issues. DO NOT REMOVE -->",
"comments": [
{
"body": "```\r\nif (source._provided && typeof source._provided[provideKey] !== 'undefined') {\r\n```\r\n\r\nshould be enough, right?",
"created_at": "2017-03-01T09:58:44Z"
},
{
"body": "`in` check would handle cases like `provide: { foo: undefined }`",
"created_at": "2017-03-01T10:02:39Z"
},
{
"body": "Or `provide.hasOwnProperty`? https://jsfiddle.net/Akryum/y7Lfa58j/",
"created_at": "2017-03-01T10:15:22Z"
},
{
"body": "`hasOwnProperty` ignores inherited properties.\r\n\r\nI guess inherited properties are not required in our case. Should it be changed to `hasOwnProperty`?",
"created_at": "2017-03-01T11:05:53Z"
},
{
"body": "I like the fact that `in` makes a shorter version 😆 Just ping Evan on the PR 🙂 ",
"created_at": "2017-03-01T12:19:00Z"
}
],
"number": 5043,
"title": "Injecting falsy values"
} | {
"body": "Fixes #5043 ",
"number": 5044,
"review_comments": [],
"title": "Check property exists instead of truthy value"
} | {
"commits": [
{
"message": "Check property exists instead of truthy value"
},
{
"message": "Provide some falsy values for inject tests"
}
],
"files": [
{
"diff": "@@ -25,7 +25,7 @@ export function initInjections (vm: Component) {\n const provideKey = isArray ? key : inject[key]\n let source = vm\n while (source) {\n- if (source._provided && source._provided[provideKey]) {\n+ if (source._provided && provideKey in source._provided) {\n vm[key] = source._provided[provideKey]\n break\n }",
"filename": "src/core/instance/inject.js",
"status": "modified"
},
{
"diff": "@@ -20,7 +20,7 @@ describe('Options provide/inject', () => {\n template: `<child/>`,\n provide: {\n foo: 1,\n- bar: 2\n+ bar: false\n },\n components: {\n child: {\n@@ -32,15 +32,15 @@ describe('Options provide/inject', () => {\n }\n }).$mount()\n \n- expect(injected).toEqual([1, 2])\n+ expect(injected).toEqual([1, false])\n })\n \n it('should use closest parent', () => {\n new Vue({\n template: `<child/>`,\n provide: {\n foo: 1,\n- bar: 2\n+ bar: null\n },\n components: {\n child: {\n@@ -55,15 +55,15 @@ describe('Options provide/inject', () => {\n }\n }).$mount()\n \n- expect(injected).toEqual([3, 2])\n+ expect(injected).toEqual([3, null])\n })\n \n it('provide function', () => {\n new Vue({\n template: `<child/>`,\n data: {\n a: 1,\n- b: 2\n+ b: false\n },\n provide () {\n return {\n@@ -81,7 +81,7 @@ describe('Options provide/inject', () => {\n }\n }).$mount()\n \n- expect(injected).toEqual([1, 2])\n+ expect(injected).toEqual([1, false])\n })\n \n it('inject with alias', () => {\n@@ -99,7 +99,7 @@ describe('Options provide/inject', () => {\n new Vue({\n template: `<child/>`,\n provide: {\n- foo: 1,\n+ foo: false,\n bar: 2\n },\n components: {\n@@ -112,7 +112,7 @@ describe('Options provide/inject', () => {\n }\n }).$mount()\n \n- expect(injected).toEqual([1, 2])\n+ expect(injected).toEqual([false, 2])\n })\n \n it('self-inject', () => {",
"filename": "test/unit/features/options/inject.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\r\n2.1.10\r\n\r\n### Reproduction Link\r\nhttps://jsfiddle.net/z11fe07p/686/#\r\n\r\n### Steps to reproduce\r\nThere seems to be an issue with the transition-group component when transitions is applied on each element iterating on a v-for with an initial empty array.\r\n\r\nWhenever you add (push) an item to the array before the previous transition is completed all previous transition will stop. But if you wait for the first transition to finish - but only on the first instance - and then try to add items all works as expected. Similar, if you fill the initial array with 1 or more values, all works as expected.\r\n\r\n### What is Expected?\r\nAll items should continue to animate.\r\n\r\n### What is actually happening?\r\nAnimation stops for all elements except for the last one added.\r\nIt seems that Vue detects a change in position and therefore replace all transition classes with the move class.",
"comments": [
{
"body": "i'm so sorry for my three pr\r\ni make some mistake",
"created_at": "2017-02-10T11:04:05Z"
},
{
"body": "hey, no need to apologise 😄 \r\nThanks for taking the time to make a PR",
"created_at": "2017-02-10T12:50:54Z"
},
{
"body": "@posva \r\ni cannot recurrent that when i write the unit test because the transition is in .test it is always been set\r\ni try to move transition from .wave-enter-active to .item then it work fine\r\nso is this still a bug\r\nhttps://jsfiddle.net/z11fe07p/706/\r\n",
"created_at": "2017-02-10T16:55:47Z"
},
{
"body": "@Kingwl Sorry for the delay. I believe it's a bug because if you wait for the first transition to finish there's no problem with the rest of the animations. It only happens if you add many items on the empty array without waiting for the first transition to finish. I'll check and see if I can help out 🙂 ",
"created_at": "2017-02-11T17:00:21Z"
}
],
"number": 4900,
"title": "Transition-group transition on empty array"
} | {
"body": "Following work from @kingwl\r\n#4900 \r\n\r\n<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n",
"number": 4911,
"review_comments": [
{
"body": "I think the class should actually be `test-empty-array-enter test-empty-array-enter-active` 😕 ",
"created_at": "2017-02-11T18:20:52Z"
},
{
"body": "NextFrame looks nextTwoFrame",
"created_at": "2017-02-13T04:02:28Z"
}
],
"title": "Fix transition"
} | {
"commits": [
{
"message": "fix transition-group transition on empty array"
},
{
"message": "Add test case for #4900"
},
{
"message": "fix nextFrame util and complete unit test"
},
{
"message": "Merge pull request #1 from Kingwl/fix-trans\n\nfix nextFrame util and complete unit test"
}
],
"files": [
{
"diff": "@@ -90,7 +90,7 @@ export default {\n updated () {\n const children = this.prevChildren\n const moveClass = this.moveClass || ((this.name || 'v') + '-move')\n- if (!children.length || !this.hasMove(children[0].elm, moveClass)) {\n+ if (!children.length || !children.every(c => this.hasMove(c.elm, moveClass))) {\n return\n }\n ",
"filename": "src/platforms/web/runtime/components/transition-group.js",
"status": "modified"
},
{
"diff": "@@ -69,6 +69,10 @@ export function nextFrame (fn: Function) {\n })\n }\n \n+export function nextOneFrame (fn: Function) {\n+ raf(fn)\n+}\n+\n export function addTransitionClass (el: any, cls: string) {\n (el._transitionClasses || (el._transitionClasses = [])).push(cls)\n addClass(el, cls)",
"filename": "src/platforms/web/runtime/transition-util.js",
"status": "modified"
},
{
"diff": "@@ -23,6 +23,7 @@ export default function injectStyles () {\n .v-appear, .v-enter, .v-leave-active,\n .test-appear, .test-enter, .test-leave-active,\n .hello, .bye.active,\n+ .test-empty-array-enter-active,\n .changed-enter {\n opacity: 0;\n }\n@@ -58,6 +59,10 @@ export default function injectStyles () {\n from { opacity: 1 }\n to { opacity: 0 }\n }\n+ .test-empty-array-enter-active, .test-empty-array-leave-active {\n+ -webkit-transition: opacity ${duration}ms ease;\n+ transition: opacity ${duration}ms ease;\n+ }\n `)\n return { duration, buffer }\n }",
"filename": "test/unit/features/transition/inject-styles.js",
"status": "modified"
},
{
"diff": "@@ -1,7 +1,7 @@\n import Vue from 'vue'\n import injectStyles from './inject-styles'\n import { isIE9 } from 'core/util/env'\n-import { nextFrame } from 'web/runtime/transition-util'\n+import { nextFrame, nextOneFrame } from 'web/runtime/transition-util'\n \n if (!isIE9) {\n describe('Transition group', () => {\n@@ -293,5 +293,58 @@ if (!isIE9) {\n }).$mount()\n expect('<transition-group> children must be keyed: <div>').toHaveBeenWarned()\n })\n+\n+ // Issue #4900\n+ it('stagger animations on initial empty children', done => {\n+ const vm = new Vue({\n+ template: `\n+ <div>\n+ <transition-group name=\"test-empty-array\">\n+ <div v-for=\"item in items\" :key=\"item\">{{ item }}</div>\n+ </transition-group>\n+ </div>\n+ `,\n+ data: {\n+ items: []\n+ }\n+ }).$mount(el)\n+ vm.items.push(0)\n+ waitForUpdate(() => {\n+ expect(vm.$el.innerHTML).toBe(\n+ `<span>` +\n+ `<div class=\"test-empty-array-enter test-empty-array-enter-active\">0</div>` +\n+ `</span>`\n+ )\n+ }).thenWaitFor(duration / 2).then(() => {\n+ vm.items.push(1)\n+ }).thenWaitFor(nextOneFrame).then(() => {\n+ expect(vm.$el.innerHTML).toBe(\n+ `<span>` +\n+ `<div class=\"test-empty-array-enter-active test-empty-array-enter-to\">0</div>` +\n+ `<div class=\"test-empty-array-enter test-empty-array-enter-active\">1</div>` +\n+ `</span>`\n+ )\n+ }).thenWaitFor(nextOneFrame).then(() => {\n+ expect(vm.$el.innerHTML).toBe(\n+ `<span>` +\n+ `<div class=\"test-empty-array-enter-active test-empty-array-enter-to\">0</div>` +\n+ `<div class=\"test-empty-array-enter-active test-empty-array-enter-to\">1</div>` +\n+ `</span>`\n+ )\n+ }).thenWaitFor(duration / 2).then(() => {\n+ expect(vm.$el.innerHTML).toBe(\n+ `<span>` +\n+ `<div class=\"\">0</div>` +\n+ `<div class=\"test-empty-array-enter-active test-empty-array-enter-to\">1</div>` +\n+ `</span>`\n+ )\n+ }).thenWaitFor(duration + buffer).then(() => {\n+ expect(vm.$el.innerHTML).toBe(\n+ `<span>` +\n+ vm.items.map(i => `<div class=\"\">${i}</div>`).join('') +\n+ `</span>`\n+ )\n+ }).then(done)\n+ })\n })\n }",
"filename": "test/unit/features/transition/transition-group.spec.js",
"status": "modified"
}
]
} |
{
"body": "Consider the following code:\n\n```\n<div id=\"demo\">\n <select v-model=\"selected\" number>\n <option v-for=\"opt in options\" :value=\"$index\" number>{{opt}}</option>\n </select>\n</div>\n```\n\nIn `<select>`, each option value is bound with `$index`. If we perform `splice()` on `options`, like, `options.splice(0,1)`, `$index` does not correctly sync with options.\n\nFor example, let `options=['a','b']` and the rendered HTML looks like (but not really):\n\n```\n<div id=\"demo\">\n <select selectedIndex=\"0\">\n <option value=\"0\">a</option>\n <option value=\"1\">b</option>\n </select>\n</div>\n```\n\nAfter `options.splice(0,1)`, then `options=['b']`, but the rendered HTML becomes:\n\n```\n<div id=\"demo\">\n <select selectedIndex=\"0\">\n <option value=\"1\">b</option>\n </select>\n</div>\n```\n\nThe value of 'b' option does not become 1, which should be 0 because of `$index`. This may not be a bug, but this is kind of odd.\n\nBelow is the live demo of this issue:\nhttps://jsfiddle.net/peteranny/trwp98g9/4/\n",
"comments": [
{
"body": "Just add a selected attribute in your template `selected=\"{{$index == selected}}\"`\n\nI update the demo here https://jsfiddle.net/trwp98g9/5/\n",
"created_at": "2016-10-01T04:24:40Z"
},
{
"body": "@peteranny Can you clarify what was the expected behavior?\n\n> After options.splice(0,1), then options=['b'], but the rendered HTML becomes:\n> `<option value=\"1\">b</option>`\n\nI'm not getting the same result as you provided from here:\nBefore clicking remove:\n\n\nAfter clicking:\n\n\n> The value of 'b' option does not become 1, which should be 0 because of $index\n\nSo what exactly should it become? The value of 'b' was 1 before click, and became 0 after click.\n",
"created_at": "2016-10-01T11:45:26Z"
},
{
"body": "@fnlctrl Um, thank you for your testing. I think I've asked the wrong question.\nAccording to your testing, the value of 'b' did become 0 after click.\n\nMy true question is: now that the value of 'b' was 0, why was `<select>` not selecting 'b' anyway?\nAs seen in your image, `<select>` did not select any option at all, while `<select>` is ought to select the option with the value 0.\n(And that is why I misguessed that the value of 'b' didn't change.)\n",
"created_at": "2016-10-02T15:48:45Z"
},
{
"body": "@peteranny It may be a bug because `selected` remained 0 while the `options` changed, and the dom is supposed to reflect this change, but I'm not sure..\n\nFor now, you can try adding `selected` prop as @defcc suggested, (note that mustache binding for props/attrs is deprecated in 2.0, so please use `:selected=\"$index == selected\"` instead)\nOr you can add a `track-by` prop to `<options>`, which probably made vue think it's safe to update the selected value in dom. https://jsfiddle.net/74ncq90w/\n",
"created_at": "2016-10-02T19:32:03Z"
},
{
"body": "Tested on 2.0 and it worked as expected: https://jsfiddle.net/dycmgzcm/\nSo I'm marking this as a bug of 1.x\n",
"created_at": "2016-10-02T19:36:24Z"
},
{
"body": "Closing 1.x issues as 1.x is now end of life and will only receive critical security patches.",
"created_at": "2018-04-17T21:38:51Z"
}
],
"number": 3821,
"title": "<select> bound with array performs incorrectly after splice()"
} | {
"body": "#3821 \r\n",
"number": 4874,
"review_comments": [],
"title": "fix select bound with error index - fix #3821"
} | {
"commits": [
{
"message": "fix select bound with error index"
}
],
"files": [
{
"diff": "@@ -16,7 +16,8 @@ import {\n def,\n cancellable,\n isArray,\n- isPlainObject\n+ isPlainObject,\n+ nextTick\n } from '../../util/index'\n \n let uid = 0\n@@ -304,7 +305,9 @@ const vFor = {\n var parent = this.start.parentNode\n var model = parent && parent.__v_model\n if (model) {\n- model.forceUpdate()\n+ nextTick(function () {\n+ model.forceUpdate()\n+ })\n }\n }\n },",
"filename": "src/directives/public/for.js",
"status": "modified"
},
{
"diff": "@@ -407,8 +407,9 @@ describe('v-model', function () {\n _.nextTick(function () {\n expect(opts[0].selected).toBe(true)\n expect(opts[1].selected).toBe(false)\n+ // select should after insert\n+ vm.opts.push({ text: 'c', value: { msg: 'C' } })\n vm.test = { msg: 'C' }\n- vm.opts.push({text: 'c', value: vm.test})\n _.nextTick(function () {\n // updating the opts array should force the\n // v-model to update\n@@ -421,6 +422,32 @@ describe('v-model', function () {\n })\n })\n \n+ // # GitHub issues #3821\n+ it('select + v-for with $index', function (done) {\n+ var vm = new Vue({\n+ el: el,\n+ data: {\n+ selected: 0,\n+ options: ['a', 'b']\n+ },\n+ template:\n+ '<select v-model=\"selected\">' +\n+ '<option v-for=\"opt in options\" :value=\"$index\">{{opt}}</option>' +\n+ '</select>'\n+ })\n+ var select = el.firstChild\n+ var options = select.options\n+ expect(vm.selected).toBe(0)\n+ expect(options[0].selected).toBe(true)\n+ expect(options[1].selected).toBe(false)\n+ vm.options.splice(0, 1)\n+ _.nextTick(function () {\n+ expect(vm.selected).toBe(0)\n+ expect(options[0].selected).toBe(true)\n+ done()\n+ })\n+ })\n+\n it('text', function (done) {\n var vm = new Vue({\n el: el,",
"filename": "test/unit/specs/directives/public/model_spec.js",
"status": "modified"
}
]
} |
{
"body": "<!-- BUG REPORT TEMPLATE -->\r\n### Vue.js version\r\n2.1.10\r\n\r\n### Reproduction Link\r\nhttp://jsfiddle.net/myuvgsj8/\r\n\r\n### What is actually happening?\r\nError:\r\nVM281 vue.js:525 [Vue warn]: <select multiple v-model=\"arr\"> expects an Array value for its binding, but got String \r\n(found in root instance)\r\n",
"comments": [
{
"body": "Thanks. It looks like a bug. I'm looking into it.",
"created_at": "2017-02-06T09:39:30Z"
},
{
"body": "It has been fixed already in the dev branch https://github.com/vuejs/vue/blob/dev/src/platforms/web/compiler/directives/model.js#L138",
"created_at": "2017-02-06T10:27:46Z"
}
],
"number": 4864,
"title": "<select v-model=\"arr\" v-bind:multiple=\"multiple\">"
} | {
"body": "Fix #4855\r\n\r\nedit: Is multiple supposed to be bindable at all? #4864\r\n\r\n<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n",
"number": 4859,
"review_comments": [],
"title": "Fix multiple attr in select with undefined value"
} | {
"commits": [
{
"message": "Fix multiple attr in select with undefined value\n\nFix #4855"
}
],
"files": [
{
"diff": "@@ -7,7 +7,8 @@ export function createElement (tagName: string, vnode: VNode): Element {\n if (tagName !== 'select') {\n return elm\n }\n- if (vnode.data && vnode.data.attrs && 'multiple' in vnode.data.attrs) {\n+ // false or null will remove the attribute but undefined will not\n+ if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {\n elm.setAttribute('multiple', 'multiple')\n }\n return elm",
"filename": "src/platforms/web/runtime/node-ops.js",
"status": "modified"
},
{
"diff": "@@ -287,6 +287,22 @@ describe('Directive v-model select', () => {\n }).then(done)\n })\n \n+ it('should not have multiple attr with falsy values except \\'\\'', () => {\n+ const vm = new Vue({\n+ template:\n+ '<div>' +\n+ '<select id=\"undefined\" :multiple=\"undefined\"></select>' +\n+ '<select id=\"null\" :multiple=\"null\"></select>' +\n+ '<select id=\"false\" :multiple=\"false\"></select>' +\n+ '<select id=\"string\" :multiple=\"\\'\\'\"></select>' +\n+ '</div>'\n+ }).$mount()\n+ expect(vm.$el.querySelector('#undefined').multiple).toEqual(false)\n+ expect(vm.$el.querySelector('#null').multiple).toEqual(false)\n+ expect(vm.$el.querySelector('#false').multiple).toEqual(false)\n+ expect(vm.$el.querySelector('#string').multiple).toEqual(true)\n+ })\n+\n it('multiple with static template', () => {\n const vm = new Vue({\n template:",
"filename": "test/unit/features/directives/model-select.spec.js",
"status": "modified"
}
]
} |
{
"body": "<!-- BUG REPORT TEMPLATE -->\r\n### Vue.js version\r\n2.1.10\r\n\r\n### Reproduction Link\r\nA variation on #4415 \r\nhttps://jsbin.com/heguyujupu/edit?html,console,output\r\n\r\n### Steps to reproduce\r\n```js\r\n{{ (price) / 100 | currency }}\r\n```\r\n\r\n### What is Expected?\r\nThis divided number gets filtered\r\n\r\n\r\n### What is actually happening?\r\nGet this error:\r\n\r\n```\r\n[Vue warn]: Property or method \\\"currency\\\" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. \r\n(found in root instance)\"\r\n```",
"comments": [
{
"body": "The parser think is a regex due to this check\r\n\r\n`\r\n(!p || !/[\\w$]/.test(p))\r\n`\r\nline 58 of *filter-parser.js*\r\n\r\n\r\nIf you test it with the close parenthesis ')' it gives true.\r\n\r\nI can add another 'if' and open a PR. If anyone see a better way just let me know",
"created_at": "2017-02-02T13:45:00Z"
},
{
"body": "Thanks for the quick response!\r\n\r\nSeems like `data[0] / 1` and `1. / 2` will blow up for the same reason. Might be worth rolling that into your PR.",
"created_at": "2017-02-03T09:11:09Z"
},
{
"body": "you're right I have to check all the parenthesis and the point. Is not the case for comma if I'm not wrong\r\n\r\n\r\n\r\n",
"created_at": "2017-02-03T10:53:54Z"
},
{
"body": "Added dot and square brackets verification",
"created_at": "2017-02-03T13:34:38Z"
}
],
"number": 4838,
"title": "Filter not recognized when filtered expression contains a '/' with ()"
} | {
"body": "The filter parser wasn't considering \"closing\" parentheses in the check for regex.\r\n\r\nFix for issue #4838 \r\n",
"number": 4844,
"review_comments": [
{
"body": "what about `{{ a++ / 5 }}` and `{{ privateVar__ / 5}}`? \r\n\r\n Template string or object literal probably does not need to be considered, IMHO,",
"created_at": "2017-02-07T09:58:07Z"
},
{
"body": "I didn't considered + and - and also _ I have to include those too",
"created_at": "2017-02-07T10:27:31Z"
},
{
"body": "made a quick test checking every single exception with `/[\\w).\\]\\+\\-\\_$]/` and it's working.\r\nMaybe there is a more generic way to do this",
"created_at": "2017-02-07T10:38:10Z"
}
],
"title": "filter division expression with parentheses (fix #4838)"
} | {
"commits": [
{
"message": "filter division expression with parentheses (fix #4838)"
},
{
"message": "verify also dot and square brackets"
},
{
"message": "missed a link check sorry for the useless commit"
},
{
"message": "added + - and _ support"
},
{
"message": "Merge branch 'dev' into division-parentheses"
}
],
"files": [
{
"diff": "@@ -55,7 +55,7 @@ export function parseFilters (exp: string): string {\n p = exp.charAt(j)\n if (p !== ' ') break\n }\n- if (!p || !/[\\w$]/.test(p)) {\n+ if (!p || !/[\\w).\\]\\+\\-\\_$]/.test(p)) {\n inRegex = true\n }\n }",
"filename": "src/compiler/parser/filter-parser.js",
"status": "modified"
},
{
"diff": "@@ -78,6 +78,68 @@ describe('Filters', () => {\n expect(vm.$el.textContent).toBe(String(1 / 4))\n })\n \n+ it('handle division with parenthesis', () => {\n+ const vm = new Vue({\n+ data: { a: 20 },\n+ template: `<div>{{ (a*2) / 5 | double }}</div>`,\n+ filters: { double: v => v * 2 }\n+ }).$mount()\n+ expect(vm.$el.textContent).toBe(String(16))\n+ })\n+\n+ it('handle division with dot', () => {\n+ const vm = new Vue({\n+ template: `<div>{{ 20. / 5 | double }}</div>`,\n+ filters: { double: v => v * 2 }\n+ }).$mount()\n+ expect(vm.$el.textContent).toBe(String(8))\n+ })\n+\n+ it('handle division with array values', () => {\n+ const vm = new Vue({\n+ data: { a: [20] },\n+ template: `<div>{{ a[0] / 5 | double }}</div>`,\n+ filters: { double: v => v * 2 }\n+ }).$mount()\n+ expect(vm.$el.textContent).toBe(String(8))\n+ })\n+\n+ it('handle division with hash values', () => {\n+ const vm = new Vue({\n+ data: { a: { n: 20 }},\n+ template: `<div>{{ a['n'] / 5 | double }}</div>`,\n+ filters: { double: v => v * 2 }\n+ }).$mount()\n+ expect(vm.$el.textContent).toBe(String(8))\n+ })\n+\n+ it('handle division with variable++', () => {\n+ const vm = new Vue({\n+ data: { a: 7 },\n+ template: `<div>{{ a++ / 2 | double }}</div>`,\n+ filters: { double: v => v * 2 }\n+ }).$mount()\n+ expect(vm.$el.textContent).toBe(String(7))\n+ })\n+\n+ it('handle division with variable--', () => {\n+ const vm = new Vue({\n+ data: { a: 7 },\n+ template: `<div>{{ a++ / 2 | double }}</div>`,\n+ filters: { double: v => v * 2 }\n+ }).$mount()\n+ expect(vm.$el.textContent).toBe(String(7))\n+ })\n+\n+ it('handle division with variable_', () => {\n+ const vm = new Vue({\n+ data: { a_: 8 },\n+ template: `<div>{{ a_ / 2 | double }}</div>`,\n+ filters: { double: v => v * 2 }\n+ }).$mount()\n+ expect(vm.$el.textContent).toBe(String(8))\n+ })\n+\n it('arguments', () => {\n const vm = new Vue({\n template: `<div>{{ msg | add(a, 3) }}</div>`,",
"filename": "test/unit/features/filter/filter.spec.js",
"status": "modified"
}
]
} |
{
"body": "<!-- BUG REPORT TEMPLATE -->\r\n### Vue.js version\r\n2.1.10\r\n\r\n### Reproduction Link\r\nhttps://jsfiddle.net/blackjid/br2h9pko/1/\r\n\r\n### Steps to reproduce\r\nHave and element with just one space inside a `<pre>` tag element.\r\n```html\r\n<div id=\"app\">\r\n <pre>\r\n <span> </span>\r\n </pre>\r\n</div>\r\n```\r\n\r\nand initialize vue in a parent element \r\n\r\n```js\r\nnew Vue({\r\n el: '#app'\r\n});\r\n```\r\n\r\n### What is Expected?\r\nVue initializes correctly.\r\n\r\n### What is actually happening?\r\nAn exception is thrown.\r\n\r\n```\r\nvue.js:7105 Uncaught TypeError: Cannot read property 'text' of undefined\r\n at Object.chars (vue.js:7105)\r\n at parseHTML (vue.js:6401)\r\n at parse (vue.js:6923)\r\n at compile$1 (vue.js:8003)\r\n at compile$$1 (vue.js:8425)\r\n at compileToFunctions (vue.js:8458)\r\n at Vue$3.$mount (vue.js:8536)\r\n at Vue$3.Vue._init (vue.js:3379)\r\n at new Vue$3 (vue.js:3427)\r\n```\r\n\r\n### What did I try\r\n- Adding a `v-pre` attribute to the `<pre>` tag or to a wrapper element. This didn't work either\r\n- Changing the space with a ` `. This worked, but you don't always control the code that you are bootstrapping vue on.",
"comments": [
{
"body": "A slightly modified test like this one triggers the error. https://github.com/vuejs/vue/blob/08bd81f8c0bd39816b5b509c5132a12188b412d7/test/unit/modules/compiler/parser.spec.js#L482-L490\r\n\r\n```js\r\n it('preserve whitespace in <pre> tag', function () {\r\n const options = extend({}, baseOptions)\r\n const ast = parse('<pre><code> \\n<span> </span>\\n </code></pre>', options)\r\n const code = ast.children[0]\r\n expect(code.children[0].type).toBe(3)\r\n expect(code.children[0].text).toBe(' \\n')\r\n expect(code.children[2].type).toBe(3)\r\n expect(code.children[2].text).toBe('\\n ')\r\n })\r\n```\r\n\r\nI also pinpoint this line, that has a comment that describes the problem.\r\n\r\nhttps://github.com/vuejs/vue/blob/80a7ceace62f1d9c5a9b93182aacc0b35cef1115/packages/vue-template-compiler/build.js#L1373-L1376",
"created_at": "2017-01-20T03:48:50Z"
},
{
"body": "Hey! thanks!, that was fast!",
"created_at": "2017-01-20T14:53:14Z"
}
],
"number": 4758,
"title": "Parser fails on tags with one space inside a <pre> tag"
} | {
"body": "fix #4758 ",
"number": 4760,
"review_comments": [],
"title": "Preserve the only whitespace child in pre (fix #4758)"
} | {
"commits": [
{
"message": "preserve the only whitespace child"
},
{
"message": "Merge remote-tracking branch 'originUpstream/dev' into whitespace-in-pre-fix"
}
],
"files": [
{
"diff": "@@ -197,7 +197,7 @@ export function parse (\n // remove trailing whitespace\n const element = stack[stack.length - 1]\n const lastNode = element.children[element.children.length - 1]\n- if (lastNode && lastNode.type === 3 && lastNode.text === ' ') {\n+ if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {\n element.children.pop()\n }\n // pop stack\n@@ -242,7 +242,7 @@ export function parse (\n expression,\n text\n })\n- } else if (text !== ' ' || children[children.length - 1].text !== ' ') {\n+ } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {\n currentParent.children.push({\n type: 3,\n text",
"filename": "src/compiler/parser/index.js",
"status": "modified"
},
{
"diff": "@@ -481,12 +481,16 @@ describe('parser', () => {\n \n it('preserve whitespace in <pre> tag', function () {\n const options = extend({}, baseOptions)\n- const ast = parse('<pre><code> \\n<span>hi</span>\\n </code></pre>', options)\n+ const ast = parse('<pre><code> \\n<span>hi</span>\\n </code><span> </span></pre>', options)\n const code = ast.children[0]\n expect(code.children[0].type).toBe(3)\n expect(code.children[0].text).toBe(' \\n')\n expect(code.children[2].type).toBe(3)\n expect(code.children[2].text).toBe('\\n ')\n+\n+ const span = ast.children[1]\n+ expect(span.children[0].type).toBe(3)\n+ expect(span.children[0].text).toBe(' ')\n })\n \n it('forgivingly handle < in plain text', () => {",
"filename": "test/unit/modules/compiler/parser.spec.js",
"status": "modified"
}
]
} |
{
"body": "Hello! First of all thank you for the great framework and your work.\r\n\r\nI faced issue when tried to use select html tag with binded multiple attribute. But it does not work.\r\nI have example on jsfiddle: https://jsfiddle.net/jqybwngo/\r\n\r\nPartially copy bellow:\r\n```html\r\n<div id=\"app\">\r\n <select v-model=\"option\" v-bind:multiple=\"isMultiple\">\r\n <option value=\"1\">item 1</option>\r\n <option value=\"2\">item 2</option>\r\n </select>\r\n</div>\r\n```\r\n\r\nAnd here is the error log from Safari (same for Firefox):\r\n\r\n\r\n```[Error] [Vue warn]: <select multiple v-model=\"option\"> expects an Array value for its binding, but got String \r\n(found in root instance)\r\n\twarn (vue.js:525)\r\n\tsetSelected (vue.js:5691)\r\n\tcomponentUpdated (vue.js:5672)\r\n\tcallHook$1 (vue.js:4746)\r\n\t(anonymous function) (vue.js:4702)\r\n\tpatchVnode (vue.js:4461)\r\n\tupdateChildren (vue.js:4364)\r\n\tpatchVnode (vue.js:4448)\r\n\tpatch (vue.js:4572)\r\n\t_update (vue.js:2646)\r\n\tupdateComponent (vue.js:2613)\r\n\tget (vue.js:2936)\r\n\trun (vue.js:3005)\r\n\tflushSchedulerQueue (vue.js:2811)\r\n\t(anonymous function) (vue.js:477)\r\n\tnextTickHandler (vue.js:426)\r\n\tpromiseReactionJob\r\n[Error] TypeError: binding.value.some is not a function. (In 'binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); })', 'binding.value.some' is undefined)\r\ncomponentUpdated — vue.js:5678\r\ncallHook$1 — vue.js:4746\r\nhttps://unpkg.com/vue\r\npatchVnode — vue.js:4461\r\nupdateChildren — vue.js:4364\r\npatchVnode — vue.js:4448\r\npatch — vue.js:4572\r\n_update — vue.js:2646\r\nupdateComponent — vue.js:2613\r\nget — vue.js:2936\r\nrun — vue.js:3005\r\nflushSchedulerQueue — vue.js:2811\r\nhttps://unpkg.com/vue\r\nnextTickHandler — vue.js:426\r\npromiseReactionJob\r\n\r\n\tlogError (vue.js:439)\r\n\tpromiseReactionJob\r\n```\r\n\r\n### What is Expected?\r\n\r\nOption is filled by array of selected values\r\n\r\n### What is actually happening?\r\n\r\nError reported in log, no parameter assigned.",
"comments": [
{
"body": "Note: The example works if `mutliple` is not bound with `v-bind`: https://jsfiddle.net/Linusborg/jqybwngo/2/\r\n",
"created_at": "2017-01-19T14:03:04Z"
}
],
"number": 4755,
"title": "Bug with dynamic binding multiple for select tag."
} | {
"body": "Determine multiple in runtime. fix #4755 ",
"number": 4756,
"review_comments": [
{
"body": "This can make the generated code quite verbose since `selectedVal` is repeated twice. We can store it in a runtime temp variable (e.g. `$$selectedVal`)",
"created_at": "2017-01-19T14:46:15Z"
},
{
"body": "ok, I'll update it.",
"created_at": "2017-01-19T16:41:56Z"
},
{
"body": "fixed",
"created_at": "2017-01-19T17:06:03Z"
}
],
"title": "Support select multiple binding (fix #4755)"
} | {
"commits": [
{
"message": "support select multiple binding"
},
{
"message": "Merge remote-tracking branch 'originUpstream/dev' into dynamic-select-multiple"
},
{
"message": "improve select onchange handle"
},
{
"message": "update style"
}
],
"files": [
{
"diff": "@@ -163,13 +163,14 @@ function genSelect (\n }\n \n const number = modifiers && modifiers.number\n- const assignment = `Array.prototype.filter` +\n+ const selectedVal = `Array.prototype.filter` +\n `.call($event.target.options,function(o){return o.selected})` +\n `.map(function(o){var val = \"_value\" in o ? o._value : o.value;` +\n- `return ${number ? '_n(val)' : 'val'}})` +\n- (el.attrsMap.multiple == null ? '[0]' : '')\n+ `return ${number ? '_n(val)' : 'val'}})`\n \n- const code = genAssignmentCode(value, assignment)\n+ const assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'\n+ let code = `var $$selectedVal = ${selectedVal};`\n+ code = `${code} ${genAssignmentCode(value, assignment)}`\n addHandler(el, 'change', code, null, true)\n }\n ",
"filename": "src/platforms/web/compiler/directives/model.js",
"status": "modified"
},
{
"diff": "@@ -262,6 +262,31 @@ describe('Directive v-model select', () => {\n })\n }\n \n+ it('should work with multiple binding', (done) => {\n+ const spy = jasmine.createSpy()\n+ const vm = new Vue({\n+ data: {\n+ isMultiple: true,\n+ selections: ['1']\n+ },\n+ template:\n+ '<select v-model=\"selections\" :multiple=\"isMultiple\">' +\n+ '<option value=\"1\">item 1</option>' +\n+ '<option value=\"2\">item 2</option>' +\n+ '</select>',\n+ watch: {\n+ selections: spy\n+ }\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ vm.$el.options[1].selected = true\n+ triggerEvent(vm.$el, 'change')\n+ waitForUpdate(() => {\n+ expect(spy).toHaveBeenCalled()\n+ expect(vm.selections).toEqual(['1', '2'])\n+ }).then(done)\n+ })\n+\n it('multiple with static template', () => {\n const vm = new Vue({\n template:",
"filename": "test/unit/features/directives/model-select.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\r\n2.1.8\r\n\r\n### Reproduction Link\r\nhttps://jsfiddle.net/bacft9s7/\r\n\r\n### Steps to reproduce\r\nClicks on the <A> element more than once.\r\n\r\n### What is Expected?\r\nThe event handler should be removed after the first click.\r\n\r\n### What is actually happening?\r\nThe event handler except for the last one with .once modifier is not removed.\r\n",
"comments": [],
"number": 4655,
"title": ".once modifier for v-on except for the last one doesn't work if more than one .once modifier used for v-on in multiple elements"
} | {
"body": "Fix issue #4655\r\n",
"number": 4657,
"review_comments": [],
"title": "Multiple elements event handler with .once modifier no removal bug fixed"
} | {
"commits": [
{
"message": "Multiple elements event handler with .once modifier no removal bug fixed"
},
{
"message": "Change target to const"
}
],
"files": [
{
"diff": "@@ -2,32 +2,31 @@\n \n import { updateListeners } from 'core/vdom/helpers/index'\n \n-let target: HTMLElement\n+function updateDOMListeners (oldVnode: VNodeWithData, vnode: VNodeWithData) {\n+ const target: HTMLElement = vnode.elm\n \n-function add (event: string, handler: Function, once: boolean, capture: boolean) {\n- if (once) {\n- const oldHandler = handler\n- handler = function (ev) {\n- remove(event, handler, capture)\n- arguments.length === 1\n- ? oldHandler(ev)\n- : oldHandler.apply(null, arguments)\n+ function add (event: string, handler: Function, once: boolean, capture: boolean) {\n+ if (once) {\n+ const oldHandler = handler\n+ handler = function (ev) {\n+ remove(event, handler, capture)\n+ arguments.length === 1\n+ ? oldHandler(ev)\n+ : oldHandler.apply(null, arguments)\n+ }\n }\n+ target.addEventListener(event, handler, capture)\n }\n- target.addEventListener(event, handler, capture)\n-}\n \n-function remove (event: string, handler: Function, capture: boolean) {\n- target.removeEventListener(event, handler, capture)\n-}\n+ function remove (event: string, handler: Function, capture: boolean) {\n+ target.removeEventListener(event, handler, capture)\n+ }\n \n-function updateDOMListeners (oldVnode: VNodeWithData, vnode: VNodeWithData) {\n if (!oldVnode.data.on && !vnode.data.on) {\n return\n }\n const on = vnode.data.on || {}\n const oldOn = oldVnode.data.on || {}\n- target = vnode.elm\n updateListeners(on, oldOn, add, remove, vnode.context)\n }\n ",
"filename": "src/platforms/web/runtime/modules/events.js",
"status": "modified"
}
]
} |
{
"body": "Example: https://jsfiddle.net/vfmxxzeb/3/\r\n\r\nWhat the example does:\r\n1. Resets `values` to an array of values every one second\r\n2. Each line has two checkboxes, both of which are bound to the same value\r\n\r\nSteps to reproduce:\r\n1. *Click* on the enabled checkbox on any line\r\n\r\nExpected behaviour:\r\n1. After one second, the value should be reset. Both checkboxes should reflect the same value\r\n\r\nActual behaviour (tested on Chrome):\r\n1. The disabled checkbox correctly reflects the value, but the enabled checkbox does not reflect the value. The enabled checkbox will reflect the correct value only after blurring from the checkbox",
"comments": [
{
"body": "Thanks @xkjyeah, I'll try to fix it.",
"created_at": "2016-12-31T16:15:54Z"
}
],
"number": 4620,
"title": "Checkbox :checked is not fully reactive when checkbox is in focus"
} | {
"body": "fix #4620 \r\n\r\n1. use *click* event instead of *change* event.\r\n2. add test case for #4521 ",
"number": 4639,
"review_comments": [],
"title": "Use 'click' event for checkbox and radio (fix #4620)"
} | {
"commits": [
{
"message": "listen to click event for checkbox and radio."
},
{
"message": "add test cases"
}
],
"files": [
{
"diff": "@@ -59,7 +59,7 @@ function genCheckboxModel (\n `?_i(${value},${valueBinding})>-1` +\n `:_q(${value},${trueValueBinding})`\n )\n- addHandler(el, 'change',\n+ addHandler(el, 'click',\n `var $$a=${value},` +\n '$$el=$event.target,' +\n `$$c=$$el.checked?(${trueValueBinding}):(${falseValueBinding});` +\n@@ -90,7 +90,7 @@ function genRadioModel (\n let valueBinding = getBindingAttr(el, 'value') || 'null'\n valueBinding = number ? `_n(${valueBinding})` : valueBinding\n addProp(el, 'checked', `_q(${value},${valueBinding})`)\n- addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true)\n+ addHandler(el, 'click', genAssignmentCode(value, valueBinding), null, true)\n }\n \n function genDefaultModel (",
"filename": "src/platforms/web/compiler/directives/model.js",
"status": "modified"
},
{
"diff": "@@ -29,13 +29,7 @@ function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {\n if (vnode.children) vnode.children.length = 0\n if (cur === oldProps[key]) continue\n }\n- // #4521: if a click event triggers update before the change event is\n- // dispatched on a checkbox/radio input, the input's checked state will\n- // be reset and fail to trigger another update.\n- /* istanbul ignore next */\n- if (key === 'checked' && !isDirty(elm, cur)) {\n- continue\n- }\n+\n if (key === 'value') {\n // store value as _value as well since\n // non-string values will be stringified\n@@ -59,17 +53,15 @@ function shouldUpdateValue (\n vnode: VNodeWithData,\n checkVal: string\n ): boolean {\n- if (!elm.composing && (\n+ return (!elm.composing && (\n vnode.tag === 'option' ||\n isDirty(elm, checkVal) ||\n isInputChanged(vnode, checkVal)\n- )) {\n- return true\n- }\n- return false\n+ ))\n }\n \n function isDirty (elm: acceptValueElm, checkVal: string): boolean {\n+ // return true when textbox (.number and .trim) loses focus and its value is not equal to the updated value\n return document.activeElement !== elm && elm.value !== checkVal\n }\n ",
"filename": "src/platforms/web/runtime/modules/dom-props.js",
"status": "modified"
},
{
"diff": "@@ -148,7 +148,7 @@ describe('Directive v-model checkbox', () => {\n `\n }).$mount()\n document.body.appendChild(vm.$el)\n- var checkboxInputs = vm.$el.getElementsByTagName('input')\n+ const checkboxInputs = vm.$el.getElementsByTagName('input')\n expect(checkboxInputs[0].checked).toBe(false)\n expect(checkboxInputs[1].checked).toBe(false)\n expect(checkboxInputs[2].checked).toBe(true)\n@@ -173,7 +173,7 @@ describe('Directive v-model checkbox', () => {\n '<input type=\"checkbox\" value=\"true\" v-model=\"test\">' +\n '</div>'\n }).$mount()\n- var checkboxInput = vm.$el.children\n+ const checkboxInput = vm.$el.children\n expect(checkboxInput[0].checked).toBe(false)\n expect(checkboxInput[1].checked).toBe(true)\n expect(checkboxInput[2].checked).toBe(false)\n@@ -217,6 +217,46 @@ describe('Directive v-model checkbox', () => {\n }).then(done)\n })\n \n+ // #4521\n+ it('should work with click event', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ num: 1,\n+ checked: false\n+ },\n+ template: '<div @click=\"add\">click {{ num }}<input ref=\"checkbox\" type=\"checkbox\" v-model=\"checked\"/></div>',\n+ methods: {\n+ add: function () {\n+ this.num++\n+ }\n+ }\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ const checkbox = vm.$refs.checkbox\n+ checkbox.click()\n+ waitForUpdate(() => {\n+ expect(checkbox.checked).toBe(true)\n+ expect(vm.num).toBe(2)\n+ }).then(done)\n+ })\n+\n+ it('should get updated with model when in focus', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ a: '2'\n+ },\n+ template: '<input type=\"checkbox\" value=\"1\" v-model=\"a\"/>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ vm.$el.click()\n+ waitForUpdate(() => {\n+ expect(vm.$el.checked).toBe(true)\n+ vm.a = 2\n+ }).then(() => {\n+ expect(vm.$el.checked).toBe(false)\n+ }).then(done)\n+ })\n+\n it('warn inline checked', () => {\n const vm = new Vue({\n template: `<input type=\"checkbox\" v-model=\"test\" checked>`,",
"filename": "test/unit/features/directives/model-checkbox.spec.js",
"status": "modified"
},
{
"diff": "@@ -197,6 +197,61 @@ describe('Directive v-model radio', () => {\n }).then(done)\n })\n \n+ // #4521\n+ it('should work with click event', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ num: 1,\n+ checked: 1\n+ },\n+ template:\n+ '<div @click=\"add\">' +\n+ 'click {{ num }}<input name=\"test\" type=\"radio\" value=\"1\" v-model=\"checked\"/>' +\n+ '<input name=\"test\" type=\"radio\" value=\"2\" v-model=\"checked\"/>' +\n+ '</div>',\n+ methods: {\n+ add: function () {\n+ this.num++\n+ }\n+ }\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ const radios = vm.$el.getElementsByTagName('input')\n+ radios[0].click()\n+ waitForUpdate(() => {\n+ expect(radios[0].checked).toBe(true)\n+ expect(radios[1].checked).toBe(false)\n+ expect(vm.num).toBe(2)\n+ radios[0].click()\n+ }).then(() => {\n+ expect(radios[0].checked).toBe(true)\n+ expect(radios[1].checked).toBe(false)\n+ expect(vm.num).toBe(3)\n+ radios[1].click()\n+ }).then(() => {\n+ expect(radios[0].checked).toBe(false)\n+ expect(radios[1].checked).toBe(true)\n+ expect(vm.num).toBe(4)\n+ }).then(done)\n+ })\n+\n+ it('should get updated with model when in focus', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ a: '2'\n+ },\n+ template: '<input type=\"radio\" value=\"1\" v-model=\"a\"/>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ vm.$el.click()\n+ waitForUpdate(() => {\n+ expect(vm.$el.checked).toBe(true)\n+ vm.a = 2\n+ }).then(() => {\n+ expect(vm.$el.checked).toBe(false)\n+ }).then(done)\n+ })\n+\n it('warn inline checked', () => {\n const vm = new Vue({\n template: `<input v-model=\"test\" type=\"radio\" value=\"1\" checked>`,",
"filename": "test/unit/features/directives/model-radio.spec.js",
"status": "modified"
}
]
} |
{
"body": "<!--\r\n中文用户请注意:\r\n\r\n1. issue 只接受带重现的 bug 报告,请不要用来提问题!不符合要求的 issue 会被直接关闭。\r\n2. 请尽量用英文描述你的 issue,这样能够让尽可能多的人帮到你。\r\n\r\nGot a question?\r\n===============\r\nThe issue list of this repo is **exclusively** for bug reports and feature requests. For simple questions, please use the following resources:\r\n\r\n- Read the docs: https://vuejs.org/guide/\r\n- Watch video tutorials: https://laracasts.com/series/learning-vue-step-by-step\r\n- Ask in the Gitter chat room: https://gitter.im/vuejs/vue\r\n- Ask on the forums: http://forum.vuejs.org/\r\n- Look for/ask questions on stack overflow: https://stackoverflow.com/questions/ask?tags=vue.js\r\n\r\nReporting a bug?\r\n================\r\n- Try to search for your issue, it may have already been answered or even fixed in the development branch.\r\n\r\n- Check if the issue is reproducible with the latest stable version of Vue. If you are using a pre-release, please indicate the specific version you are using.\r\n\r\n- It is **required** that you clearly describe the steps necessary to reproduce the issue you are running into. Issues with no clear repro steps will not be triaged. If an issue labeled \"need repro\" receives no further input from the issue author for more than 5 days, it will be closed.\r\n\r\n- It is recommended that you make a JSFiddle/JSBin/Codepen to demonstrate your issue. You could start with [this template](http://jsfiddle.net/5sH6A/) that already includes the latest version of Vue.\r\n\r\n- For bugs that involves build setups, you can create a reproduction repository with steps in the README.\r\n\r\n- If your issue is resolved but still open, don’t hesitate to close it. In case you found a solution by yourself, it could be helpful to explain how you fixed it.\r\n\r\nHave a feature request?\r\n=======================\r\nRemove the template from below and provide thoughtful commentary *and code samples* on what this feature means for your product. What will it allow you to do that you can't do today? How will it make current work-arounds straightforward? What potential bugs and edge cases does it help to avoid? etc. Please keep it product-centric.\r\n-->\r\n\r\n<!-- BUG REPORT TEMPLATE -->\r\n### Vue.js version\r\n2.1.6 \r\n\r\n### Reproduction Link\r\n<!-- A minimal JSBin, JSFiddle, Codepen, or a GitHub repository that can reproduce the bug. -->\r\n<!-- You could start with this template: http://jsfiddle.net/df4Lnuw6/ -->\r\nhttp://codepen.io/qbaty/pen/NboZoz?editors=1111\r\n\r\n### Steps to reproduce\r\nmy html is div > input[type=checkbox]\r\nwhen div with v-on:click, I found that the input element can not be selected.\r\n\r\n### What is Expected?\r\nwhen click this input checkbox, checkbox should be selected or canceled.\r\ndiv click event will trigger.\r\n\r\n### What is actually happening?\r\nI have not read the source code,But I think div capture this click event and should not stop this event immediate, it kinda like use “event.stopImmediatePropagation” stop the event progagation?\r\n",
"comments": [
{
"body": "<input type=\"checkbox\" v-model=\"checked\">\r\nv-model ?!",
"created_at": "2016-12-20T06:20:25Z"
},
{
"body": "@Marshare I do not think you understand my problem。",
"created_at": "2016-12-20T07:13:41Z"
},
{
"body": "@qbaty `@click.self=\"add\" `",
"created_at": "2016-12-20T08:33:41Z"
},
{
"body": "@qbaty Thanks for rteporting this, looks like a bug indeed!\r\n\r\nI took the freedom to correct the Vue version in your OP, as you use 2.1.6, noch 2.0.3",
"created_at": "2016-12-20T08:38:16Z"
},
{
"body": "@LinusBorg Okey first I met this bug when I am using vue 2.0.3,and I try to update vue to the lastest version. this bug still exsit, so ... version should be 2.x",
"created_at": "2016-12-20T10:05:06Z"
},
{
"body": "Seems fixing this bug created a new bug for :checked=\"\" binding when using in combination with vuex states for maintaining checkbox states.\r\n\r\n```javascript\r\n<template>\r\n\t<ul>\r\n\t\t<li v-for=\"option in visibleOptions\" :key=\"option.value\">\r\n\t\t\t<input\r\n\t\t\t\ttype=\"checkbox\"\r\n\t\t\t\t:name=\"filter.key\"\r\n\t\t\t\t:value=\"option.value\"\r\n\t\t\t\t:checked=\"inArray(option.value, filter.active)\"\r\n\t\t\t\t@change=\"updateFilter\">\r\n\t\t</li>\r\n\t</ul>\r\n</template>\r\n```\r\nIn this code example is :checked set to true or false whenever it's in the active filter array.\r\nIt seems when this component is updated (via vuex) the :checked stated doesn't get's updated like in 2.1.6. In my application is the state managed _almost_ totally by Vuex. \r\n\r\n### Vue.js version\r\n2.1.7+\r\n\r\n### Reproduction Link\r\nhttp://vroom.automotivated.nl/\r\n\r\n### Howto reproduce\r\nWhen selecting several checkboxes (like brands) and use your **browser back button** to fallback to previous states. (it's managed by the popstate event)\r\n\r\n### What is expected\r\nThe checkbox will go on or off depending on the previous action.\r\n\r\n### What is actually happening?\r\nEverything get's correctly updated (value wise), except the checkbox isn't honored to update (checked true/false). It keeps in a previous state. When selecting multiple after eachother and navigating back and forward is looks like is off a beat and missing the last changed checkbox.\r\n\r\nCode that goes with it:\r\nhttps://github.com/Automotivated/vroom/blob/master/src/views/elements/filters/Multiple.vue\r\n\r\nWhile reading the [docs](https://vuex.vuejs.org/en/forms.html) in Vuex, it seems to be best practise to do it like I did. \r\n\r\n### When did it work\r\nIt worked like a charm in 2.1.6. Seems really that fixing this bug triggered this bug to be created.",
"created_at": "2017-01-12T22:29:53Z"
},
{
"body": "@FKobus Please open a new issue instead of adding to the bottom of closed ones. Thanks!",
"created_at": "2017-01-12T22:39:24Z"
},
{
"body": "干得漂亮",
"created_at": "2019-03-13T02:17:37Z"
}
],
"number": 4521,
"title": "checkbox can not be selected if it's in a element with @click listener?"
} | {
"body": "fix #4620 \r\n\r\n1. use *click* event instead of *change* event.\r\n2. add test case for #4521 ",
"number": 4639,
"review_comments": [],
"title": "Use 'click' event for checkbox and radio (fix #4620)"
} | {
"commits": [
{
"message": "listen to click event for checkbox and radio."
},
{
"message": "add test cases"
}
],
"files": [
{
"diff": "@@ -59,7 +59,7 @@ function genCheckboxModel (\n `?_i(${value},${valueBinding})>-1` +\n `:_q(${value},${trueValueBinding})`\n )\n- addHandler(el, 'change',\n+ addHandler(el, 'click',\n `var $$a=${value},` +\n '$$el=$event.target,' +\n `$$c=$$el.checked?(${trueValueBinding}):(${falseValueBinding});` +\n@@ -90,7 +90,7 @@ function genRadioModel (\n let valueBinding = getBindingAttr(el, 'value') || 'null'\n valueBinding = number ? `_n(${valueBinding})` : valueBinding\n addProp(el, 'checked', `_q(${value},${valueBinding})`)\n- addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true)\n+ addHandler(el, 'click', genAssignmentCode(value, valueBinding), null, true)\n }\n \n function genDefaultModel (",
"filename": "src/platforms/web/compiler/directives/model.js",
"status": "modified"
},
{
"diff": "@@ -29,13 +29,7 @@ function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {\n if (vnode.children) vnode.children.length = 0\n if (cur === oldProps[key]) continue\n }\n- // #4521: if a click event triggers update before the change event is\n- // dispatched on a checkbox/radio input, the input's checked state will\n- // be reset and fail to trigger another update.\n- /* istanbul ignore next */\n- if (key === 'checked' && !isDirty(elm, cur)) {\n- continue\n- }\n+\n if (key === 'value') {\n // store value as _value as well since\n // non-string values will be stringified\n@@ -59,17 +53,15 @@ function shouldUpdateValue (\n vnode: VNodeWithData,\n checkVal: string\n ): boolean {\n- if (!elm.composing && (\n+ return (!elm.composing && (\n vnode.tag === 'option' ||\n isDirty(elm, checkVal) ||\n isInputChanged(vnode, checkVal)\n- )) {\n- return true\n- }\n- return false\n+ ))\n }\n \n function isDirty (elm: acceptValueElm, checkVal: string): boolean {\n+ // return true when textbox (.number and .trim) loses focus and its value is not equal to the updated value\n return document.activeElement !== elm && elm.value !== checkVal\n }\n ",
"filename": "src/platforms/web/runtime/modules/dom-props.js",
"status": "modified"
},
{
"diff": "@@ -148,7 +148,7 @@ describe('Directive v-model checkbox', () => {\n `\n }).$mount()\n document.body.appendChild(vm.$el)\n- var checkboxInputs = vm.$el.getElementsByTagName('input')\n+ const checkboxInputs = vm.$el.getElementsByTagName('input')\n expect(checkboxInputs[0].checked).toBe(false)\n expect(checkboxInputs[1].checked).toBe(false)\n expect(checkboxInputs[2].checked).toBe(true)\n@@ -173,7 +173,7 @@ describe('Directive v-model checkbox', () => {\n '<input type=\"checkbox\" value=\"true\" v-model=\"test\">' +\n '</div>'\n }).$mount()\n- var checkboxInput = vm.$el.children\n+ const checkboxInput = vm.$el.children\n expect(checkboxInput[0].checked).toBe(false)\n expect(checkboxInput[1].checked).toBe(true)\n expect(checkboxInput[2].checked).toBe(false)\n@@ -217,6 +217,46 @@ describe('Directive v-model checkbox', () => {\n }).then(done)\n })\n \n+ // #4521\n+ it('should work with click event', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ num: 1,\n+ checked: false\n+ },\n+ template: '<div @click=\"add\">click {{ num }}<input ref=\"checkbox\" type=\"checkbox\" v-model=\"checked\"/></div>',\n+ methods: {\n+ add: function () {\n+ this.num++\n+ }\n+ }\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ const checkbox = vm.$refs.checkbox\n+ checkbox.click()\n+ waitForUpdate(() => {\n+ expect(checkbox.checked).toBe(true)\n+ expect(vm.num).toBe(2)\n+ }).then(done)\n+ })\n+\n+ it('should get updated with model when in focus', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ a: '2'\n+ },\n+ template: '<input type=\"checkbox\" value=\"1\" v-model=\"a\"/>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ vm.$el.click()\n+ waitForUpdate(() => {\n+ expect(vm.$el.checked).toBe(true)\n+ vm.a = 2\n+ }).then(() => {\n+ expect(vm.$el.checked).toBe(false)\n+ }).then(done)\n+ })\n+\n it('warn inline checked', () => {\n const vm = new Vue({\n template: `<input type=\"checkbox\" v-model=\"test\" checked>`,",
"filename": "test/unit/features/directives/model-checkbox.spec.js",
"status": "modified"
},
{
"diff": "@@ -197,6 +197,61 @@ describe('Directive v-model radio', () => {\n }).then(done)\n })\n \n+ // #4521\n+ it('should work with click event', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ num: 1,\n+ checked: 1\n+ },\n+ template:\n+ '<div @click=\"add\">' +\n+ 'click {{ num }}<input name=\"test\" type=\"radio\" value=\"1\" v-model=\"checked\"/>' +\n+ '<input name=\"test\" type=\"radio\" value=\"2\" v-model=\"checked\"/>' +\n+ '</div>',\n+ methods: {\n+ add: function () {\n+ this.num++\n+ }\n+ }\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ const radios = vm.$el.getElementsByTagName('input')\n+ radios[0].click()\n+ waitForUpdate(() => {\n+ expect(radios[0].checked).toBe(true)\n+ expect(radios[1].checked).toBe(false)\n+ expect(vm.num).toBe(2)\n+ radios[0].click()\n+ }).then(() => {\n+ expect(radios[0].checked).toBe(true)\n+ expect(radios[1].checked).toBe(false)\n+ expect(vm.num).toBe(3)\n+ radios[1].click()\n+ }).then(() => {\n+ expect(radios[0].checked).toBe(false)\n+ expect(radios[1].checked).toBe(true)\n+ expect(vm.num).toBe(4)\n+ }).then(done)\n+ })\n+\n+ it('should get updated with model when in focus', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ a: '2'\n+ },\n+ template: '<input type=\"radio\" value=\"1\" v-model=\"a\"/>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ vm.$el.click()\n+ waitForUpdate(() => {\n+ expect(vm.$el.checked).toBe(true)\n+ vm.a = 2\n+ }).then(() => {\n+ expect(vm.$el.checked).toBe(false)\n+ }).then(done)\n+ })\n+\n it('warn inline checked', () => {\n const vm = new Vue({\n template: `<input v-model=\"test\" type=\"radio\" value=\"1\" checked>`,",
"filename": "test/unit/features/directives/model-radio.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\r\n2.1.6\r\n\r\n### Reproduction Link\r\nhttp://jsfiddle.net/od3m0ta9/\r\n\r\n### Steps to reproduce\r\nGiven the following code\r\n\r\n```html\r\n<html>\r\n <body>\r\n <div id=\"vue\">\r\n <div style=\"background: blue;\" v-if=\"!message\">Something</div>\r\n <div style=\"background: red;\" v-if=\"message\" v-text=\"message\"></div>\r\n <button v-on:click=\"buttonClicked\">Click me</button>\r\n </div>\r\n\r\n <script src=\"https://unpkg.com/vue@2.1.6/dist/vue.js\"></script>\r\n\r\n <script>\r\n var vue = new Vue({\r\n el: '#vue',\r\n data: {\r\n message: null\r\n },\r\n methods: {\r\n buttonClicked: function() {\r\n this.message = \"Hello @ \" + new Date();\r\n }\r\n }\r\n });\r\n </script>\r\n </body>\r\n</html>\r\n```\r\n\r\nclicking the button causes the following exception to be thrown in the Chrome Version 55.0.2883.95 (64-bit) console\r\n\r\n```\r\nDOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.\r\n at Object.removeChild (https://unpkg.com/vue@2.1.6/dist/vue.js:3825:8)\r\n at removeVnodes (https://unpkg.com/vue@2.1.6/dist/vue.js:4188:19)\r\n at patchVnode (https://unpkg.com/vue@2.1.6/dist/vue.js:4333:9)\r\n at updateChildren (https://unpkg.com/vue@2.1.6/dist/vue.js:4252:9)\r\n at patchVnode (https://unpkg.com/vue@2.1.6/dist/vue.js:4328:29)\r\n at Vue$3.patch [as __patch__] (https://unpkg.com/vue@2.1.6/dist/vue.js:4451:9)\r\n at Vue$3.Vue._update (https://unpkg.com/vue@2.1.6/dist/vue.js:2224:19)\r\n at Vue$3.<anonymous> (https://unpkg.com/vue@2.1.6/dist/vue.js:2191:10)\r\n at Watcher.get (https://unpkg.com/vue@2.1.6/dist/vue.js:1656:27)\r\n at Watcher.run (https://unpkg.com/vue@2.1.6/dist/vue.js:1725:22)\r\n```\r\n\r\nand all JS execution stops (this is proven by the fact the time does not update with repeated clicks).\r\n\r\n### Notes\r\n\r\nStrangely, the error doesn't happen if you drop the style attributes from the two divs.\r\n\r\n### Salutation\r\n\r\nThanks! Best regards,\r\n\r\nEric\r\n\r\n",
"comments": [
{
"body": "I found a workaround in the meantime. Wrap each of the two `div`s in a dummy `div` with no attributes, i.e. substitute the relevant lines with this:\r\n\r\n```html\r\n<div><div style=\"background: blue;\" v-if=\"!message\">Something</div></div>\r\n<div><div style=\"background: red;\" v-if=\"message\" v-text=\"message\"></div></div>\r\n```",
"created_at": "2016-12-21T12:46:42Z"
},
{
"body": "Thanks for reporting this. It seems that Vue tries to re-use the div element instead of removing one and adding the other (Re-using elements is generally preferred for performance reasons), but messes up in the process.\r\n\r\nSeems to be a bug indeed.\r\n\r\nA better workaround would be to explicitly key the elements with a key (unique in the component's scope) to force Vue to actually replace the divs:\r\n\r\nhttp://jsfiddle.net/Linusborg/od3m0ta9/2/",
"created_at": "2016-12-21T12:57:29Z"
},
{
"body": "Cool thanks for the better workaround",
"created_at": "2016-12-21T12:59:27Z"
},
{
"body": "Thanks, I am looking into it.",
"created_at": "2016-12-22T02:13:17Z"
}
],
"number": 4535,
"title": "Exception thrown by Vue code during update with template involving v-if and css styles"
} | {
"body": "fix #4535 \r\n\r\nrelative commit https://github.com/vuejs/vue/commit/d0afcd3cf9ad572621676ef02005d226cb4ac7c4#diff-4c8bbf2657619e18d911574dbc6b32e9",
"number": 4548,
"review_comments": [],
"title": "Node maybe be removed by v-html/v-text (fix #4535)"
} | {
"commits": [
{
"message": "Node maybe be removed v-html/v-text"
}
],
"files": [
{
"diff": "@@ -69,16 +69,16 @@ export function createPatchFunction (backend) {\n function createRmCb (childElm, listeners) {\n function remove () {\n if (--remove.listeners === 0) {\n- removeElement(childElm)\n+ removeNode(childElm)\n }\n }\n remove.listeners = listeners\n return remove\n }\n \n- function removeElement (el) {\n+ function removeNode (el) {\n const parent = nodeOps.parentNode(el)\n- // element may have already been removed due to v-html\n+ // element may have already been removed due to v-html / v-text\n if (parent) {\n nodeOps.removeChild(parent, el)\n }\n@@ -298,7 +298,7 @@ export function createPatchFunction (backend) {\n removeAndInvokeRemoveHook(ch)\n invokeDestroyHook(ch)\n } else { // Text node\n- nodeOps.removeChild(parentElm, ch.elm)\n+ removeNode(ch.elm)\n }\n }\n }\n@@ -328,7 +328,7 @@ export function createPatchFunction (backend) {\n rm()\n }\n } else {\n- removeElement(vnode.elm)\n+ removeNode(vnode.elm)\n }\n }\n ",
"filename": "src/core/vdom/patch.js",
"status": "modified"
},
{
"diff": "@@ -52,6 +52,16 @@ describe('vdom domProps module', () => {\n const elm2 = patch(null, vnode2)\n expect(elm2.textContent).toBe('hi')\n expect(vnode2.children.length).toBe(0)\n+\n+ const vnode3 = new VNode('div', undefined, undefined, '123')\n+ patch(null, vnode3)\n+ const elm3 = patch(vnode3, vnode2)\n+ expect(elm3.textContent).toBe('hi')\n+\n+ const vnode4 = new VNode('div', undefined, undefined, new VNode('span'))\n+ patch(null, vnode4)\n+ const elm4 = patch(vnode4, vnode)\n+ expect(elm4.textContent).toBe('hi')\n })\n \n it('should handle mutating observed props object', done => {",
"filename": "test/unit/modules/vdom/modules/dom-props.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\r\n2.1.6\r\n\r\n### Reproduction Link\r\nhttp://sandbox.runjs.cn/show/xu7gfzz2\r\n\r\n### Steps to reproduce\r\n\r\nswitch tag `option` between value='' and value='0', then to see ` {{ selected }}`'s change.\r\n\r\n### What is Expected?\r\n\r\nthe value of 'selected' always changes with your choose.\r\n\r\n### What is actually happening?\r\n\r\nsometime works, sometime does't work.\r\n",
"comments": [
{
"body": "Could you make reproduction on services like [JS Fiddle](https://jsfiddle.net/) because it is important to see the bindings but it is difficult (if not impossible) to see it from compiled template.",
"created_at": "2016-12-19T10:10:00Z"
},
{
"body": "Now code is in [JS Fiddle](https://jsfiddle.net/7tgtgg9x/1/) .",
"created_at": "2016-12-19T12:30:14Z"
},
{
"body": "Works perfectly for me on latest Chrome & Windows as well as OS X. Whats your setup?",
"created_at": "2016-12-19T12:37:11Z"
},
{
"body": "I made reproduction in (chrome on ubuntu 16.10, chrome on windows 10, edge on windows 10).",
"created_at": "2016-12-19T12:40:51Z"
},
{
"body": "After page loaded, select `<option>on<option>`, then select `<option><option>`, now `{{ selected }}`'s value is '0', not ''.",
"created_at": "2016-12-19T12:45:33Z"
},
{
"body": "Or switch `<option>` between value='' and value='0' more than 3 times, you will see it also.",
"created_at": "2016-12-19T12:48:45Z"
},
{
"body": "@LinusBorg testing on chrome 56/OS X, I can verify that the fiddle is broken (whether or not it's Vue or the fiddle's fault, not sure). \r\n\r\n1. The select is initialized with \"on\" and the text displays \"Selected: 1\".\r\n2. Select \"off\".\r\n - Expected the selected option to be \"off\", text should display \"Selected: 0\".\r\n - Selected option was the empty choice, text correctly displays \"Selected: 0\".\r\n3. Select \"off\" again (since it's currently empty). \r\n - The \"off\" option is correctly selected, text correctly displays \"Selected: 0\".\r\n4. Select the empty choice.\r\n - The empty choice is correctly selected, text correctly displays \"Selected: \".\r\n5. Select \"off\". Even though the current choice is empty, this breaks again.\r\n - Expected the selected option to be \"off\", text should display \"Selected: 0\".\r\n - Selected option was the empty choice, text correctly displays \"Selected: 0\". \r\n6. Select \"off\" again (since it's currently empty). \r\n - The \"off\" option is correctly selected, text correctly displays \"Selected: 0\".\r\n\r\nI was able to fix the fiddle in two ways:\r\n- change the numeric values to strings.\r\n- change the 'empty' option to a number (such as -1).\r\n\r\nEither vue is getting confused by having two falsey values ('', 0), or vue is getting confused by the mixed types. ",
"created_at": "2016-12-19T21:16:45Z"
},
{
"body": "Campares fails in looseEqual, I'll make a patch.",
"created_at": "2016-12-20T15:59:00Z"
}
],
"number": 4514,
"title": "sometime select's event does't work when option's vlaue in ('',0)"
} | {
"body": "fix #4514 ",
"number": 4528,
"review_comments": [
{
"body": "LGTM.\r\n(It may be better to check more strictly ... 😉 )",
"created_at": "2016-12-21T02:29:11Z"
},
{
"body": "It's loose equal. Which I think just add the 0 check is enough for primitive type cases. So we can skip unnecessary methods invoke here and keep it simple.\r\n```\r\nif(a === 0) {\r\n a = '0'\r\n}\r\nif(b === 0) {\r\n b = '0'\r\n}\r\nreturn a == b || (\r\n isObject(a) && isObject(b)\r\n ? JSON.stringify(a) === JSON.stringify(b)\r\n : false\r\n )\r\n```",
"created_at": "2016-12-21T04:35:45Z"
},
{
"body": "We need strict equality for primitive type, e.g., '0' is equal to false. I'll update the test case like bellow\r\n```js\r\nnew Vue({\r\n data: {\r\n val: false,\r\n test: 0\r\n },\r\n template:\r\n '<div>' +\r\n '<input type=\"radio\" value=\"\" v-model=\"test\">' +\r\n '<input type=\"radio\" value=\"0\" v-model=\"test\">' +\r\n '<input type=\"radio\" :value=\"val\" v-model=\"test\">' +\r\n '</div>'\r\n}).$mount('#app')\r\n```",
"created_at": "2016-12-21T05:32:06Z"
},
{
"body": "done via #4542 ",
"created_at": "2016-12-22T02:05:21Z"
}
],
"title": "Update loose equal function, check toString value for primitive type (fix #4514)"
} | {
"commits": [
{
"message": "update loose equal, check toString value for primitive type"
}
],
"files": [
{
"diff": "@@ -208,13 +208,15 @@ export function genStaticKeys (modules: Array<ModuleOptions>): string {\n * if they are plain objects, do they have the same shape?\n */\n export function looseEqual (a: mixed, b: mixed): boolean {\n- /* eslint-disable eqeqeq */\n- return a == b || (\n- isObject(a) && isObject(b)\n- ? JSON.stringify(a) === JSON.stringify(b)\n- : false\n- )\n- /* eslint-enable eqeqeq */\n+ const isObjectA = isObject(a)\n+ const isObjectB = isObject(b)\n+ if (isObjectA && isObjectB) {\n+ return JSON.stringify(a) === JSON.stringify(b)\n+ } else if (!isObjectA && !isObjectB) {\n+ return String(a) === String(b)\n+ } else {\n+ return false\n+ }\n }\n \n export function looseIndexOf (arr: Array<mixed>, val: mixed): number {",
"filename": "src/shared/util.js",
"status": "modified"
},
{
"diff": "@@ -159,6 +159,40 @@ describe('Directive v-model checkbox', () => {\n expect(vm.check).toEqual(false)\n })\n \n+ it('should respect different primitive type value', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ test: [0]\n+ },\n+ template:\n+ '<div>' +\n+ '<input type=\"checkbox\" value=\"\" v-model=\"test\">' +\n+ '<input type=\"checkbox\" value=\"0\" v-model=\"test\">' +\n+ '<input type=\"checkbox\" value=\"1\" v-model=\"test\">' +\n+ '</div>'\n+ }).$mount()\n+ var checkboxInput = vm.$el.children\n+ expect(checkboxInput[0].checked).toBe(false)\n+ expect(checkboxInput[1].checked).toBe(true)\n+ expect(checkboxInput[2].checked).toBe(false)\n+ vm.test = [1]\n+ waitForUpdate(() => {\n+ expect(checkboxInput[0].checked).toBe(false)\n+ expect(checkboxInput[1].checked).toBe(false)\n+ expect(checkboxInput[2].checked).toBe(true)\n+ vm.test = ['']\n+ }).then(() => {\n+ expect(checkboxInput[0].checked).toBe(true)\n+ expect(checkboxInput[1].checked).toBe(false)\n+ expect(checkboxInput[2].checked).toBe(false)\n+ vm.test = ['', 0, 1]\n+ }).then(() => {\n+ expect(checkboxInput[0].checked).toBe(true)\n+ expect(checkboxInput[1].checked).toBe(true)\n+ expect(checkboxInput[2].checked).toBe(true)\n+ }).then(done)\n+ })\n+\n it('warn inline checked', () => {\n const vm = new Vue({\n template: `<input type=\"checkbox\" v-model=\"test\" checked>`,",
"filename": "test/unit/features/directives/model-checkbox.spec.js",
"status": "modified"
},
{
"diff": "@@ -146,6 +146,35 @@ describe('Directive v-model radio', () => {\n expect(vm.test).toBe(2)\n })\n \n+ it('should respect different primitive type value', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ test: 1\n+ },\n+ template:\n+ '<div>' +\n+ '<input type=\"radio\" value=\"\" v-model=\"test\" name=\"test\">' +\n+ '<input type=\"radio\" value=\"0\" v-model=\"test\" name=\"test\">' +\n+ '<input type=\"radio\" value=\"1\" v-model=\"test\" name=\"test\">' +\n+ '</div>'\n+ }).$mount()\n+ var radioboxInput = vm.$el.children\n+ expect(radioboxInput[0].checked).toBe(false)\n+ expect(radioboxInput[1].checked).toBe(false)\n+ expect(radioboxInput[2].checked).toBe(true)\n+ vm.test = 0\n+ waitForUpdate(() => {\n+ expect(radioboxInput[0].checked).toBe(false)\n+ expect(radioboxInput[1].checked).toBe(true)\n+ expect(radioboxInput[2].checked).toBe(false)\n+ vm.test = ''\n+ }).then(() => {\n+ expect(radioboxInput[0].checked).toBe(true)\n+ expect(radioboxInput[1].checked).toBe(false)\n+ expect(radioboxInput[2].checked).toBe(false)\n+ }).then(done)\n+ })\n+\n it('warn inline checked', () => {\n const vm = new Vue({\n template: `<input v-model=\"test\" type=\"radio\" value=\"1\" checked>`,",
"filename": "test/unit/features/directives/model-radio.spec.js",
"status": "modified"
},
{
"diff": "@@ -310,7 +310,7 @@ describe('Directive v-model select', () => {\n '<select v-model.number=\"test\">' +\n '<option value=\"1\">a</option>' +\n '<option :value=\"2\">b</option>' +\n- ' <option :value=\"3\">c</option>' +\n+ '<option :value=\"3\">c</option>' +\n '</select>'\n }).$mount()\n document.body.appendChild(vm.$el)\n@@ -319,6 +319,35 @@ describe('Directive v-model select', () => {\n expect(vm.test).toBe(1)\n })\n \n+ it('should respect different pritive type value', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ test: 0\n+ },\n+ template:\n+ '<select v-model.number=\"test\">' +\n+ '<option value=\"\">a</option>' +\n+ '<option value=\"0\">b</option>' +\n+ '<option value=\"1\">c</option>' +\n+ '</select>'\n+ }).$mount()\n+ var opts = vm.$el.options\n+ expect(opts[0].selected).toBe(false)\n+ expect(opts[1].selected).toBe(true)\n+ expect(opts[2].selected).toBe(false)\n+ vm.test = 1\n+ waitForUpdate(() => {\n+ expect(opts[0].selected).toBe(false)\n+ expect(opts[1].selected).toBe(false)\n+ expect(opts[2].selected).toBe(true)\n+ vm.test = ''\n+ }).then(() => {\n+ expect(opts[0].selected).toBe(true)\n+ expect(opts[1].selected).toBe(false)\n+ expect(opts[2].selected).toBe(false)\n+ }).then(done)\n+ })\n+\n it('should warn inline selected', () => {\n const vm = new Vue({\n data: {",
"filename": "test/unit/features/directives/model-select.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\r\n2.1.6\r\n\r\n### Reproduction Link\r\n\r\nhttp://codepen.io/dolymood/pen/gLQmwy\r\n\r\n### Steps to reproduce\r\n\r\nCode\r\n\r\n```html\r\n<div class=\"el el-if\" v-if=\"bln\"><span v-show=\"false\">hidden content</span></div>\r\n<div class=\"el el-else\" v-else><span @click=\"toggle\">visible content</span></div>\r\n```\r\n\r\n1. `bln=true`, the `span` element in `el-if` is hidden\r\n\r\n2. `bln=false`, the `span` element in `el-else` is __hidden__\r\n\r\n### What is Expected?\r\n\r\nWhen `bln=false`, the `span` element should be __visible__\r\n\r\n### What is actually happening?\r\n\r\n`patchVnode` will check the nodes is same:\r\n\r\n```js\r\nfunction sameVnode (vnode1, vnode2) {\r\n return (\r\n vnode1.key === vnode2.key &&\r\n vnode1.tag === vnode2.tag &&\r\n vnode1.isComment === vnode2.isComment &&\r\n !vnode1.data === !vnode2.data\r\n )\r\n}\r\n```\r\n\r\nBecause the old vnode `vnode1.data` is \r\n\r\n```js\r\n{\r\n directives: [{\r\n def: {bind: fn, update: fn}\r\n expression: \"false\"\r\n modifiers: {},\r\n name: \"show\",\r\n rawName: \"v-show\",\r\n value: false\r\n }]\r\n}\r\n```\r\n\r\nand the new vnode `vnode2.data` is\r\n\r\n```js\r\n{\r\n on: {click: fn}\r\n}\r\n```\r\n\r\nSo `sameVnode(span1, span2)` result is `true`, but `updateDirectives` will be call `v-show` directive's `unbind` hook function.\r\n\r\nIf the `span` elements have different `key` attributes, the result will be correct. But i think it will be better if:\r\n\r\n> When `bln=false`, the `span` element should be __visible__\r\n\r\n",
"comments": [
{
"body": "Thanks, I'm looking into it.",
"created_at": "2016-12-15T11:23:00Z"
},
{
"body": "👍 Thanks",
"created_at": "2016-12-23T03:33:34Z"
}
],
"number": 4484,
"title": "node with v-show inside v-if is reused in the adjacent v-else"
} | {
"body": "fix #4484 \r\n\r\nIf element exists in dom tree, will set its display property back.\r\n\r\nApply possible transition if value is false.\r\n",
"number": 4490,
"review_comments": [],
"title": "Add unbind to v-show (fix #4484)"
} | {
"commits": [
{
"message": "add unbind method for v-show"
},
{
"message": "apply transition enter if hidden"
},
{
"message": "Merge remote-tracking branch 'originUpstream/dev' into v-show"
}
],
"files": [
{
"diff": "@@ -44,5 +44,15 @@ export default {\n } else {\n el.style.display = value ? el.__vOriginalDisplay : 'none'\n }\n+ },\n+ unbind (el: any, { value }: VNodeDirective, vnode: VNodeWithData) {\n+ if (el.parentNode) {\n+ vnode = locateNode(vnode)\n+ const transition = vnode.data && vnode.data.transition\n+ if (!value && transition && !isIE9) {\n+ enter(vnode)\n+ }\n+ el.style.display = el.__vOriginalDisplay\n+ }\n }\n }",
"filename": "src/platforms/web/runtime/directives/show.js",
"status": "modified"
},
{
"diff": "@@ -64,4 +64,21 @@ describe('Directive v-show', () => {\n expect(vm.$el.firstChild.style.display).toBe('block')\n }).then(done)\n })\n+\n+ it('should support unbind when reused', done => {\n+ const vm = new Vue({\n+ template:\n+ '<div v-if=\"tester\"><span v-show=\"false\"></span></div>' +\n+ '<div v-else><span @click=\"tester=!tester\">show</span></div>',\n+ data: { tester: true }\n+ }).$mount()\n+ expect(vm.$el.firstChild.style.display).toBe('none')\n+ vm.tester = false\n+ waitForUpdate(() => {\n+ expect(vm.$el.firstChild.style.display).toBe('')\n+ vm.tester = true\n+ }).then(() => {\n+ expect(vm.$el.firstChild.style.display).toBe('none')\n+ }).then(done)\n+ })\n })",
"filename": "test/unit/features/directives/show.spec.js",
"status": "modified"
}
]
} |
{
"body": "Howdy!\r\n\r\nIt seems like `v-bind` is not removing attributes with falsy values when another attribute with the `.prop` modifier appears first in the element's list of attributes. More details in the comments of the fiddle.\r\n\r\n### Vue.js version\r\n2.x (Tested with 2.1.3 and 2.1.4)\r\n\r\n### Reproduction Link\r\nhttp://jsfiddle.net/JosephusPaye/df4Lnuw6/78/\r\n\r\n### Steps to reproduce\r\n1. Run the fiddle\r\n2. Inspect the rendered elements using devtools to see the problem described\r\n\r\n### What is Expected?\r\n`v-bind` should remove attributes whose values are falsy (`false`, `null`, `undefined`) regardless of the presence of other attributes and the `.prop` modifier.\r\n\r\n### What is actually happening?\r\nAttributes with falsy values are not removed when another attribute with the `.prop` modifier appears first. Instead, these attributes are rendered with the string `\"false\"`, `\"null\"` or `\"undefined\"` as their value.\r\n",
"comments": [
{
"body": "Thank you!",
"created_at": "2016-12-17T06:45:40Z"
}
],
"number": 4432,
"title": "[2.x] v-bind not removing attributes with falsy values when another attribute with `.prop` modifier appears first"
} | {
"body": "fix #4432",
"number": 4435,
"review_comments": [
{
"body": "Actually, the test case should use a null or false value and check that the id attribute is absent on the element",
"created_at": "2016-12-10T13:33:44Z"
},
{
"body": "Thanks, I updated the test case",
"created_at": "2016-12-10T14:26:30Z"
}
],
"title": "fix v-bind.prop parse (fix #4432)"
} | {
"commits": [
{
"message": "reset isProp value"
},
{
"message": "add test case"
},
{
"message": "update test case"
},
{
"message": "fix typo"
}
],
"files": [
{
"diff": "@@ -414,6 +414,7 @@ function processAttrs (el) {\n if (bindRE.test(name)) { // v-bind\n name = name.replace(bindRE, '')\n value = parseFilters(value)\n+ isProp = false\n if (modifiers) {\n if (modifiers.prop) {\n isProp = true",
"filename": "src/compiler/parser/index.js",
"status": "modified"
},
{
"diff": "@@ -121,6 +121,18 @@ describe('Directive v-bind', () => {\n expect(vm.$el.children[1].innerHTML).toBe('<span>qux</span>')\n })\n \n+ it('.prop modifier with normal attribute binding', () => {\n+ const vm = new Vue({\n+ template: '<input :some.prop=\"some\" :id=\"id\">',\n+ data: {\n+ some: 'hello',\n+ id: false\n+ }\n+ }).$mount()\n+ expect(vm.$el.some).toBe('hello')\n+ expect(vm.$el.getAttribute('id')).toBe(null)\n+ })\n+\n it('.camel modifier', () => {\n const vm = new Vue({\n template: '<svg :view-box.camel=\"viewBox\"></svg>',",
"filename": "test/unit/features/directives/bind.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\r\nv2.1.3\r\n\r\n### Reproduction Link\r\nhttp://jsfiddle.net/1y2nk1L9/5/\r\n\r\n### Steps to reproduce\r\nEnter a number with some zeros after the comma into a type=\"number\" input field, while Vue performs some page rendering in the background with (unrelated) variables of the same component.\r\n\r\n### What is Expected?\r\nEntering a number like 1.00001 works without issues.\r\n\r\n### What is actually happening?\r\nEvery time Vue triggers a DOM change all v-model input fields are \"re-rendered\" (\"0.000\" -> \"0\") which makes it impossible to enter decimal numbers that contain zeros in busy components. While this sounds like a minor issue it is a **huge problem**, since the entered number could be completely wrong. Imagine entering 1.00345, but the input is silently changed to 1345. This has already led to some serious trouble in our (financial) Vue application.",
"comments": [
{
"body": "When input gets focused and the user is inputing something, the input value property should not be updated. I'll make a patch.",
"created_at": "2016-12-06T06:22:45Z"
},
{
"body": "The same problem with trim modifier, I'll try to fix it together.",
"created_at": "2016-12-06T14:35:09Z"
},
{
"body": "Hey @patrickb1991 , sorry for the potential problems this have caused in your app. Before a new release is out, you can build Vue from the dev branch locally to see if it fixes your issue.",
"created_at": "2016-12-08T21:13:23Z"
},
{
"body": "No problem @yyx990803! Thanks for your great work and the fast fix.",
"created_at": "2016-12-08T21:19:26Z"
}
],
"number": 4392,
"title": "Input [v-model & type=number] is truncated when (unrelated) DOM update happens."
} | {
"body": "fix #4392\r\n\r\nWe should update the elm.value when in these cases:\r\n1. the elm is not active and the value is not equal to model.value\r\n2. the elm needs to be casted to number or trimed, and the casted value is not equal to model.value",
"number": 4402,
"review_comments": [
{
"body": "I guess you can use a better name, as `isToNumber` isn't the most meaningful of them IMHO.",
"created_at": "2016-12-07T02:49:25Z"
},
{
"body": "The brackets are unnecessary, aren't they?",
"created_at": "2016-12-07T02:49:59Z"
},
{
"body": "Yes. `&&` has higher priority, just to make it explicitly. I'll update it",
"created_at": "2016-12-07T02:54:54Z"
},
{
"body": "I think that this function is not problem, however, If modifier did not find, in end of function, \r\nwhen you explicitly return, we can easily understand about this function.",
"created_at": "2016-12-07T02:57:48Z"
},
{
"body": "Added an explictly `return undefined` statement",
"created_at": "2016-12-07T03:15:04Z"
},
{
"body": "For logical operator && ||, updated the coding style to keep consistent with other codes",
"created_at": "2016-12-07T03:16:27Z"
},
{
"body": "I think so, I'll try to find a better one",
"created_at": "2016-12-07T03:37:18Z"
},
{
"body": "the first toNumber has an extra argument",
"created_at": "2016-12-07T14:43:17Z"
},
{
"body": "Isn't better to return an empty object so at the top you can do `modifiers.number` instead of `modifiers && modifiers.number`?",
"created_at": "2016-12-07T15:00:23Z"
},
{
"body": "I'll correct it",
"created_at": "2016-12-08T00:31:14Z"
},
{
"body": "Yes, thanks",
"created_at": "2016-12-08T00:31:42Z"
}
],
"title": "Improve elm.value update (fix #4392)"
} | {
"commits": [
{
"message": "we should update the elem.value when:\n1. the elem is not active and the value is not equal to model.value\n2. the elem need to be casted to number or trimed, and the casted value is not equal to model.value"
},
{
"message": "add test case"
},
{
"message": "1. add explictly return statement\n2. for logical operator && ||, keep it consistent with other codes"
},
{
"message": "Merge remote-tracking branch 'originUpstream/dev' into model-value-patch"
},
{
"message": "remove unnessary"
},
{
"message": "refactor"
},
{
"message": "ensure getModelModifier to return an Object"
}
],
"files": [
{
"diff": "@@ -1,6 +1,6 @@\n /* @flow */\n \n-import { extend } from 'shared/util'\n+import { extend, toNumber } from 'shared/util'\n \n function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {\n if (!oldVnode.data.domProps && !vnode.data.domProps) {\n@@ -35,7 +35,10 @@ function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {\n elm._value = cur\n // avoid resetting cursor position when value is the same\n const strCur = cur == null ? '' : String(cur)\n- if (elm.value !== strCur && !elm.composing) {\n+ if (!elm.composing && (\n+ (document.activeElement !== elm && elm.value !== strCur) ||\n+ isValueChanged(vnode, strCur)\n+ )) {\n elm.value = strCur\n }\n } else {\n@@ -44,6 +47,31 @@ function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {\n }\n }\n \n+function isValueChanged (vnode: VNodeWithData, newVal: string): boolean {\n+ const value = vnode.elm.value\n+ const modifiers = getModelModifier(vnode)\n+ const needNumber = modifiers.number || vnode.elm.type === 'number'\n+ const needTrim = modifiers.trim\n+ if (needNumber) {\n+ return toNumber(value) !== toNumber(newVal)\n+ }\n+ if (needTrim) {\n+ return value.trim() !== newVal.trim()\n+ }\n+ return value !== newVal\n+}\n+\n+function getModelModifier (vnode: VNodeWithData): ASTModifiers | Object {\n+ const directives = vnode.data.directives || []\n+ for (let i = 0, directive; i < directives.length; i++) {\n+ directive = directives[i]\n+ if (directive.name === 'model') {\n+ return directive.modifiers || {}\n+ }\n+ }\n+ return {}\n+}\n+\n export default {\n create: updateDOMProps,\n update: updateDOMProps",
"filename": "src/platforms/web/runtime/modules/dom-props.js",
"status": "modified"
},
{
"diff": "@@ -64,6 +64,61 @@ describe('Directive v-model text', () => {\n expect(vm.test).toBe('what')\n })\n \n+ it('.number focus and typing', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ test: 0,\n+ update: 0\n+ },\n+ template:\n+ '<div>' +\n+ '<input ref=\"input\" v-model=\"test\" type=\"number\">{{ update }}' +\n+ '<input ref=\"blur\"/>' +\n+ '</div>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ vm.$refs.input.focus()\n+ expect(vm.test).toBe(0)\n+ vm.$refs.input.value = '1.0'\n+ triggerEvent(vm.$refs.input, 'input')\n+ expect(vm.test).toBe(1)\n+ vm.update++\n+ waitForUpdate(() => {\n+ expect(vm.$refs.input.value).toBe('1.0')\n+ vm.$refs.blur.focus()\n+ vm.update++\n+ }).then(() => {\n+ expect(vm.$refs.input.value).toBe('1')\n+ }).then(done)\n+ })\n+\n+ it('.trim focus and typing', (done) => {\n+ const vm = new Vue({\n+ data: {\n+ test: 'abc',\n+ update: 0\n+ },\n+ template:\n+ '<div>' +\n+ '<input ref=\"input\" v-model.trim=\"test\" type=\"text\">{{ update }}' +\n+ '<input ref=\"blur\"/>' +\n+ '</div>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ vm.$refs.input.focus()\n+ vm.$refs.input.value = ' abc '\n+ triggerEvent(vm.$refs.input, 'input')\n+ expect(vm.test).toBe('abc')\n+ vm.update++\n+ waitForUpdate(() => {\n+ expect(vm.$refs.input.value).toBe(' abc ')\n+ vm.$refs.blur.focus()\n+ vm.update++\n+ }).then(() => {\n+ expect(vm.$refs.input.value).toBe('abc')\n+ }).then(done)\n+ })\n+\n it('multiple inputs', (done) => {\n const spy = jasmine.createSpy()\n const vm = new Vue({",
"filename": "test/unit/features/directives/model-text.spec.js",
"status": "modified"
}
]
} |
{
"body": "I ran into this issue yesterday. I'm working on a page that includes images with CSS shape-outside for flowing the text around them based on a shape image. To do this, I include the URL to the shape image in an inline style attribute.\r\n\r\nDuring my work this stopped working after I upgraded Vue to the latest. The earliest reproducible version is 2.0.6. It's working on 2.0.5. When the HTML is compiled, the url from the style attribute string gets broken, and instead of the full URL you just end up with \"http\".\r\n\r\n### Vue.js version\r\n2.0.6+\r\n\r\n### Reproduction Link\r\nhttps://jsfiddle.net/mottokrosh/5Lppm3ce/7/\r\n\r\n### Steps to reproduce\r\nGo to the above JSBin. Ignore the CORS error about failing to load the shape image. \r\n\r\n### What is Expected?\r\nInspect the HTML of the `<figure>` in the dev console. The full `style=\"shape-outside: url(https://grove.sidhewoods.com/assets/verdant-reaches-players-guide/art/NPC_Sheriff_Lucas_Quint-shape.png); shape-margin: 1rem;\"` should be seen, as in the specified HTML. \r\n\r\n### What is actually happening?\r\nInstead, it's become `style=\"shape-outside: url(\"https\"); shape-margin: 1rem;\"`.",
"comments": [
{
"body": "Thanks @Mottokrosh, I'm looking into it. Current now it just parses the background-image, I'll make a PR to fix it.",
"created_at": "2016-11-30T15:57:15Z"
}
],
"number": 4346,
"title": "Template compilation error in style attribute with url"
} | {
"body": "fix #4346 \r\n\r\nRemove the unproper hasBackground check and add more test cases.",
"number": 4349,
"review_comments": [],
"title": "fix static style parse error (fix #4346)"
} | {
"commits": [
{
"message": "fix static style parse error."
}
],
"files": [
{
"diff": "@@ -4,10 +4,8 @@ import { cached, extend, toObject } from 'shared/util'\n \n export const parseStyleText = cached(function (cssText) {\n const res = {}\n- const hasBackground = cssText.indexOf('background') >= 0\n- // maybe with background-image: url(http://xxx) or base64 img\n- const listDelimiter = hasBackground ? /;(?![^(]*\\))/g : ';'\n- const propertyDelimiter = hasBackground ? /:(.+)/ : ':'\n+ const listDelimiter = /;(?![^(]*\\))/g\n+ const propertyDelimiter = /:(.+)/\n cssText.split(listDelimiter).forEach(function (item) {\n if (item) {\n var tmp = item.split(propertyDelimiter)",
"filename": "src/platforms/web/util/style.js",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,41 @@\n+import { parseStyleText } from 'web/util/style'\n+const base64ImgUrl = 'url(\"data:image/webp;base64,UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==\")'\n+const logoUrl = 'url(https://vuejs.org/images/logo.png)'\n+\n+it('should parse normal static style', () => {\n+ const staticStyle = `font-size: 12px;background: ${logoUrl};color:red`\n+ const res = parseStyleText(staticStyle)\n+ expect(res.background).toBe(logoUrl)\n+ expect(res.color).toBe('red')\n+ expect(res['font-size']).toBe('12px')\n+})\n+\n+it('should parse base64 background', () => {\n+ const staticStyle = `background: ${base64ImgUrl}`\n+ const res = parseStyleText(staticStyle)\n+ expect(res.background).toBe(base64ImgUrl)\n+})\n+\n+it('should parse multiple background images ', () => {\n+ let staticStyle = `background: ${logoUrl}, ${logoUrl};`\n+ let res = parseStyleText(staticStyle)\n+ expect(res.background).toBe(`${logoUrl}, ${logoUrl}`)\n+\n+ staticStyle = `background: ${base64ImgUrl}, ${base64ImgUrl}`\n+ res = parseStyleText(staticStyle)\n+ expect(res.background).toBe(`${base64ImgUrl}, ${base64ImgUrl}`)\n+})\n+\n+it('should parse other images ', () => {\n+ let staticStyle = `shape-outside: ${logoUrl}`\n+ let res = parseStyleText(staticStyle)\n+ expect(res['shape-outside']).toBe(logoUrl)\n+\n+ staticStyle = `list-style-image: ${logoUrl}`\n+ res = parseStyleText(staticStyle)\n+ expect(res['list-style-image']).toBe(logoUrl)\n+\n+ staticStyle = `border-image: ${logoUrl} 30 30 repeat`\n+ res = parseStyleText(staticStyle)\n+ expect(res['border-image']).toBe(`${logoUrl} 30 30 repeat`)\n+})",
"filename": "test/unit/features/directives/static-style-parser.spec.js",
"status": "added"
}
]
} |
{
"body": "### Reproduction Link\r\nhttp://codepen.io/localvoid/pen/WojeKN\r\n",
"comments": [
{
"body": "Thanks, this is vue's repository. If you have question on react, please go to https://github.com/facebook/react/",
"created_at": "2016-11-23T04:50:23Z"
},
{
"body": "@HerringtonDarkholme this is vue2 issue, if you don't care about correct behavior in vue, you may ignore this issue.",
"created_at": "2016-11-23T06:57:05Z"
},
{
"body": "cc @yyx990803 check this, almost all virtual dom implementations have this issue.",
"created_at": "2016-11-23T06:59:09Z"
},
{
"body": "Sorry, I misread the link. Reopened. It would've clearer to just paste a direct link to vue's reproduction rather than adding a React entry point.\r\n\r\nhttps://jsfiddle.net/localvoid/d3bohccg/",
"created_at": "2016-11-23T07:02:34Z"
}
],
"number": 4284,
"title": "Component root node changing is broken"
} | {
"body": "Fix #4284 , to recap the bug, in one sentence: \r\n\r\n`vm.$el` should always be the same as `vm.$vnode.elm`\r\n\r\nMore detail:\r\n\r\n1. If a component changes its root element during rendering, all ancestors' placeholder root element's element should be all updated.\r\n\r\n2. If one component is the root element of another component, for example `wrapper` in the test case, and wrapper's parent is updated (which triggers wrapper's `updateFromParent`), `wrapper`'s $vnode is not the same as `comp`'s $vnode.parent. While in the initial rendering, these two vnodes are the same one.\r\n\r\nTo simplify these two statements, we have to keep one invariant: `vm.$el` should always be the same as `vm.$vnode.elm`. Otherwise vdom patching will mistakenly insert new dom node.\r\n\r\nIf we correctly sync vnode's element when child tree's root changes its tag (1), and update vm's vnode when parent is updated(2), we can ensure $el is up to date.\r\n\r\nI hope I made myself understood. it is quite perplexing.\r\n\r\nI don't think this is the only way to fix the edge case. If @yyx990803 and other members have better alternatives, I'm happy to see it.",
"number": 4299,
"review_comments": [],
"title": "Ensure Vue instance's vnode and element is up to date"
} | {
"commits": [
{
"message": "fix #4284, recursively update vnode element"
},
{
"message": "fix #4284, ensure vm's vnode is up to date"
},
{
"message": "add test for edge case"
}
],
"files": [
{
"diff": "@@ -116,6 +116,10 @@ export function lifecycleMixin (Vue: Class<Component>) {\n const vm: Component = this\n const hasChildren = !!(vm.$options._renderChildren || renderChildren)\n vm.$options._parentVnode = parentVnode\n+ vm.$vnode = parentVnode // update vm's placeholder node without re-render\n+ if (vm._vnode) { // update child tree's parent\n+ vm._vnode.parent = parentVnode\n+ }\n vm.$options._renderChildren = renderChildren\n // update props\n if (propsData && vm.$options.props) {",
"filename": "src/core/instance/lifecycle.js",
"status": "modified"
},
{
"diff": "@@ -505,9 +505,13 @@ export function createPatchFunction (backend) {\n createElm(vnode, insertedVnodeQueue)\n \n // component root element replaced.\n- // update parent placeholder node element.\n+ // update parent placeholder node element, recursively\n if (vnode.parent) {\n- vnode.parent.elm = vnode.elm\n+ let ancestor = vnode.parent\n+ while (ancestor) {\n+ ancestor.elm = vnode.elm\n+ ancestor = ancestor.parent\n+ }\n if (isPatchable(vnode)) {\n for (let i = 0; i < cbs.create.length; ++i) {\n cbs.create[i](emptyNode, vnode.parent)",
"filename": "src/core/vdom/patch.js",
"status": "modified"
},
{
"diff": "@@ -57,4 +57,61 @@ describe('vdom patch: edge cases', () => {\n expect(vm.$el.querySelector('.d').textContent).toBe('2')\n }).then(done)\n })\n+\n+ it('should synchronize vm\\' vnode', done => {\n+ const comp = {\n+ data: () => ({ swap: true }),\n+ render (h) {\n+ return this.swap\n+ ? h('a', 'atag')\n+ : h('span', 'span')\n+ }\n+ }\n+\n+ const wrapper = {\n+ render: h => h('comp'),\n+ components: { comp }\n+ }\n+\n+ const vm = new Vue({\n+ render (h) {\n+ const children = [\n+ h('wrapper'),\n+ h('div', 'row')\n+ ]\n+ if (this.swap) {\n+ children.reverse()\n+ }\n+ return h('div', children)\n+ },\n+ data: () => ({ swap: false }),\n+ components: { wrapper }\n+ }).$mount()\n+\n+ expect(vm.$el.innerHTML).toBe('<a>atag</a><div>row</div>')\n+ const wrapperVm = vm.$children[0]\n+ const compVm = wrapperVm.$children[0]\n+ vm.swap = true\n+ waitForUpdate(() => {\n+ expect(compVm.$vnode.parent).toBe(wrapperVm.$vnode)\n+ expect(vm.$el.innerHTML).toBe('<div>row</div><a>atag</a>')\n+ vm.swap = false\n+ })\n+ .then(() => {\n+ expect(compVm.$vnode.parent).toBe(wrapperVm.$vnode)\n+ expect(vm.$el.innerHTML).toBe('<a>atag</a><div>row</div>')\n+ compVm.swap = false\n+ })\n+ .then(() => {\n+ expect(vm.$el.innerHTML).toBe('<span>span</span><div>row</div>')\n+ expect(compVm.$vnode.parent).toBe(wrapperVm.$vnode)\n+ vm.swap = true\n+ })\n+ .then(() => {\n+ expect(vm.$el.innerHTML).toBe('<div>row</div><span>span</span>')\n+ expect(compVm.$vnode.parent).toBe(wrapperVm.$vnode)\n+ vm.swap = true\n+ })\n+ .then(done)\n+ })\n })",
"filename": "test/unit/modules/vdom/patch/edge-cases.spec.js",
"status": "modified"
}
]
} |
{
"body": "When using vue-class-component library with vue-router in 2.0.8, dom elements are not being id'd and therefore the 'scoped' css is broken.\r\n\r\nTo replicate, simply install VueRouter in a test project that exports using the js like:\r\n\r\n\r\n```\r\n// hello.vue\r\n...\r\n<script>\r\nimport Component from 'vue-class-component'\r\n\r\n@Component export default class Login {\r\n name = 'hello'\r\n msg = 'Welcome to Your Vue.js App'\r\n}\r\n</script>\r\n...\r\n```\r\n\r\n```\r\n// app.js\r\nimport Vue from 'vue'\r\nimport App from './App'\r\nimport VueRouter from 'vue-router'\r\n\r\nVue.use(VueRouter)\r\n\r\n/* eslint-disable no-new */\r\nnew Vue({\r\n el: '#app',\r\n template: '<App/>',\r\n components: { App }\r\n})\r\n```\r\n\"vue\": \"^2.0.8\",\r\n\"vue-class-component\": \"^4.3.1\",\r\n \"vue-router\": \"^2.0.3\"\r\n\r\nI also find it impossible to roll back vue (i want to roll back to 2.0.7) because the vue-loader library which is a dependancy of vue has a subdependancy of vue-template-compiler@^2.0.5 which will then just install the latest, and throw a version mismatch error. It would be nice to be able to lock to an older version ",
"comments": [
{
"body": "If this only happens with vue-class-component, please open an issue in that repo.\r\n\r\nAlso, please follow the [guidelines](https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md) on how to report an issue. In particular, provide an example on www.jsfiddle.net (or a similar service) that reproduces the problem. If nessessary, create a repository for us to clone, with a minimal reproduction. repositories of actual projects will generally not be accepted .\r\n\r\n\r\nThank you.",
"created_at": "2016-11-21T12:47:51Z"
},
{
"body": "the issue is with view-template-compiler tho, so i moved the bug here, it is also 'caused' by vue-router being present too. Obv. i can move it if you want tho",
"created_at": "2016-11-21T12:53:19Z"
},
{
"body": "Here is an example repo\r\n\r\nhttps://github.com/tonypee/vue-issue-4266",
"created_at": "2016-11-21T13:59:26Z"
},
{
"body": "Haven't looked into the details but I suspect it may have to do with `vue-class-component` not handling `_scopeId` properly. I don't see anything between 2.0.7 and 2.0.8 that could cause this problem. /cc @ktsn ",
"created_at": "2016-11-21T17:26:19Z"
},
{
"body": "I'll look into it.",
"created_at": "2016-11-22T00:36:08Z"
}
],
"number": 4266,
"title": "2.0.8 vue-template-compiler breaks scoped css "
} | {
"body": "Fix #4266\r\n\r\nThis PR fixes the problem that `_scopeId` will be dropped after applying global mixin.\r\nreproduction: https://jsfiddle.net/tutjybnv/\r\n\r\nLooks like same problem as vuejs/vue-loader#433",
"number": 4274,
"review_comments": [],
"title": "Avoid to drop scope id by applying global mixin"
} | {
"commits": [
{
"message": "global mixin should not drop scope id (fix #4266)"
}
],
"files": [
{
"diff": "@@ -72,6 +72,7 @@ export function resolveConstructorOptions (Ctor: Class<Component>) {\n Ctor.superOptions = superOptions\n extendOptions.render = options.render\n extendOptions.staticRenderFns = options.staticRenderFns\n+ extendOptions._scopeId = options._scopeId\n options = Ctor.options = mergeOptions(superOptions, extendOptions)\n if (options.name) {\n options.components[options.name] = Ctor",
"filename": "src/core/instance/init.js",
"status": "modified"
},
{
"diff": "@@ -70,4 +70,18 @@ describe('Global API: mixin', () => {\n \n expect(vm.$el.textContent).toBe('hello')\n })\n+\n+ // #4266\n+ it('should not drop scopedId', () => {\n+ const Test = Vue.extend({})\n+ Test.options._scopeId = 'foo'\n+\n+ Vue.mixin({})\n+\n+ const vm = new Test({\n+ template: '<div><p>hi<p></div>'\n+ }).$mount()\n+\n+ expect(vm.$el.children[0].hasAttribute('foo')).toBe(true)\n+ })\n })",
"filename": "test/unit/features/global-api/mixin.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\r\n2.0.8\r\n\r\n### Reproduction Link\r\nhttp://jsfiddle.net/3hmp0e16/1/\r\n\r\n### Steps to reproduce\r\nRun the JSFiddle above and you will see that content is not visible.\r\n\r\n### What is Expected?\r\nI would expect the app to run regardless of the Unicode characters, without errors.\r\n\r\n### What is actually happening?\r\n`Uncaught TypeError: Cannot set property 'isStatic' of undefined`\r\nfor Vue 2.0.8 when \\u2028 character is in DOM element attribute on creating new Vue instance.\r\n`<img src=\"http://placehold.it/350x150\" alt=\"hello\\u2028 word\" />`\r\n\r\n```\r\n[Vue warn]: failed to compile template:\r\n\r\n<div id=\"app\">\r\n <img src=\"http://placehold.it/350x150\" alt=\"hello
word\">\r\n</div>\r\n \r\n(found in root instance)warn @ vue.js:2658compileToFunctions @ vue.js:7826Vue$3.$mount @ vue.js:7895initRender @ vue.js:2234Vue._init @ vue.js:2597Vue$3 @ vue.js:2641window.onload @ (index):49\r\nvue.js:2658 [Vue warn]: Error when rendering root instance: warn @ vue.js:2658Vue._render @ vue.js:2269(anonymous function) @ vue.js:1709get @ vue.js:740Watcher @ vue.js:732Vue._mount @ vue.js:1708Vue$3.$mount @ vue.js:5746Vue$3.$mount @ vue.js:7906initRender @ vue.js:2234Vue._init @ vue.js:2597Vue$3 @ vue.js:2641window.onload @ (index):49\r\nvue.js:2278 TypeError: Cannot set property 'isStatic' of undefined(…)\r\n```\r\n\r\nRelated to #3895",
"comments": [
{
"body": "Thanks! It's the same as #3895 but in attrs. I'll fix it",
"created_at": "2016-11-21T14:13:28Z"
}
],
"number": 4268,
"title": "Unicode \\u2028 character crashing vue"
} | {
"body": "<!--\r\nPlease make sure to read the Pull Request Guidelines:\r\nhttps://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines\r\n-->\r\n\r\nFix #4268\r\nRelated to #3903\r\nI just applied the same strategy as @defcc to make it work for the moment but there's a difference here:\r\n\r\nUsing the U+2028 character in a title actually makes the title to wrap: http://jsfiddle.net/posva/rjzbxgea/\r\nSo instead of eliminating it, I'm replacing it with another newline",
"number": 4270,
"review_comments": [],
"title": "Replace special terminators chars in attrs"
} | {
"commits": [
{
"message": "Replace special terminators chars in attrs\n\nFix #4268\nRelated to #3903"
}
],
"files": [
{
"diff": "@@ -363,7 +363,8 @@ function processAttrs (el) {\n let i, l, name, rawName, value, arg, modifiers, isProp\n for (i = 0, l = list.length; i < l; i++) {\n name = rawName = list[i].name\n- value = list[i].value\n+ // #4268 Use an ecmascript valid lf character\n+ value = list[i].value.replace(specialNewlineRE, '\\n')\n if (dirRE.test(name)) {\n // mark element as dynamic\n el.hasBindings = true",
"filename": "src/compiler/parser/index.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\r\n2.0.6+\r\n\r\n### Reproduction Link\r\nhttps://jsfiddle.net/gw8g8cos/\r\n\r\n\r\n\r\n\r\n### Steps to reproduce\r\n```\r\n$ vue init webpack-simple .\r\n$ npm install vue@2.0.7 vue-template-compiler@2.0.7\r\n```\r\n\r\n```vue\r\n<template>\r\n<div>\r\n <section style=\"text-align: center\" v-if=\"loading\">\r\n Should be centered.\r\n </section>\r\n <section style=\"margin-top: 6rem;\" v-if=\"!loading\">\r\n Should not be centered.\r\n </section>\r\n</div>\r\n</template>\r\n\r\n<script>\r\nexport default {\r\n name: 'app',\r\n data () {\r\n return {\r\n loading: true\r\n }\r\n },\r\n mounted: function() {\r\n setTimeout(() => {\r\n this.loading = false;\r\n }, 2000);\r\n }\r\n}\r\n</script>\r\n```\r\n\r\n### What is Expected?\r\nPatched elements should not keep inline styles from old vnodes.\r\n\r\n### What is actually happening?\r\nDuring the update operation, patched elements will retain styles from vnodes that will no longer exist in the DOM.\r\n\r\nTemporarily solution for end-users: changing inline styles to classes, choosing different tag names or adding a `key` directive will fix the issue. Thanks to @LinusBorg for the latter.\r\n\r\nIt looks like this PR has introduced this regression https://github.com/vuejs/vue/pull/4138. I've opened a pull request with a failing test that confirms this issue.",
"comments": [
{
"body": "This might be related to https://github.com/vuejs/vue/issues/4205. But I'm not sure. Can you try adding a key property to section?\n\nOnline repro: \nhttps://jsfiddle.net/gw8g8cos/\n",
"created_at": "2016-11-17T09:26:47Z"
},
{
"body": "@HerringtonDarkholme it's definitely related. Still a little annoying to have to deal with this... Adding the `key` tag worked... Would be nice to mention something in the docs about diffing. \n",
"created_at": "2016-11-17T09:34:49Z"
},
{
"body": "@Igdexter\n\n> Would be nice to mention something in the docs about diffing.\n\nWe're on it vuejs/vuejs.org#587\n",
"created_at": "2016-11-17T09:42:05Z"
},
{
"body": "@LinusBorg cool, thanks for the quick response. had quite a shock in my staging environment today with 2.0.7\n",
"created_at": "2016-11-17T09:47:21Z"
},
{
"body": "> had quite a shock in my staging environment today with 2.0.7\n\nThis is not an intended breaking change, mind you. It's generally expected behaviour in many situations, but as already mentioned, documentation about this is still lacking. \n\nI assume that this worked \"accidentally\" before, and recent fixes of bugs which, amongst other things, related to handling of style and class bindings, might have changed that. \n",
"created_at": "2016-11-17T09:52:40Z"
},
{
"body": "@LinusBorg I wonder whether this is a correct behavior.\n\nThe example above can be diffed solely by v-dom. The style attribute should be considered as a v-dom construct.\n\nBy comparison, consider this example. https://jsfiddle.net/gw8g8cos/4/\nThe inner text and class has been updated, the class is not merged, but style is merged.\n\nNote, this issue is different from #4205 , since lifecycle is not managed by virtual dom.\nAnd it is also different from https://github.com/vuejs/vue/issues/4216, since inline-template, speaking in implementation, has a different slot than `render` in vnode representation.\n\ncc @defcc \n",
"created_at": "2016-11-17T09:54:03Z"
},
{
"body": "@LinusBorg I'm guessing the improvement to preserve static inline styles with dynamic inline styles as per #4138 is what made this issue apparent now. I'm just wondering if this is the correct behavior. Here it's comparing the old node with the new node and then applying the necessary style changes, but the code seems to be merging them. Reusing the same node is fine; I just think it should keep only the styles for the active node that needs to be represented on the DOM.\n\nEdited the OP in light of the new info\n",
"created_at": "2016-11-17T09:55:09Z"
},
{
"body": "Hm you might be right.\n",
"created_at": "2016-11-17T09:55:19Z"
},
{
"body": "Seems to be something wrong with static style and style binding merge. I am looking into it. \n",
"created_at": "2016-11-17T12:36:47Z"
},
{
"body": "[https://github.com/vuejs/vue/blob/dev/src/platforms/web/runtime/modules/style.js#L48](https://github.com/vuejs/vue/blob/dev/src/platforms/web/runtime/modules/style.js#L48)\n\n``` js\nconst style = normalizeStyleBinding(vnode.data.style) || {}\nvnode.data.style = style.__ob__ ? extend({}, style) : style\nconst newStyle = getStyle(vnode, true)\n```\n\nThe style now only holds the style binding, which will be removed in the next render. The static style and style binding should be removed both when reusing the same node.\n",
"created_at": "2016-11-17T12:51:05Z"
},
{
"body": "I'll make a PR to fix it\n",
"created_at": "2016-11-17T14:05:08Z"
}
],
"number": 4227,
"title": "Patched elements keep inline styles from old vnodes"
} | {
"body": "fix #4227 ",
"number": 4235,
"review_comments": [],
"title": "Remove old static style when applying style update (fix #4227)"
} | {
"commits": [
{
"message": "both static style and stylebinding should be removed"
},
{
"message": "Merge remote-tracking branch 'originUpstream/dev' into fix-style-update\n\n# Conflicts:\n#\ttest/unit/features/directives/style.spec.js"
},
{
"message": "update test case"
},
{
"message": "update test case"
}
],
"files": [
{
"diff": "@@ -42,7 +42,12 @@ function updateStyle (oldVnode: VNodeWithData, vnode: VNodeWithData) {\n \n let cur, name\n const el: any = vnode.elm\n- const oldStyle: any = oldVnode.data.style || {}\n+ const oldStaticStyle: any = oldVnode.data.staticStyle\n+ const oldStyleBinding: any = oldVnode.data.style || {}\n+\n+ // if static style exists, stylebinding already merged into it when doing normalizeStyleData\n+ const oldStyle = oldStaticStyle || oldStyleBinding\n+\n const style = normalizeStyleBinding(vnode.data.style) || {}\n \n vnode.data.style = style.__ob__ ? extend({}, style) : style",
"filename": "src/platforms/web/runtime/modules/style.js",
"status": "modified"
},
{
"diff": "@@ -280,19 +280,28 @@ describe('Directive v-bind:style', () => {\n \n it('should not merge for different adjacent elements', (done) => {\n const vm = new Vue({\n- template: '<div>' +\n- '<section style=\"color: blue\" v-if=\"!bool\"></section>' +\n- '<div></div>' +\n- '<section style=\"margin: 0\" v-if=\"bool\"></section>' +\n- '</div>',\n+ template:\n+ '<div>' +\n+ '<section style=\"color: blue\" :style=\"style\" v-if=\"!bool\"></section>' +\n+ '<div></div>' +\n+ '<section style=\"margin-top: 12px\" v-if=\"bool\"></section>' +\n+ '</div>',\n data: {\n- bool: false\n+ bool: false,\n+ style: {\n+ fontSize: '12px'\n+ }\n }\n }).$mount()\n+ const style = vm.$el.children[0].style\n+ expect(style.fontSize).toBe('12px')\n+ expect(style.color).toBe('blue')\n waitForUpdate(() => {\n vm.bool = true\n }).then(() => {\n- expect(vm.$el.children[1].style.color).not.toBe('blue')\n+ expect(style.color).toBe('')\n+ expect(style.fontSize).toBe('')\n+ expect(style.marginTop).toBe('12px')\n }).then(done)\n })\n })",
"filename": "test/unit/features/directives/style.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\r\n2.0.6+\r\n\r\n### Reproduction Link\r\nhttps://jsfiddle.net/gw8g8cos/\r\n\r\n\r\n\r\n\r\n### Steps to reproduce\r\n```\r\n$ vue init webpack-simple .\r\n$ npm install vue@2.0.7 vue-template-compiler@2.0.7\r\n```\r\n\r\n```vue\r\n<template>\r\n<div>\r\n <section style=\"text-align: center\" v-if=\"loading\">\r\n Should be centered.\r\n </section>\r\n <section style=\"margin-top: 6rem;\" v-if=\"!loading\">\r\n Should not be centered.\r\n </section>\r\n</div>\r\n</template>\r\n\r\n<script>\r\nexport default {\r\n name: 'app',\r\n data () {\r\n return {\r\n loading: true\r\n }\r\n },\r\n mounted: function() {\r\n setTimeout(() => {\r\n this.loading = false;\r\n }, 2000);\r\n }\r\n}\r\n</script>\r\n```\r\n\r\n### What is Expected?\r\nPatched elements should not keep inline styles from old vnodes.\r\n\r\n### What is actually happening?\r\nDuring the update operation, patched elements will retain styles from vnodes that will no longer exist in the DOM.\r\n\r\nTemporarily solution for end-users: changing inline styles to classes, choosing different tag names or adding a `key` directive will fix the issue. Thanks to @LinusBorg for the latter.\r\n\r\nIt looks like this PR has introduced this regression https://github.com/vuejs/vue/pull/4138. I've opened a pull request with a failing test that confirms this issue.",
"comments": [
{
"body": "This might be related to https://github.com/vuejs/vue/issues/4205. But I'm not sure. Can you try adding a key property to section?\n\nOnline repro: \nhttps://jsfiddle.net/gw8g8cos/\n",
"created_at": "2016-11-17T09:26:47Z"
},
{
"body": "@HerringtonDarkholme it's definitely related. Still a little annoying to have to deal with this... Adding the `key` tag worked... Would be nice to mention something in the docs about diffing. \n",
"created_at": "2016-11-17T09:34:49Z"
},
{
"body": "@Igdexter\n\n> Would be nice to mention something in the docs about diffing.\n\nWe're on it vuejs/vuejs.org#587\n",
"created_at": "2016-11-17T09:42:05Z"
},
{
"body": "@LinusBorg cool, thanks for the quick response. had quite a shock in my staging environment today with 2.0.7\n",
"created_at": "2016-11-17T09:47:21Z"
},
{
"body": "> had quite a shock in my staging environment today with 2.0.7\n\nThis is not an intended breaking change, mind you. It's generally expected behaviour in many situations, but as already mentioned, documentation about this is still lacking. \n\nI assume that this worked \"accidentally\" before, and recent fixes of bugs which, amongst other things, related to handling of style and class bindings, might have changed that. \n",
"created_at": "2016-11-17T09:52:40Z"
},
{
"body": "@LinusBorg I wonder whether this is a correct behavior.\n\nThe example above can be diffed solely by v-dom. The style attribute should be considered as a v-dom construct.\n\nBy comparison, consider this example. https://jsfiddle.net/gw8g8cos/4/\nThe inner text and class has been updated, the class is not merged, but style is merged.\n\nNote, this issue is different from #4205 , since lifecycle is not managed by virtual dom.\nAnd it is also different from https://github.com/vuejs/vue/issues/4216, since inline-template, speaking in implementation, has a different slot than `render` in vnode representation.\n\ncc @defcc \n",
"created_at": "2016-11-17T09:54:03Z"
},
{
"body": "@LinusBorg I'm guessing the improvement to preserve static inline styles with dynamic inline styles as per #4138 is what made this issue apparent now. I'm just wondering if this is the correct behavior. Here it's comparing the old node with the new node and then applying the necessary style changes, but the code seems to be merging them. Reusing the same node is fine; I just think it should keep only the styles for the active node that needs to be represented on the DOM.\n\nEdited the OP in light of the new info\n",
"created_at": "2016-11-17T09:55:09Z"
},
{
"body": "Hm you might be right.\n",
"created_at": "2016-11-17T09:55:19Z"
},
{
"body": "Seems to be something wrong with static style and style binding merge. I am looking into it. \n",
"created_at": "2016-11-17T12:36:47Z"
},
{
"body": "[https://github.com/vuejs/vue/blob/dev/src/platforms/web/runtime/modules/style.js#L48](https://github.com/vuejs/vue/blob/dev/src/platforms/web/runtime/modules/style.js#L48)\n\n``` js\nconst style = normalizeStyleBinding(vnode.data.style) || {}\nvnode.data.style = style.__ob__ ? extend({}, style) : style\nconst newStyle = getStyle(vnode, true)\n```\n\nThe style now only holds the style binding, which will be removed in the next render. The static style and style binding should be removed both when reusing the same node.\n",
"created_at": "2016-11-17T12:51:05Z"
},
{
"body": "I'll make a PR to fix it\n",
"created_at": "2016-11-17T14:05:08Z"
}
],
"number": 4227,
"title": "Patched elements keep inline styles from old vnodes"
} | {
"body": "test to confirm issue #4227 ",
"number": 4232,
"review_comments": [],
"title": "destroyed elements pass their styles onto others that are similar"
} | {
"commits": [
{
"message": "destroyed elements pass their styles onto others that are similar"
}
],
"files": [
{
"diff": "@@ -277,4 +277,22 @@ describe('Directive v-bind:style', () => {\n expect(style.marginLeft).toBe('40px')\n }).then(done)\n })\n+\n+ it('should not merge for different adjacent elements', (done) => {\n+ const vm = new Vue({\n+ template: '<div>' +\n+ '<section style=\"color: blue\" v-if=\"!bool\"></section>' +\n+ '<div></div>' +\n+ '<section style=\"margin: 0\" v-if=\"bool\"></section>' +\n+ '</div>',\n+ data: {\n+ bool: false\n+ }\n+ }).$mount()\n+ waitForUpdate(() => {\n+ vm.bool = true\n+ }).then(() => {\n+ expect(vm.$el.children[1].style.color).not.toBe('blue')\n+ }).then(done)\n+ })\n })",
"filename": "test/unit/features/directives/style.spec.js",
"status": "modified"
}
]
} |
{
"body": "<!-- BUG REPORT TEMPLATE -->\r\n### Vue.js version\r\n2.0.2\r\n\r\n### Steps to reproduce\r\n\r\n1. Create component\r\n```\r\nVue.component('testcomponent', {\r\n render: h => h('div', 'contain')\r\n})\r\n```\r\n2. Use the components within the parent component template with className\r\n```\r\n <div id=\"appcomponent\">\r\n <testcomponent class=\"testclass\" />\r\n </div>\r\n```\r\n\r\n### What is Expected?\r\nExpected to render on the server side\r\n```\r\n <div id=\"appcomponent\">\r\n <div class=\"testclass\">contain</div>\r\n </div>\r\n```\r\nSimilarly, as the client-side\r\n\r\n### What is actually happening?\r\nThe server side is not renders classes in dynamically generated components\r\n```\r\n <div id=\"appcomponent\">\r\n <div>contain</div>\r\n </div>\r\n```\r\nAt the same time, the client side, renders everything with classes\r\n\r\n```\r\n <div id=\"appcomponent\">\r\n <div class=\"testclass\">contain</div>\r\n </div>\r\n```\r\n\r\nThis behavior causes a twitch of the interface, due to the belated addition of classes with styles.\r\nAlso incorrect display if the js file not to load on slow internet.",
"comments": [
{
"body": "Hello @PowerfulPony,\n\nthank you for your filing this issue.\n\nPlease follow the [guidelines](https://github.com/vuejs/vue/blob/dev/CONTRIBUTING.md) on how to report an issue. In particular, provide an example on www.jsfiddle.net (or a similar service) that reproduces the problem.\n\nThank you.\n",
"created_at": "2016-11-07T08:36:18Z"
},
{
"body": "Hi @LinusBorg,\nI do not understand how you can demonstrate through the server render jsfiddle.\n",
"created_at": "2016-11-07T10:05:53Z"
},
{
"body": "In this case, a repository would be the better option, oviously.\n",
"created_at": "2016-11-07T12:01:47Z"
},
{
"body": "As @LinusBorg said, it would be better to provide a repository for this case. Seems to be a bug, similar to #4076\n",
"created_at": "2016-11-07T15:09:25Z"
}
],
"number": 4143,
"title": "Using SSR with defined dynamic components, not rendered classes at tag (component)"
} | {
"body": "fix #4143",
"number": 4146,
"review_comments": [],
"title": "Update ssr class render (fix #4143)"
} | {
"commits": [
{
"message": "fix ssr class render"
},
{
"message": "update test case"
}
],
"files": [
{
"diff": "@@ -3,7 +3,8 @@\n import { genClassForVnode } from 'web/util/index'\n \n export default function renderClass (node: VNodeWithData): ?string {\n- if (node.data.class || node.data.staticClass) {\n- return ` class=\"${genClassForVnode(node)}\"`\n+ const classList = genClassForVnode(node)\n+ if (classList) {\n+ return ` class=\"${classList}\"`\n }\n }",
"filename": "src/platforms/web/server/modules/class.js",
"status": "modified"
},
{
"diff": "@@ -57,6 +57,42 @@ describe('SSR: renderToString', () => {\n })\n })\n \n+ it('custome component class', done => {\n+ renderVmWithOptions({\n+ template: '<div><cmp class=\"cmp\"></cmp></div>',\n+ components: {\n+ cmp: {\n+ render: h => h('div', 'test')\n+ }\n+ }\n+ }, result => {\n+ expect(result).toContain('<div server-rendered=\"true\"><div class=\"cmp\">test</div></div>')\n+ done()\n+ })\n+ })\n+\n+ it('nested component class', done => {\n+ renderVmWithOptions({\n+ template: '<cmp class=\"outer\" :class=\"cls\"></cmp>',\n+ data: { cls: { 'success': 1 }},\n+ components: {\n+ cmp: {\n+ render: h => h('div', [h('nested', { staticClass: 'nested', 'class': { 'error': 1 }})]),\n+ components: {\n+ nested: {\n+ render: h => h('div', { staticClass: 'inner' }, 'test')\n+ }\n+ }\n+ }\n+ }\n+ }, result => {\n+ expect(result).toContain('<div server-rendered=\"true\" class=\"outer success\">' +\n+ '<div class=\"inner nested error\">test</div>' +\n+ '</div>')\n+ done()\n+ })\n+ })\n+\n it('dynamic style', done => {\n renderVmWithOptions({\n template: '<div style=\"background-color:black\" :style=\"{ fontSize: fontSize + \\'px\\', color: color }\"></div>',",
"filename": "test/ssr/ssr-string.spec.js",
"status": "modified"
}
]
} |
{
"body": "<!-- BUG REPORT TEMPLATE -->\n### Vue.js version\n\n2.0.3\n### Reproduction Link\n\nhttps://jsfiddle.net/e4mxqbfv/1/\n### Steps to reproduce\n\nChange the selected option an look at the output in `<pre>` element below.\n### What is Expected?\n\nSelected number type should be a `Number` because `<select>` element is bound to a variable (model) and has `.number` modifier: `<select v-model.number=\"perpage\">`.\n### What is actually happening?\n\nVue fails to cast the selected value to `Number`, it remains a `String`.\n### Workarounds\n\nSome people have suggested binding the value `<option :value=\"10\">10</option>`, but that's a workaround, not a fix. It's be great if the modifier worked on `<select>` too or at least there would be a notice in the documentation.\n",
"comments": [
{
"body": "Thanks @gskema , I am looking into this.\n",
"created_at": "2016-10-23T14:35:26Z"
},
{
"body": "I'll fix the problem later\n",
"created_at": "2016-10-23T15:18:51Z"
}
],
"number": 4018,
"title": "Model .number modifier fails to cast selected value of select element."
} | {
"body": "fix #4018\n",
"number": 4022,
"review_comments": [
{
"body": "Is modifiers type `{[key: string]: true}` more specific? Reference: https://github.com/vuejs/vue/blob/dev/flow/compiler.js#L46\n",
"created_at": "2016-10-25T15:25:21Z"
},
{
"body": "I think so. I'll update it\n",
"created_at": "2016-10-26T05:12:06Z"
},
{
"body": "I think a ternary could be used here\n",
"created_at": "2016-10-26T17:04:23Z"
},
{
"body": "Thanks, updated :)\n",
"created_at": "2016-10-28T14:00:41Z"
}
],
"title": ".number modifier should work with select, radio, checkbox (fix #4018)"
} | {
"commits": [
{
"message": "support number modifier in select, radio, checkbox"
},
{
"message": "add test case"
},
{
"message": "add ASTModifier type to specify modifiers type"
},
{
"message": "fix typo"
},
{
"message": "keep code consistent"
}
],
"files": [
{
"diff": "@@ -41,9 +41,11 @@ declare type ModuleOptions = {\n staticKeys?: Array<string>; // AST properties to be considered static\n }\n \n+declare type ASTModifiers = { [key: string]: boolean }\n+\n declare type ASTElementHandler = {\n value: string;\n- modifiers: ?{ [key: string]: true };\n+ modifiers: ?ASTModifiers;\n }\n \n declare type ASTElementHandlers = {\n@@ -55,7 +57,7 @@ declare type ASTDirective = {\n rawName: string;\n value: string;\n arg: ?string;\n- modifiers: ?{ [key: string]: true };\n+ modifiers: ?ASTModifiers;\n }\n \n declare type ASTNode = ASTElement | ASTText | ASTExpression",
"filename": "flow/compiler.js",
"status": "modified"
},
{
"diff": "@@ -60,6 +60,6 @@ declare type VNodeDirective = {\n value?: any;\n oldValue?: any;\n arg?: string;\n- modifiers?: { [key: string]: boolean };\n+ modifiers?: ASTModifiers;\n def?: Object;\n }",
"filename": "flow/vnode.js",
"status": "modified"
},
{
"diff": "@@ -27,7 +27,7 @@ export function addDirective (\n rawName: string,\n value: string,\n arg: ?string,\n- modifiers: ?{ [key: string]: true }\n+ modifiers: ?ASTModifiers\n ) {\n (el.directives || (el.directives = [])).push({ name, rawName, value, arg, modifiers })\n }\n@@ -36,7 +36,7 @@ export function addHandler (\n el: ASTElement,\n name: string,\n value: string,\n- modifiers: ?{ [key: string]: true },\n+ modifiers: ?ASTModifiers,\n important: ?boolean\n ) {\n // check capture modifier",
"filename": "src/compiler/helpers.js",
"status": "modified"
},
{
"diff": "@@ -26,19 +26,23 @@ export default function model (\n }\n }\n if (tag === 'select') {\n- genSelect(el, value)\n+ genSelect(el, value, modifiers)\n } else if (tag === 'input' && type === 'checkbox') {\n- genCheckboxModel(el, value)\n+ genCheckboxModel(el, value, modifiers)\n } else if (tag === 'input' && type === 'radio') {\n- genRadioModel(el, value)\n+ genRadioModel(el, value, modifiers)\n } else {\n genDefaultModel(el, value, modifiers)\n }\n // ensure runtime directive metadata\n return true\n }\n \n-function genCheckboxModel (el: ASTElement, value: string) {\n+function genCheckboxModel (\n+ el: ASTElement,\n+ value: string,\n+ modifiers: ?ASTModifiers\n+) {\n if (process.env.NODE_ENV !== 'production' &&\n el.attrsMap.checked != null) {\n warn(\n@@ -47,6 +51,7 @@ function genCheckboxModel (el: ASTElement, value: string) {\n 'Declare initial values in the component\\'s data option instead.'\n )\n }\n+ const number = modifiers && modifiers.number\n const valueBinding = getBindingAttr(el, 'value') || 'null'\n const trueValueBinding = getBindingAttr(el, 'true-value') || 'true'\n const falseValueBinding = getBindingAttr(el, 'false-value') || 'false'\n@@ -60,7 +65,7 @@ function genCheckboxModel (el: ASTElement, value: string) {\n '$$el=$event.target,' +\n `$$c=$$el.checked?(${trueValueBinding}):(${falseValueBinding});` +\n 'if(Array.isArray($$a)){' +\n- `var $$v=${valueBinding},` +\n+ `var $$v=${number ? '_n(' + valueBinding + ')' : valueBinding},` +\n '$$i=_i($$a,$$v);' +\n `if($$c){$$i<0&&(${value}=$$a.concat($$v))}` +\n `else{$$i>-1&&(${value}=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}` +\n@@ -69,7 +74,11 @@ function genCheckboxModel (el: ASTElement, value: string) {\n )\n }\n \n-function genRadioModel (el: ASTElement, value: string) {\n+function genRadioModel (\n+ el: ASTElement,\n+ value: string,\n+ modifiers: ?ASTModifiers\n+) {\n if (process.env.NODE_ENV !== 'production' &&\n el.attrsMap.checked != null) {\n warn(\n@@ -78,15 +87,17 @@ function genRadioModel (el: ASTElement, value: string) {\n 'Declare initial values in the component\\'s data option instead.'\n )\n }\n- const valueBinding = getBindingAttr(el, 'value') || 'null'\n+ const number = modifiers && modifiers.number\n+ let valueBinding = getBindingAttr(el, 'value') || 'null'\n+ valueBinding = number ? `_n(${valueBinding})` : valueBinding\n addProp(el, 'checked', `_q(${value},${valueBinding})`)\n addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true)\n }\n \n function genDefaultModel (\n el: ASTElement,\n value: string,\n- modifiers: ?Object\n+ modifiers: ?ASTModifiers\n ): ?boolean {\n if (process.env.NODE_ENV !== 'production') {\n if (el.tag === 'input' && el.attrsMap.value) {\n@@ -111,12 +122,13 @@ function genDefaultModel (\n const needCompositionGuard = !lazy && type !== 'range'\n const isNative = el.tag === 'input' || el.tag === 'textarea'\n \n- const valueExpression = isNative\n+ let valueExpression = isNative\n ? `$event.target.value${trim ? '.trim()' : ''}`\n : `$event`\n- let code = number || type === 'number'\n- ? genAssignmentCode(value, `_n(${valueExpression})`)\n- : genAssignmentCode(value, valueExpression)\n+ valueExpression = number || type === 'number'\n+ ? `_n(${valueExpression})`\n+ : valueExpression\n+ let code = genAssignmentCode(value, valueExpression)\n if (isNative && needCompositionGuard) {\n code = `if($event.target.composing)return;${code}`\n }\n@@ -133,14 +145,20 @@ function genDefaultModel (\n addHandler(el, event, code, null, true)\n }\n \n-function genSelect (el: ASTElement, value: string) {\n+function genSelect (\n+ el: ASTElement,\n+ value: string,\n+ modifiers: ?ASTModifiers\n+) {\n if (process.env.NODE_ENV !== 'production') {\n el.children.some(checkOptionWarning)\n }\n \n+ const number = modifiers && modifiers.number\n const assignment = `Array.prototype.filter` +\n `.call($event.target.options,function(o){return o.selected})` +\n- `.map(function(o){return \"_value\" in o ? o._value : o.value})` +\n+ `.map(function(o){var val = \"_value\" in o ? o._value : o.value;` +\n+ `return ${number ? '_n(val)' : 'val'}})` +\n (el.attrsMap.multiple == null ? '[0]' : '')\n \n const code = genAssignmentCode(value, assignment)",
"filename": "src/platforms/web/compiler/directives/model.js",
"status": "modified"
},
{
"diff": "@@ -133,6 +133,32 @@ describe('Directive v-model checkbox', () => {\n }).then(done)\n })\n \n+ it('.number modifier', () => {\n+ const vm = new Vue({\n+ data: {\n+ test: [],\n+ check: true\n+ },\n+ template: `\n+ <div>\n+ <input type=\"checkbox\" v-model.number=\"test\" value=\"1\">\n+ <input type=\"checkbox\" v-model=\"test\" value=\"2\">\n+ <input type=\"checkbox\" v-model.number=\"check\">\n+ </div>\n+ `\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ var checkboxInputs = vm.$el.getElementsByTagName('input')\n+ expect(checkboxInputs[0].checked).toBe(false)\n+ expect(checkboxInputs[1].checked).toBe(false)\n+ expect(checkboxInputs[2].checked).toBe(true)\n+ checkboxInputs[0].click()\n+ checkboxInputs[1].click()\n+ checkboxInputs[2].click()\n+ expect(vm.test).toEqual([1, '2'])\n+ expect(vm.check).toEqual(false)\n+ })\n+\n it('warn inline checked', () => {\n const vm = new Vue({\n template: `<input type=\"checkbox\" v-model=\"test\" checked>`,",
"filename": "test/unit/features/directives/model-checkbox.spec.js",
"status": "modified"
},
{
"diff": "@@ -125,6 +125,27 @@ describe('Directive v-model radio', () => {\n }).then(done)\n })\n \n+ it('.number modifier', () => {\n+ const vm = new Vue({\n+ data: {\n+ test: 1\n+ },\n+ template: `\n+ <div>\n+ <input type=\"radio\" value=\"1\" v-model=\"test\" name=\"test\">\n+ <input type=\"radio\" value=\"2\" v-model.number=\"test\" name=\"test\">\n+ </div>\n+ `\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ expect(vm.$el.children[0].checked).toBe(true)\n+ expect(vm.$el.children[1].checked).toBe(false)\n+ vm.$el.children[1].click()\n+ expect(vm.$el.children[0].checked).toBe(false)\n+ expect(vm.$el.children[1].checked).toBe(true)\n+ expect(vm.test).toBe(2)\n+ })\n+\n it('warn inline checked', () => {\n const vm = new Vue({\n template: `<input v-model=\"test\" type=\"radio\" value=\"1\" checked>`,",
"filename": "test/unit/features/directives/model-radio.spec.js",
"status": "modified"
},
{
"diff": "@@ -301,6 +301,24 @@ describe('Directive v-model select', () => {\n }).then(done)\n })\n \n+ it('.number modifier', () => {\n+ const vm = new Vue({\n+ data: {\n+ test: 2\n+ },\n+ template:\n+ '<select v-model.number=\"test\">' +\n+ '<option value=\"1\">a</option>' +\n+ '<option :value=\"2\">b</option>' +\n+ ' <option :value=\"3\">c</option>' +\n+ '</select>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ updateSelect(vm.$el, '1')\n+ triggerEvent(vm.$el, 'change')\n+ expect(vm.test).toBe(1)\n+ })\n+\n it('should warn inline selected', () => {\n const vm = new Vue({\n data: {",
"filename": "test/unit/features/directives/model-select.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\n\n2.0.2\n### Reproduction Link\n\nhttp://jsfiddle.net/2vqkLkjL/1/\n### Steps to reproduce\n- Create a component with a nested data property: Object, of an object containing an array.\n- Set up watcher for this property, specifying the deep flag.\n### What is Expected?\n\nWhen the value of an array changes, the watcher runs\n### What is actually happening?\n\nWatcher isn't getting triggered.\n\nThe code seemed to work fine in Vue 1.x.\n\nNot 100% nested objects/arrays is the correct way for managing a view with lots of inputs.\n",
"comments": [
{
"body": "the same problem with #3958 I am resolving this problem\n\n@allistera You could use object as a workaround now. [jsfiddler](http://jsfiddle.net/defcc/2vqkLkjL/2/) here\n",
"created_at": "2016-10-18T23:37:08Z"
},
{
"body": "Ah I should have done a better job searching. Thanks deffc awesome work!\n",
"created_at": "2016-10-19T06:02:49Z"
},
{
"body": "closing as it duplicates #3958 \n",
"created_at": "2016-10-19T11:41:08Z"
}
],
"number": 3979,
"title": "Unable to watch nested data"
} | {
"body": "fix #3958 #3979 \nAs for array type case, v-model=\"model[idx]\" binding uses **model[idx]=** internally, so the value change could not be reactive.\n\nthe binding model expression maybe be as follows:\n- test\n- test[idx]\n- test[test1[idx]]\n- xxx.test[a[a].test1[idx]]\n- test.xxx.a[\"asa\"][test1[idx]]\n- test[\"a\"][idx]\n\nSo I use a modelParser to parse the model expression to two parts **exp** and **idx**, and if the exp is an Array type, then use $$exp.splice($$idx, 1, value)\n",
"number": 3988,
"review_comments": [],
"title": "v-model binding with array. (fix #3958,#3979)"
} | {
"commits": [
{
"message": "fix v-model with array binding"
},
{
"message": "add mutli selects test case"
},
{
"message": "add test case. v-bind with array"
},
{
"message": "add comments"
},
{
"message": "code refactor"
}
],
"files": [
{
"diff": "@@ -2,6 +2,7 @@\n \n import { isIE } from 'core/util/env'\n import { addHandler, addProp, getBindingAttr } from 'compiler/helpers'\n+import parseModel from 'web/util/model'\n \n let warn\n \n@@ -79,7 +80,7 @@ function genRadioModel (el: ASTElement, value: string) {\n }\n const valueBinding = getBindingAttr(el, 'value') || 'null'\n addProp(el, 'checked', `_q(${value},${valueBinding})`)\n- addHandler(el, 'change', `${value}=${valueBinding}`, null, true)\n+ addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true)\n }\n \n function genDefaultModel (\n@@ -114,8 +115,8 @@ function genDefaultModel (\n ? `$event.target.value${trim ? '.trim()' : ''}`\n : `$event`\n let code = number || type === 'number'\n- ? `${value}=_n(${valueExpression})`\n- : `${value}=${valueExpression}`\n+ ? genAssignmentCode(value, `_n(${valueExpression})`)\n+ : genAssignmentCode(value, valueExpression)\n if (isNative && needCompositionGuard) {\n code = `if($event.target.composing)return;${code}`\n }\n@@ -136,10 +137,13 @@ function genSelect (el: ASTElement, value: string) {\n if (process.env.NODE_ENV !== 'production') {\n el.children.some(checkOptionWarning)\n }\n- const code = `${value}=Array.prototype.filter` +\n+\n+ const assignment = `Array.prototype.filter` +\n `.call($event.target.options,function(o){return o.selected})` +\n `.map(function(o){return \"_value\" in o ? o._value : o.value})` +\n (el.attrsMap.multiple == null ? '[0]' : '')\n+\n+ const code = genAssignmentCode(value, assignment)\n addHandler(el, 'change', code, null, true)\n }\n \n@@ -156,3 +160,15 @@ function checkOptionWarning (option: any): boolean {\n }\n return false\n }\n+\n+function genAssignmentCode (value: string, assignment: string): string {\n+ const modelRs = parseModel(value)\n+ if (modelRs.idx === null) {\n+ return `${value}=${assignment}`\n+ } else {\n+ return `var $$exp = ${modelRs.exp}, $$idx = ${modelRs.idx};` +\n+ `if (!Array.isArray($$exp)){` +\n+ `${value}=${assignment}}` +\n+ `else{$$exp.splice($$idx, 1, ${assignment})}`\n+ }\n+}",
"filename": "src/platforms/web/compiler/directives/model.js",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,84 @@\n+/* @flow */\n+\n+let len, str, chr, index, expressionPos, expressionEndPos\n+\n+/**\n+ * parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)\n+ *\n+ * for loop possible cases:\n+ *\n+ * - test\n+ * - test[idx]\n+ * - test[test1[idx]]\n+ * - test[\"a\"][idx]\n+ * - xxx.test[a[a].test1[idx]]\n+ * - test.xxx.a[\"asa\"][test1[idx]]\n+ *\n+ */\n+\n+export default function parseModel (val: string): Object {\n+ str = val\n+ len = str.length\n+ index = expressionPos = expressionEndPos = 0\n+\n+ if (val.indexOf('[') < 0) {\n+ return {\n+ exp: val,\n+ idx: null\n+ }\n+ }\n+\n+ while (!eof()) {\n+ chr = next()\n+ if (isStringStart(chr)) {\n+ parseString(chr)\n+ } else if (chr === 0x5B) {\n+ parseBracket(chr)\n+ }\n+ }\n+\n+ return {\n+ exp: val.substring(0, expressionPos),\n+ idx: val.substring(expressionPos + 1, expressionEndPos)\n+ }\n+}\n+\n+function next (): number {\n+ return str.charCodeAt(++index)\n+}\n+\n+function eof (): boolean {\n+ return index >= len\n+}\n+\n+function isStringStart (chr: number): boolean {\n+ return chr === 0x22 || chr === 0x27\n+}\n+\n+function parseBracket (chr: number): void {\n+ let inBracket = 1\n+ expressionPos = index\n+ while (!eof()) {\n+ chr = next()\n+ if (isStringStart(chr)) {\n+ parseString(chr)\n+ continue\n+ }\n+ if (chr === 0x5B) inBracket++\n+ if (chr === 0x5D) inBracket--\n+ if (inBracket === 0) {\n+ expressionEndPos = index\n+ break\n+ }\n+ }\n+}\n+\n+function parseString (chr: number): void {\n+ const stringQuote = chr\n+ while (!eof()) {\n+ chr = next()\n+ if (chr === stringQuote) {\n+ break\n+ }\n+ }\n+}",
"filename": "src/platforms/web/util/model.js",
"status": "added"
},
{
"diff": "@@ -2,14 +2,18 @@ import Vue from 'vue'\n \n describe('Directive v-model component', () => {\n it('should work', done => {\n+ const spy = jasmine.createSpy()\n const vm = new Vue({\n data: {\n- msg: 'hello'\n+ msg: ['hello']\n+ },\n+ watch: {\n+ msg: spy\n },\n template: `\n <div>\n <p>{{ msg }}</p>\n- <validate v-model=\"msg\">\n+ <validate v-model=\"msg[0]\">\n <input type=\"text\">\n </validate>\n </div>\n@@ -40,7 +44,8 @@ describe('Directive v-model component', () => {\n input.value = 'world'\n triggerEvent(input, 'input')\n }).then(() => {\n- expect(vm.msg).toBe('world')\n+ expect(vm.msg).toEqual(['world'])\n+ expect(spy).toHaveBeenCalled()\n }).then(() => {\n document.body.removeChild(vm.$el)\n vm.$destroy()",
"filename": "test/unit/features/directives/model-component.spec.js",
"status": "modified"
},
{
"diff": "@@ -85,6 +85,46 @@ describe('Directive v-model radio', () => {\n }).then(done)\n })\n \n+ it('multiple radios ', (done) => {\n+ const spy = jasmine.createSpy()\n+ const vm = new Vue({\n+ data: {\n+ selections: ['a', '1'],\n+ radioList: [\n+ {\n+ name: 'questionA',\n+ data: ['a', 'b', 'c']\n+ },\n+ {\n+ name: 'questionB',\n+ data: ['1', '2']\n+ }\n+ ]\n+ },\n+ watch: {\n+ selections: spy\n+ },\n+ template:\n+ '<div>' +\n+ '<div v-for=\"(radioGroup, idx) in radioList\">' +\n+ '<div>' +\n+ '<span v-for=\"(item, index) in radioGroup.data\">' +\n+ '<input :name=\"radioGroup.name\" type=\"radio\" :value=\"item\" v-model=\"selections[idx]\" :id=\"idx\"/>' +\n+ '<label>{{item}}</label>' +\n+ '</span>' +\n+ '</div>' +\n+ '</div>' +\n+ '</div>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ var inputs = vm.$el.getElementsByTagName('input')\n+ inputs[1].click()\n+ waitForUpdate(() => {\n+ expect(vm.selections).toEqual(['b', '1'])\n+ expect(spy).toHaveBeenCalled()\n+ }).then(done)\n+ })\n+\n it('warn inline checked', () => {\n const vm = new Vue({\n template: `<input v-model=\"test\" type=\"radio\" value=\"1\" checked>`,",
"filename": "test/unit/features/directives/model-radio.spec.js",
"status": "modified"
},
{
"diff": "@@ -263,6 +263,44 @@ describe('Directive v-model select', () => {\n }).then(done)\n })\n \n+ it('multiple selects', (done) => {\n+ const spy = jasmine.createSpy()\n+ const vm = new Vue({\n+ data: {\n+ selections: ['', ''],\n+ selectBoxes: [\n+ [\n+ { value: 'foo', text: 'foo' },\n+ { value: 'bar', text: 'bar' }\n+ ],\n+ [\n+ { value: 'day', text: 'day' },\n+ { value: 'night', text: 'night' }\n+ ]\n+ ]\n+ },\n+ watch: {\n+ selections: spy\n+ },\n+ template:\n+ '<div>' +\n+ '<select v-for=\"(item, index) in selectBoxes\" v-model=\"selections[index]\">' +\n+ '<option v-for=\"element in item\" v-bind:value=\"element.value\" v-text=\"element.text\"></option>' +\n+ '</select>' +\n+ '<span ref=\"rs\">{{selections}}</span>' +\n+ '</div>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ var selects = vm.$el.getElementsByTagName('select')\n+ var select0 = selects[0]\n+ select0.options[0].selected = true\n+ triggerEvent(select0, 'change')\n+ waitForUpdate(() => {\n+ expect(spy).toHaveBeenCalled()\n+ expect(vm.selections).toEqual(['foo', ''])\n+ }).then(done)\n+ })\n+\n it('should warn inline selected', () => {\n const vm = new Vue({\n data: {",
"filename": "test/unit/features/directives/model-select.spec.js",
"status": "modified"
},
{
"diff": "@@ -64,6 +64,47 @@ describe('Directive v-model text', () => {\n expect(vm.test).toBe('what')\n })\n \n+ it('multiple inputs', (done) => {\n+ const spy = jasmine.createSpy()\n+ const vm = new Vue({\n+ data: {\n+ selections: [[1, 2, 3], [4, 5]],\n+ inputList: [\n+ {\n+ name: 'questionA',\n+ data: ['a', 'b', 'c']\n+ },\n+ {\n+ name: 'questionB',\n+ data: ['1', '2']\n+ }\n+ ]\n+ },\n+ watch: {\n+ selections: spy\n+ },\n+ template:\n+ '<div>' +\n+ '<div v-for=\"(inputGroup, idx) in inputList\">' +\n+ '<div>' +\n+ '<span v-for=\"(item, index) in inputGroup.data\">' +\n+ '<input v-bind:name=\"item\" type=\"text\" v-model.number=\"selections[idx][index]\" v-bind:id=\"idx+\\'-\\'+index\"/>' +\n+ '<label>{{item}}</label>' +\n+ '</span>' +\n+ '</div>' +\n+ '</div>' +\n+ '<span ref=\"rs\">{{selections}}</span>' +\n+ '</div>'\n+ }).$mount()\n+ var inputs = vm.$el.getElementsByTagName('input')\n+ inputs[1].value = 'test'\n+ triggerEvent(inputs[1], 'input')\n+ waitForUpdate(() => {\n+ expect(spy).toHaveBeenCalled()\n+ expect(vm.selections).toEqual([[1, 'test', 3], [4, 5]])\n+ }).then(done)\n+ })\n+\n if (isIE9) {\n it('IE9 selectionchange', done => {\n const vm = new Vue({",
"filename": "test/unit/features/directives/model-text.spec.js",
"status": "modified"
}
]
} |
{
"body": "I'm in process migrating an application from Vue 1.x to 2.0.3. In this application I'm having several selects where each v-model binds to an individual index of an array . This is without problems in Vue 1.x but in version 2 it does not update. I believe this is a potential bug.\n\nI have reproduced the problem here:\nhttps://jsfiddle.net/peterkorgaard/a7vvz753/18/\n\n<!--\n中文用户请注意:\n\n1. issue 只接受带重现的 bug 报告,请不要用来提问题!不符合要求的 issue 会被直接关闭。\n2. 请尽量用英文描述你的 issue,这样能够让尽可能多的人帮到你。\n\nGot a question?\n===============\nThe issue list of this repo is **exclusively** for bug reports and feature requests. For simple questions, please use the following resources:\n\n- Read the docs: https://vuejs.org/guide/\n- Watch video tutorials: https://laracasts.com/series/learning-vue-step-by-step\n- Ask in the Gitter chat room: https://gitter.im/vuejs/vue\n- Ask on the forums: http://forum.vuejs.org/\n- Look for/ask questions on stack overflow: https://stackoverflow.com/questions/ask?tags=vue.js\n\nReporting a bug?\n================\n- Try to search for your issue, it may have already been answered or even fixed in the development branch.\n\n- Check if the issue is reproducible with the latest stable version of Vue. If you are using a pre-release, please indicate the specific version you are using.\n\n- It is **required** that you clearly describe the steps necessary to reproduce the issue you are running into. Issues with no clear repro steps will not be triaged. If an issue labeled \"need repro\" receives no further input from the issue author for more than 5 days, it will be closed.\n\n- It is recommended that you make a JSFiddle/JSBin/Codepen to demonstrate your issue. You could start with [this template](http://jsfiddle.net/5sH6A/) that already includes the latest version of Vue.\n\n- For bugs that involves build setups, you can create a reproduction repository with steps in the README.\n\n- If your issue is resolved but still open, don’t hesitate to close it. In case you found a solution by yourself, it could be helpful to explain how you fixed it.\n\nHave a feature request?\n=======================\nRemove the template from below and provide thoughtful commentary *and code samples* on what this feature means for your product. What will it allow you to do that you can't do today? How will it make current work-arounds straightforward? What potential bugs and edge cases does it help to avoid? etc. Please keep it product-centric.\n-->\n\n<!-- BUG REPORT TEMPLATE -->\n### Vue.js version\n\n2.0.3\n### Reproduction Link\n\nhttps://jsfiddle.net/peterkorgaard/a7vvz753/18/\n### Steps to reproduce\n### What is Expected?\n### What is actually happening?\n",
"comments": [
{
"body": "I am looking into this. Seems selections do not get Observered correctly\n",
"created_at": "2016-10-17T00:43:38Z"
},
{
"body": "@peterkorgaard I update the fiddler here [https://jsfiddle.net/defcc/a7vvz753/20/](https://jsfiddle.net/defcc/a7vvz753/20/), You could use like this as a workaround. \n\nFor more info, take a look at this [http://vuejs.org/guide/reactivity.html#Change-Detection-Caveats](http://vuejs.org/guide/reactivity.html#Change-Detection-Caveats)\n",
"created_at": "2016-10-17T01:02:53Z"
},
{
"body": "I got the same question.\n\n@defcc Your solution can solve that we already know how many items of the model. If change the model from array to object, how can we do?\n",
"created_at": "2016-10-17T02:54:57Z"
},
{
"body": "You should use **object** type, as model binding uses **model[index]=** in internal implementation. If you use array type, the value could not be observed. [http://vuejs.org/guide/list.html#Caveats](http://vuejs.org/guide/list.html#Caveats)\n\nYou could init the selections when created, and update the selections after the selectBoxes data updated.\n\nI update the fiddler here [https://jsfiddle.net/defcc/a7vvz753/21/](https://jsfiddle.net/defcc/a7vvz753/21/)\n",
"created_at": "2016-10-17T03:56:03Z"
},
{
"body": "@defcc Bravo, this solution worked for me fine. Thank you so much!\n",
"created_at": "2016-10-17T06:03:49Z"
},
{
"body": "Thank you, @defcc, for clarifying this. I will use this workaround until the problem gets solved. And thanks for the great work everybody does on Vue. I'm really amazed.\n",
"created_at": "2016-10-17T08:55:40Z"
}
],
"number": 3958,
"title": "vue 2.0.3 v-model not updating using an array"
} | {
"body": "fix #3958 #3979 \nAs for array type case, v-model=\"model[idx]\" binding uses **model[idx]=** internally, so the value change could not be reactive.\n\nthe binding model expression maybe be as follows:\n- test\n- test[idx]\n- test[test1[idx]]\n- xxx.test[a[a].test1[idx]]\n- test.xxx.a[\"asa\"][test1[idx]]\n- test[\"a\"][idx]\n\nSo I use a modelParser to parse the model expression to two parts **exp** and **idx**, and if the exp is an Array type, then use $$exp.splice($$idx, 1, value)\n",
"number": 3988,
"review_comments": [],
"title": "v-model binding with array. (fix #3958,#3979)"
} | {
"commits": [
{
"message": "fix v-model with array binding"
},
{
"message": "add mutli selects test case"
},
{
"message": "add test case. v-bind with array"
},
{
"message": "add comments"
},
{
"message": "code refactor"
}
],
"files": [
{
"diff": "@@ -2,6 +2,7 @@\n \n import { isIE } from 'core/util/env'\n import { addHandler, addProp, getBindingAttr } from 'compiler/helpers'\n+import parseModel from 'web/util/model'\n \n let warn\n \n@@ -79,7 +80,7 @@ function genRadioModel (el: ASTElement, value: string) {\n }\n const valueBinding = getBindingAttr(el, 'value') || 'null'\n addProp(el, 'checked', `_q(${value},${valueBinding})`)\n- addHandler(el, 'change', `${value}=${valueBinding}`, null, true)\n+ addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true)\n }\n \n function genDefaultModel (\n@@ -114,8 +115,8 @@ function genDefaultModel (\n ? `$event.target.value${trim ? '.trim()' : ''}`\n : `$event`\n let code = number || type === 'number'\n- ? `${value}=_n(${valueExpression})`\n- : `${value}=${valueExpression}`\n+ ? genAssignmentCode(value, `_n(${valueExpression})`)\n+ : genAssignmentCode(value, valueExpression)\n if (isNative && needCompositionGuard) {\n code = `if($event.target.composing)return;${code}`\n }\n@@ -136,10 +137,13 @@ function genSelect (el: ASTElement, value: string) {\n if (process.env.NODE_ENV !== 'production') {\n el.children.some(checkOptionWarning)\n }\n- const code = `${value}=Array.prototype.filter` +\n+\n+ const assignment = `Array.prototype.filter` +\n `.call($event.target.options,function(o){return o.selected})` +\n `.map(function(o){return \"_value\" in o ? o._value : o.value})` +\n (el.attrsMap.multiple == null ? '[0]' : '')\n+\n+ const code = genAssignmentCode(value, assignment)\n addHandler(el, 'change', code, null, true)\n }\n \n@@ -156,3 +160,15 @@ function checkOptionWarning (option: any): boolean {\n }\n return false\n }\n+\n+function genAssignmentCode (value: string, assignment: string): string {\n+ const modelRs = parseModel(value)\n+ if (modelRs.idx === null) {\n+ return `${value}=${assignment}`\n+ } else {\n+ return `var $$exp = ${modelRs.exp}, $$idx = ${modelRs.idx};` +\n+ `if (!Array.isArray($$exp)){` +\n+ `${value}=${assignment}}` +\n+ `else{$$exp.splice($$idx, 1, ${assignment})}`\n+ }\n+}",
"filename": "src/platforms/web/compiler/directives/model.js",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,84 @@\n+/* @flow */\n+\n+let len, str, chr, index, expressionPos, expressionEndPos\n+\n+/**\n+ * parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)\n+ *\n+ * for loop possible cases:\n+ *\n+ * - test\n+ * - test[idx]\n+ * - test[test1[idx]]\n+ * - test[\"a\"][idx]\n+ * - xxx.test[a[a].test1[idx]]\n+ * - test.xxx.a[\"asa\"][test1[idx]]\n+ *\n+ */\n+\n+export default function parseModel (val: string): Object {\n+ str = val\n+ len = str.length\n+ index = expressionPos = expressionEndPos = 0\n+\n+ if (val.indexOf('[') < 0) {\n+ return {\n+ exp: val,\n+ idx: null\n+ }\n+ }\n+\n+ while (!eof()) {\n+ chr = next()\n+ if (isStringStart(chr)) {\n+ parseString(chr)\n+ } else if (chr === 0x5B) {\n+ parseBracket(chr)\n+ }\n+ }\n+\n+ return {\n+ exp: val.substring(0, expressionPos),\n+ idx: val.substring(expressionPos + 1, expressionEndPos)\n+ }\n+}\n+\n+function next (): number {\n+ return str.charCodeAt(++index)\n+}\n+\n+function eof (): boolean {\n+ return index >= len\n+}\n+\n+function isStringStart (chr: number): boolean {\n+ return chr === 0x22 || chr === 0x27\n+}\n+\n+function parseBracket (chr: number): void {\n+ let inBracket = 1\n+ expressionPos = index\n+ while (!eof()) {\n+ chr = next()\n+ if (isStringStart(chr)) {\n+ parseString(chr)\n+ continue\n+ }\n+ if (chr === 0x5B) inBracket++\n+ if (chr === 0x5D) inBracket--\n+ if (inBracket === 0) {\n+ expressionEndPos = index\n+ break\n+ }\n+ }\n+}\n+\n+function parseString (chr: number): void {\n+ const stringQuote = chr\n+ while (!eof()) {\n+ chr = next()\n+ if (chr === stringQuote) {\n+ break\n+ }\n+ }\n+}",
"filename": "src/platforms/web/util/model.js",
"status": "added"
},
{
"diff": "@@ -2,14 +2,18 @@ import Vue from 'vue'\n \n describe('Directive v-model component', () => {\n it('should work', done => {\n+ const spy = jasmine.createSpy()\n const vm = new Vue({\n data: {\n- msg: 'hello'\n+ msg: ['hello']\n+ },\n+ watch: {\n+ msg: spy\n },\n template: `\n <div>\n <p>{{ msg }}</p>\n- <validate v-model=\"msg\">\n+ <validate v-model=\"msg[0]\">\n <input type=\"text\">\n </validate>\n </div>\n@@ -40,7 +44,8 @@ describe('Directive v-model component', () => {\n input.value = 'world'\n triggerEvent(input, 'input')\n }).then(() => {\n- expect(vm.msg).toBe('world')\n+ expect(vm.msg).toEqual(['world'])\n+ expect(spy).toHaveBeenCalled()\n }).then(() => {\n document.body.removeChild(vm.$el)\n vm.$destroy()",
"filename": "test/unit/features/directives/model-component.spec.js",
"status": "modified"
},
{
"diff": "@@ -85,6 +85,46 @@ describe('Directive v-model radio', () => {\n }).then(done)\n })\n \n+ it('multiple radios ', (done) => {\n+ const spy = jasmine.createSpy()\n+ const vm = new Vue({\n+ data: {\n+ selections: ['a', '1'],\n+ radioList: [\n+ {\n+ name: 'questionA',\n+ data: ['a', 'b', 'c']\n+ },\n+ {\n+ name: 'questionB',\n+ data: ['1', '2']\n+ }\n+ ]\n+ },\n+ watch: {\n+ selections: spy\n+ },\n+ template:\n+ '<div>' +\n+ '<div v-for=\"(radioGroup, idx) in radioList\">' +\n+ '<div>' +\n+ '<span v-for=\"(item, index) in radioGroup.data\">' +\n+ '<input :name=\"radioGroup.name\" type=\"radio\" :value=\"item\" v-model=\"selections[idx]\" :id=\"idx\"/>' +\n+ '<label>{{item}}</label>' +\n+ '</span>' +\n+ '</div>' +\n+ '</div>' +\n+ '</div>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ var inputs = vm.$el.getElementsByTagName('input')\n+ inputs[1].click()\n+ waitForUpdate(() => {\n+ expect(vm.selections).toEqual(['b', '1'])\n+ expect(spy).toHaveBeenCalled()\n+ }).then(done)\n+ })\n+\n it('warn inline checked', () => {\n const vm = new Vue({\n template: `<input v-model=\"test\" type=\"radio\" value=\"1\" checked>`,",
"filename": "test/unit/features/directives/model-radio.spec.js",
"status": "modified"
},
{
"diff": "@@ -263,6 +263,44 @@ describe('Directive v-model select', () => {\n }).then(done)\n })\n \n+ it('multiple selects', (done) => {\n+ const spy = jasmine.createSpy()\n+ const vm = new Vue({\n+ data: {\n+ selections: ['', ''],\n+ selectBoxes: [\n+ [\n+ { value: 'foo', text: 'foo' },\n+ { value: 'bar', text: 'bar' }\n+ ],\n+ [\n+ { value: 'day', text: 'day' },\n+ { value: 'night', text: 'night' }\n+ ]\n+ ]\n+ },\n+ watch: {\n+ selections: spy\n+ },\n+ template:\n+ '<div>' +\n+ '<select v-for=\"(item, index) in selectBoxes\" v-model=\"selections[index]\">' +\n+ '<option v-for=\"element in item\" v-bind:value=\"element.value\" v-text=\"element.text\"></option>' +\n+ '</select>' +\n+ '<span ref=\"rs\">{{selections}}</span>' +\n+ '</div>'\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ var selects = vm.$el.getElementsByTagName('select')\n+ var select0 = selects[0]\n+ select0.options[0].selected = true\n+ triggerEvent(select0, 'change')\n+ waitForUpdate(() => {\n+ expect(spy).toHaveBeenCalled()\n+ expect(vm.selections).toEqual(['foo', ''])\n+ }).then(done)\n+ })\n+\n it('should warn inline selected', () => {\n const vm = new Vue({\n data: {",
"filename": "test/unit/features/directives/model-select.spec.js",
"status": "modified"
},
{
"diff": "@@ -64,6 +64,47 @@ describe('Directive v-model text', () => {\n expect(vm.test).toBe('what')\n })\n \n+ it('multiple inputs', (done) => {\n+ const spy = jasmine.createSpy()\n+ const vm = new Vue({\n+ data: {\n+ selections: [[1, 2, 3], [4, 5]],\n+ inputList: [\n+ {\n+ name: 'questionA',\n+ data: ['a', 'b', 'c']\n+ },\n+ {\n+ name: 'questionB',\n+ data: ['1', '2']\n+ }\n+ ]\n+ },\n+ watch: {\n+ selections: spy\n+ },\n+ template:\n+ '<div>' +\n+ '<div v-for=\"(inputGroup, idx) in inputList\">' +\n+ '<div>' +\n+ '<span v-for=\"(item, index) in inputGroup.data\">' +\n+ '<input v-bind:name=\"item\" type=\"text\" v-model.number=\"selections[idx][index]\" v-bind:id=\"idx+\\'-\\'+index\"/>' +\n+ '<label>{{item}}</label>' +\n+ '</span>' +\n+ '</div>' +\n+ '</div>' +\n+ '<span ref=\"rs\">{{selections}}</span>' +\n+ '</div>'\n+ }).$mount()\n+ var inputs = vm.$el.getElementsByTagName('input')\n+ inputs[1].value = 'test'\n+ triggerEvent(inputs[1], 'input')\n+ waitForUpdate(() => {\n+ expect(spy).toHaveBeenCalled()\n+ expect(vm.selections).toEqual([[1, 'test', 3], [4, 5]])\n+ }).then(done)\n+ })\n+\n if (isIE9) {\n it('IE9 selectionchange', done => {\n const vm = new Vue({",
"filename": "test/unit/features/directives/model-text.spec.js",
"status": "modified"
}
]
} |
{
"body": "Multiple select box does not work in same Vue instance.\n### Vue.js version\n- Vue.js v2.0.2\n### Reproduction Link\n\nhttps://jsfiddle.net/hd0drbo0/3/\n### Steps to reproduce\n\nChange second select box value, method \"testMethod\" will be called infinite times, even it is not bonded to second select box.\nChange first select box value, and later change second select box value, everything works as expected.\n### What is Expected?\n\nUpdate of different models of select.\n### What is actually happening?\n\nInfinite call of not assigned @change method.\n",
"comments": [
{
"body": "Cannot reproduce on windows 10 x64 Chrome 53 / Firefox 48 / Edge, everything works fine here.\nCan you specify the system and browser you're using?\n",
"created_at": "2016-10-12T13:42:22Z"
},
{
"body": "Windows 10 x64, Chrome 53.0.\n\nThis happens only if at least one select element model is not initialized, existing value in select options is not specified in model by default.\n\nSolution as suggested in line chat https://jsfiddle.net/crswll/hd0drbo0/5/\n",
"created_at": "2016-10-12T13:55:05Z"
},
{
"body": "> This happens only if at least one select element model is not initialized, existing value in select options is not specified in model by default. \n\nOk.. I see the problem now, looks like a bug to me.\n",
"created_at": "2016-10-12T14:04:49Z"
}
],
"number": 3917,
"title": "Multiple select elements @change event problem"
} | {
"body": "If select binding not changed, then needRest should be set to false, and no **change** event should be emitted. fix #3917 \n",
"number": 3922,
"review_comments": [],
"title": "select change event fix"
} | {
"commits": [
{
"message": "if select binding not changed, then needRest should be set to false, and no change event should be emitted"
},
{
"message": "update code style"
}
],
"files": [
{
"diff": "@@ -60,7 +60,7 @@ export default {\n // option in the DOM.\n const needReset = el.multiple\n ? binding.value.some(v => hasNoMatchingOption(v, el.options))\n- : hasNoMatchingOption(binding.value, el.options)\n+ : binding.value === binding.oldValue ? false : hasNoMatchingOption(binding.value, el.options)\n if (needReset) {\n trigger(el, 'change')\n }",
"filename": "src/platforms/web/runtime/directives/model.js",
"status": "modified"
},
{
"diff": "@@ -161,6 +161,32 @@ describe('Directive v-model select', () => {\n }).then(done)\n })\n \n+ it('should work with select which has no default selected options', (done) => {\n+ const spy = jasmine.createSpy()\n+ const vm = new Vue({\n+ data: {\n+ id: 4,\n+ list: [1, 2, 3],\n+ testChange: 5\n+ },\n+ template:\n+ '<div>' +\n+ '<select @change=\"test\" v-model=\"id\">' +\n+ '<option v-for=\"item in list\" :value=\"item\">{{item}}</option>' +\n+ '</select>' +\n+ '{{testChange}}' +\n+ '</div>',\n+ methods: {\n+ test: spy\n+ }\n+ }).$mount()\n+ document.body.appendChild(vm.$el)\n+ vm.testChange = 10\n+ waitForUpdate(() => {\n+ expect(spy.calls.count()).toBe(0)\n+ }).then(done)\n+ })\n+\n it('multiple', done => {\n const vm = new Vue({\n data: {",
"filename": "test/unit/features/directives/model-select.spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\n\n1.0.26\n### Reproduction Link\n\nhttps://jsfiddle.net/0o853fzd/\n\nTake a look at example. You can see that when i try to pass object to the filter as an argument it doesn't work when there is some space in the string.\n\n\n\nIsn't supposed to PR #834 fix this issue? or is it forbidden to use spaces when passing obejct to the filter like this?\n",
"comments": [
{
"body": "This is because the 1.x filter syntax uses space as the argument delimiter. If anyone wants to work on this, the relevant logic is here: https://github.com/vuejs/vue/blob/dev/src/parsers/directive.js#L20-L35\n",
"created_at": "2016-07-02T15:11:37Z"
},
{
"body": "I am working on a simple expression parser to parse the filter syntax rather then the regex way。Is it an acceptable method ? If so I will make a pull request soon.\n",
"created_at": "2016-09-20T16:48:03Z"
},
{
"body": "@defcc code size is also a concern here. We don't want to bloat the code for a relatively rare use case.\n",
"created_at": "2016-09-20T17:36:42Z"
},
{
"body": "ok, got it. @yyx990803 \n",
"created_at": "2016-09-21T01:51:23Z"
}
],
"number": 3210,
"title": "Parsing object as a filter argument fails with spaces inside"
} | {
"body": "Use a state machine based expression parser to parse the directive.\n\n fix #3210 and #3214 #\n",
"number": 3734,
"review_comments": [],
"title": "use a simple expression parser instead of regexp to parse directive"
} | {
"commits": [
{
"message": "use a simple expression parser instead of regexp to parse directive"
}
],
"files": [
{
"diff": "@@ -2,36 +2,173 @@ import { toNumber, stripQuotes } from '../util/index'\n import Cache from '../cache'\n \n const cache = new Cache(1000)\n-const filterTokenRE = /[^\\s'\"]+|'[^']*'|\"[^\"]*\"/g\n const reservedArgRE = /^in$|^-?\\d+/\n \n /**\n * Parser state\n */\n \n-var str, dir\n-var c, prev, i, l, lastFilterIndex\n-var inSingle, inDouble, curly, square, paren\n+var str, dir, len\n+var index\n+var chr\n+var state\n+var startState = 0\n+var filterState = 1\n+var filterNameState = 2\n+var filterArgState = 3\n+\n+var doubleChr = 0x22\n+var singleChr = 0x27\n+var pipeChr = 0x7C\n+var escapeChr = 0x5C\n+var spaceChr = 0x20\n+\n+var expStartChr = { 0x5B: 1, 0x7B: 1, 0x28: 1 }\n+var expChrPair = { 0x5B: 0x5D, 0x7B: 0x7D, 0x28: 0x29 }\n+\n+function peek () {\n+ return str.charCodeAt(index + 1)\n+}\n+\n+function next () {\n+ return str.charCodeAt(++index)\n+}\n+\n+function eof () {\n+ return index >= len\n+}\n+\n+function eatSpace () {\n+ while (peek() === spaceChr) {\n+ next()\n+ }\n+}\n+\n+function isStringStart (chr) {\n+ return chr === doubleChr || chr === singleChr\n+}\n+\n+function isExpStart (chr) {\n+ return expStartChr[chr]\n+}\n+\n+function isExpEnd (start, chr) {\n+ return expChrPair[start] === chr\n+}\n+\n+function parseString () {\n+ var stringQuote = next()\n+ var chr\n+ while (!eof()) {\n+ chr = next()\n+ // escape char\n+ if (chr === escapeChr) {\n+ next()\n+ } else if (chr === stringQuote) {\n+ break\n+ }\n+ }\n+}\n+\n+function parseSpecialExp (chr) {\n+ var inExp = 0\n+ var startChr = chr\n+\n+ while (!eof()) {\n+ chr = peek()\n+ if (isStringStart(chr)) {\n+ parseString()\n+ continue\n+ }\n+\n+ if (startChr === chr) {\n+ inExp++\n+ }\n+ if (isExpEnd(startChr, chr)) {\n+ inExp--\n+ }\n+\n+ next()\n+\n+ if (inExp === 0) {\n+ break\n+ }\n+ }\n+}\n \n /**\n- * Push a filter to the current directive object\n+ * syntax:\n+ * expression | filterName [arg arg [| filterName arg arg]]\n */\n \n-function pushFilter () {\n- var exp = str.slice(lastFilterIndex, i).trim()\n- var filter\n- if (exp) {\n- filter = {}\n- var tokens = exp.match(filterTokenRE)\n- filter.name = tokens[0]\n- if (tokens.length > 1) {\n- filter.args = tokens.slice(1).map(processFilterArg)\n+function parseExpression () {\n+ var start = index\n+ while (!eof()) {\n+ chr = peek()\n+ if (isStringStart(chr)) {\n+ parseString()\n+ } else if (isExpStart(chr)) {\n+ parseSpecialExp(chr)\n+ } else if (chr === pipeChr) {\n+ next()\n+ chr = peek()\n+ if (chr === pipeChr) {\n+ next()\n+ } else {\n+ if (state === startState || state === filterArgState) {\n+ state = filterState\n+ }\n+ break\n+ }\n+ } else if (chr === spaceChr && (state === filterNameState || state === filterArgState)) {\n+ eatSpace()\n+ break\n+ } else {\n+ if (state === filterState) {\n+ state = filterNameState\n+ }\n+ next()\n }\n }\n- if (filter) {\n- (dir.filters = dir.filters || []).push(filter)\n+\n+ return str.slice(start + 1, index) || null\n+}\n+\n+function parseFilterList () {\n+ var filters = []\n+ while (!eof()) {\n+ filters.push(parseFilter())\n }\n- lastFilterIndex = i + 1\n+ return filters\n+}\n+\n+function parseFilter () {\n+ var filter = {}\n+ var args\n+\n+ state = filterState\n+ filter.name = parseExpression().trim()\n+\n+ state = filterArgState\n+ args = parseFilterArguments()\n+\n+ if (args.length) {\n+ filter.args = args\n+ }\n+ return filter\n+}\n+\n+function parseFilterArguments () {\n+ var args = []\n+ while (!eof() && state !== filterState) {\n+ var arg = parseExpression()\n+ if (!arg) {\n+ break\n+ }\n+ args.push(processFilterArg(arg))\n+ }\n+\n+ return args\n }\n \n /**\n@@ -83,51 +220,22 @@ export function parseDirective (s) {\n \n // reset parser state\n str = s\n- inSingle = inDouble = false\n- curly = square = paren = 0\n- lastFilterIndex = 0\n dir = {}\n+ len = str.length\n+ index = -1\n+ chr = ''\n+ state = startState\n \n- for (i = 0, l = str.length; i < l; i++) {\n- prev = c\n- c = str.charCodeAt(i)\n- if (inSingle) {\n- // check single quote\n- if (c === 0x27 && prev !== 0x5C) inSingle = !inSingle\n- } else if (inDouble) {\n- // check double quote\n- if (c === 0x22 && prev !== 0x5C) inDouble = !inDouble\n- } else if (\n- c === 0x7C && // pipe\n- str.charCodeAt(i + 1) !== 0x7C &&\n- str.charCodeAt(i - 1) !== 0x7C\n- ) {\n- if (dir.expression == null) {\n- // first filter, end of expression\n- lastFilterIndex = i + 1\n- dir.expression = str.slice(0, i).trim()\n- } else {\n- // already has filter\n- pushFilter()\n- }\n- } else {\n- switch (c) {\n- case 0x22: inDouble = true; break // \"\n- case 0x27: inSingle = true; break // '\n- case 0x28: paren++; break // (\n- case 0x29: paren--; break // )\n- case 0x5B: square++; break // [\n- case 0x5D: square--; break // ]\n- case 0x7B: curly++; break // {\n- case 0x7D: curly--; break // }\n- }\n- }\n- }\n+ var filters\n \n- if (dir.expression == null) {\n- dir.expression = str.slice(0, i).trim()\n- } else if (lastFilterIndex !== 0) {\n- pushFilter()\n+ if (str.indexOf('|') < 0) {\n+ dir.expression = str.trim()\n+ } else {\n+ dir.expression = parseExpression().trim()\n+ filters = parseFilterList()\n+ if (filters.length) {\n+ dir.filters = filters\n+ }\n }\n \n cache.put(s, dir)",
"filename": "src/parsers/directive.js",
"status": "modified"
},
{
"diff": "@@ -85,6 +85,32 @@ describe('Directive Parser', function () {\n expect(res.filters[0].args).toBeUndefined()\n })\n \n+ it('white spaces inside object literal', function () {\n+ var res = parse('abc | filter {a:1} {b: 2}')\n+ expect(res.expression).toBe('abc')\n+ expect(res.filters.length).toBe(1)\n+ expect(res.filters[0].name).toBe('filter')\n+ expect(res.filters[0].args.length).toBe(2)\n+ expect(res.filters[0].args[0].value).toBe('{a:1}')\n+ expect(res.filters[0].args[0].dynamic).toBe(true)\n+ expect(res.filters[0].args[1].value).toBe('{b: 2}')\n+ expect(res.filters[0].args[1].dynamic).toBe(true)\n+ })\n+\n+ it('white spaces inside array literal', function () {\n+ var res = parse('abc | filter0 abc||def | filter1 [ 1, { a: 2 }]')\n+ expect(res.expression).toBe('abc')\n+ expect(res.filters.length).toBe(2)\n+ expect(res.filters[0].name).toBe('filter0')\n+ expect(res.filters[0].args.length).toBe(1)\n+ expect(res.filters[0].args[0].value).toBe('abc||def')\n+ expect(res.filters[0].args[0].dynamic).toBe(true)\n+ expect(res.filters[1].name).toBe('filter1')\n+ expect(res.filters[1].args.length).toBe(1)\n+ expect(res.filters[1].args[0].value).toBe('[ 1, { a: 2 }]')\n+ expect(res.filters[1].args[0].dynamic).toBe(true)\n+ })\n+\n it('cache', function () {\n var res1 = parse('a || b | c')\n var res2 = parse('a || b | c')",
"filename": "test/unit/specs/parsers/directive_spec.js",
"status": "modified"
}
]
} |
{
"body": "As demonstrated in [this fiddle](https://jsfiddle.net/chrisvfritz/dtvcthkh/), the following is interpreted literally:\n\n``` html\n<p>{{{ '<strong>hello</strong> world' }}}</p>\n```\n\nInstead, I would expect it to produce:\n\n``` html\n<p><strong>hello</strong> world</p>\n```\n\nThis also occurs with normal interpolation (`{{ }}`).\n",
"comments": [
{
"body": "I created a failing test for it https://github.com/Grafikart/vue/blob/fix-html-interpolation/test/unit/specs/compiler/compile_spec.js#L719 \n\nI try to look at the source to find where it comes from \n",
"created_at": "2016-08-20T01:26:40Z"
},
{
"body": "I'm working on a fix\n\n## First idea\n\nThis solution is pretty dirty but I see no way around. I need to edit the compileNode method to add a new Condition. \nI check if I find a text childNode containing an opening delimiter. If I encounter such a case every Node (until the next text childNode containing a closing delimiter) should be treated as text. \n",
"created_at": "2016-08-20T02:27:20Z"
},
{
"body": "Hi\n\nI am not entirely convinced this should be considered a bug.\nAccording to the [docs](https://vuejs.org/guide/syntax.html#Interpolations): The mustache tag will be replaced with the value of the msg property on the corresponding data object.\nIn your example there is no data object.\n\nTo be able to get an error message I modified your example from\n\n```\n<p>{{{ '<strong>hello</strong> world' }}}</p>\n```\n\nto\n\n```\n<p v-html=\"<strong>hello</strong> world\"></p>\n```\n\nas the [docs](https://vuejs.org/api/#v-html) state the triple curly braces will ultimately be compiled as v-html directive.\nThen you can see in the console the following warning:\n\n> [Vue warn]: Invalid expression. Generated function body: `<scope.strong>scope.hello</scope.strong>scope.world`\n\nWhat is happening here is vue is looking for the properties on the data object but cannot find them because they are not there.\nHere is a working example: https://jsfiddle.net/bsyxkxy2/\n",
"created_at": "2016-09-10T09:13:35Z"
},
{
"body": "@Bilie Your example isn't quite right.\n\n``` html\n<p>{{{ '<strong>hello</strong> world' }}}</p>\n```\n\nactually compiles to:\n\n``` html\n<p v-html=\"'<strong>hello</strong> world'\"></p>\n```\n\n(Note the single quotes.) And as you can [see here](https://jsfiddle.net/chrisvfritz/nh5vkqav/), the `v-html` version works fine while the interpolated version fails. So it is indeed a bug.\n",
"created_at": "2016-09-25T19:52:12Z"
},
{
"body": "@chrisvfritz Since Vue utilizes the Object.defineProperty to convert instance data to observed object, inline expression without instance data would not be compiled at all. So this is not a bug to me too. And I suspect anyone would do inline expression interpolation like this for a good reason.",
"created_at": "2017-01-19T10:00:18Z"
},
{
"body": "@chrisvfritz> I agree that the issue is a bug and I'd like to share my findings after a few initial debugging sessions with `Vue.js v2.1.10`. This version seems to only handle double, not triple, curly braces, so I used double curly braces for testing. (Does Vue support triple curly braces at all?) Vue called a vendor function, `parseHTML`, to parse the entire template below as a whole string of HTML code.\r\n```html\r\n<div id=\"demo\">\r\n <p>{{ '<strong>hello</strong> world' }}</p>\r\n</div>\r\n```\r\nThe specific paragraph in question was parsed as:\r\n```html\r\n1. Start tag: <p>\r\n2. Text: {{ ' /* {{ was further parsed by function parseText as plain text */\r\n3. Start tag: <strong>\r\n4. Text: hello\r\n5. End tag: </strong>\r\n6. Text: world' }} /* }} was parsed by parseText as plain text */\r\n7. End tag: </p>\r\n```\r\nI changed the paragraph to the following and got the correct result:\r\n```html\r\n <p>{{ 'hello world' }}</p>\r\n```\r\nWhy? Because it was parsed as the following:\r\n```html\r\n1. Start tag: <p>\r\n2. Text: {{ 'hello world' }}\r\n /* Function parseText found a Vue construct with pattern: /\\{\\{((?:.|\\n)+?)\\}\\}/g */\r\n3. End tag: </p>\r\n```\r\nAs `function parseHTML` is vendor code, I wonder whether and how we should change the template parsing algorithm to fix this. By the way, triple curly braces were parsed as plain text in this case:\r\n```html\r\n <p>{{{ '<strong>hello</strong> world' }}}</p>\r\n```\r\nThey were parsed as `object { 'hello world' }` being wrapped up by double curly braces in the following case:\r\n```html\r\n <p>{{{ 'hello world' }}}</p>\r\n```\r\n\r\n\r\n",
"created_at": "2017-02-25T18:06:37Z"
},
{
"body": "@zrw354 Thanks for sharing your research. HTML interpolation has indeed [been removed](https://vuejs.org/v2/guide/migration.html#HTML-Interpolation-removed).",
"created_at": "2017-02-25T18:44:46Z"
},
{
"body": "I think this is not a bug, but rather an html quirk.\r\n\r\nFirst see this demo: https://jsfiddle.net/simplesmiler/14dtfh51/14/. Note, that raw and encoded code have the same effect when used in the attribute, but different effect when used in the body.\r\n\r\n\r\n\r\nSo the fact that `v-text=\"'<strong>hello</strong>'\"` works is an html quirk, where html tolerates (and even promotes) non-encoded attributes.\r\n\r\nWhen written \"properly\", it would be `v-text=\"'<strong>hello</strong>'\"`,\r\nwhich maps to `{{ '<strong>hello</strong>' }}` and works exactly as you would expect.",
"created_at": "2017-02-26T09:16:59Z"
},
{
"body": "Closing 1.x issues as 1.x is now end of life and will only receive critical security patches.",
"created_at": "2018-04-17T21:38:26Z"
}
],
"number": 3323,
"title": "Interpolation fails on inline string containing HTML"
} | {
"body": "Partial Fix for issue #3323 \n\nThis fix allow `<p>{{ '<strong>hello</strong> world' }}</p>`\nbut `<p>{{{ '<strong>hello</strong> world' }}}</p>` won't work due to the way the compiler works :(. It would force a lots of changes for an edge case.\n",
"number": 3489,
"review_comments": [],
"title": "Fix html interpolation"
} | {
"commits": [
{
"message": "Make test fails"
},
{
"message": "Fix HTML interpolation"
},
{
"message": "Fix linting problems"
},
{
"message": "Fix regression"
},
{
"message": "=== instead of =="
}
],
"files": [
{
"diff": "@@ -4,6 +4,7 @@ import { compileProps } from './compile-props'\n import { parseText, tokensToExp } from '../parsers/text'\n import { parseDirective } from '../parsers/directive'\n import { parseTemplate } from '../parsers/template'\n+import config from '../config'\n import {\n _toString,\n resolveAsset,\n@@ -492,6 +493,7 @@ function makeTextNodeLinkFn (tokens, frag) {\n function compileNodeList (nodeList, options) {\n var linkFns = []\n var nodeLinkFn, childLinkFn, node\n+ flatifyNodeList(nodeList)\n for (var i = 0, l = nodeList.length; i < l; i++) {\n node = nodeList[i]\n nodeLinkFn = compileNode(node, options)\n@@ -844,6 +846,70 @@ function hasOneTime (tokens) {\n }\n }\n \n+/**\n+ * Check if an interpolation string contains one-time tokens.\n+ *\n+ * @param {Element} node\n+ * @return {Boolean}\n+ */\n+\n+function flatifyNodeList (nodeList) {\n+ var openingDelimiterNode = false\n+ for (var i = 0, l = nodeList.length; i < l; i++) {\n+ var node = nodeList[i]\n+ if (openingDelimiterNode && node.nodeType === 1) {\n+ node.parentNode.replaceChild(document.createTextNode(node.outerHTML), node)\n+ } else if (openingDelimiterNode && node.nodeType === 3 && containsClosingDelimiter(node)) {\n+ openingDelimiterNode = false\n+ } else {\n+ node = nodeList[i]\n+ if (containsOpeningDelimiter(node)) {\n+ openingDelimiterNode = node\n+ }\n+ }\n+ }\n+}\n+\n+/**\n+ * Check if a node contains a starting delimiter\n+ *\n+ * @param {Element} node\n+ * @return {Boolean}\n+ */\n+\n+function containsOpeningDelimiter (node) {\n+ var openingRe = new RegExp(config.delimiters[0] + '|' + config.unsafeDelimiters[0], 'g')\n+ var endingRe = new RegExp(config.delimiters[1] + '|' + config.unsafeDelimiters[1], 'g')\n+ if (node && node.nodeType === 3) {\n+ var openingMatches = node.textContent.match(openingRe)\n+ var endingMatches = node.textContent.match(endingRe)\n+ if (!openingMatches) openingMatches = []\n+ if (!endingMatches) endingMatches = []\n+ return openingMatches.length > endingMatches.length\n+ }\n+ return false\n+}\n+\n+/**\n+ * Check if a node contains an ending delimiter\n+ *\n+ * @param {Element} node\n+ * @return {Boolean}\n+ */\n+\n+function containsClosingDelimiter (node) {\n+ var openingRe = new RegExp(config.delimiters[0] + '|' + config.unsafeDelimiters[0], 'g')\n+ var endingRe = new RegExp(config.delimiters[1] + '|' + config.unsafeDelimiters[1], 'g')\n+ if (node && node.nodeType === 3) {\n+ var openingMatches = node.textContent.match(openingRe)\n+ var endingMatches = node.textContent.match(endingRe)\n+ if (!openingMatches) openingMatches = []\n+ if (!endingMatches) endingMatches = []\n+ return openingMatches.length < endingMatches.length\n+ }\n+ return false\n+}\n+\n function isScript (el) {\n return el.tagName === 'SCRIPT' && (\n !el.hasAttribute('type') ||",
"filename": "src/compiler/compile.js",
"status": "modified"
},
{
"diff": "@@ -715,4 +715,16 @@ describe('Compile', function () {\n done()\n })\n })\n+\n+ it('should interpolate string with html', function (done) {\n+ /* disable no-new */\n+ new Vue({\n+ el: el,\n+ template: \"<div>{{ '<strong>hello</strong> world' }}</div>\"\n+ })\n+ _.nextTick(function () {\n+ expect(el.textContent).toBe('<strong>hello</strong> world')\n+ done()\n+ })\n+ })\n })",
"filename": "test/unit/specs/compiler/compile_spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\n\n1.0.26\n### Reproduction Link\n\nhttp://codepen.io/sirlancelot/pen/zBPVBo?editors=1010#0\n### Steps to reproduce\n- Bind an inline object with a value containing the backtick character\n### What is Expected?\n- Object is reproduced properly in the data model\n### What is actually happening?\n- `scope.` is being added to everything between the backtick and an escaped quote.\n\nWe're using props to curry an initial data model from the server to the browser. We're doing it in a manner similar to the example shown in the CodePen. Basically, our root Vue instance contains a list of props that will show up on the element and are populated by the server.\n",
"comments": [
{
"body": "As a temporary workaround, you can bypass the issue by escaping the backtick.\n\n```\n//broken\n:items=\"[{'title':'one','value':1},{'title':'t`wo','value':2}]\"\n\n//works\n:items=\"[{'title':'one','value':1},{'title':'t\\`wo','value':2}]\"\n```\n\nFor anyone investigating, it seems that the issue doesn't occur when the array contains only a single element.\n",
"created_at": "2016-07-14T12:50:10Z"
},
{
"body": "I made a change to a regular expression and this seems to be working fine now. However this seemed like a very important regexp and I am not sure of the patch.\n\n### Before\n\n\n\n### After\n\n(I've highlighted the part in red)\n\n\n",
"created_at": "2016-07-19T17:18:23Z"
},
{
"body": "@skyronic what RegExp tool is that? looks very useful...\n",
"created_at": "2016-07-22T19:04:22Z"
},
{
"body": "@LinusBorg - I used https://www.debuggex.com/ very handy!\n",
"created_at": "2016-07-22T19:26:38Z"
},
{
"body": "@skyronic thx! I use http://rubular.com/ a lot. It tests with the ruby lib but works fine too.\n",
"created_at": "2016-09-27T09:11:37Z"
}
],
"number": 3273,
"title": "Bad parsing when bound data contains a backtick"
} | {
"body": "This fixes #3273 but might introduce other bugs. I'm not sure of it.\n",
"number": 3292,
"review_comments": [
{
"body": "There's a stray \"|\" which should be removed here I guess.\n",
"created_at": "2016-07-19T17:19:04Z"
}
],
"title": "Handle back-ticks in expression"
} | {
"commits": [
{
"message": "Handle back-ticks in expression"
}
],
"files": [
{
"diff": "@@ -23,7 +23,7 @@ const improperKeywordsRE =\n \n const wsRE = /\\s/g\n const newlineRE = /\\n/g\n-const saveRE = /[\\{,]\\s*[\\w\\$_]+\\s*:|('(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|`(?:[^`\\\\]|\\\\.)*\\$\\{|\\}(?:[^`\\\\]|\\\\.)*`|`(?:[^`\\\\]|\\\\.)*`)|new |typeof |void /g\n+const saveRE = /[\\{,]\\s*[\\w\\$_]+\\s*:|('(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|`(?:[^`\\\\]|\\\\.)*\\$\\{|\\}(?:[^`\\\\\"']|\\\\.)*`|`(?:[^`\\\\]|\\\\.)*`)|new |typeof |void /g\n const restoreRE = /\"(\\d+)\"/g\n const pathTestRE = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*|\\['.*?'\\]|\\[\".*?\"\\]|\\[\\d+\\]|\\[[A-Za-z_$][\\w$]*\\])*$/\n const identRE = /[^\\w$\\.](?:[A-Za-z_$][\\w$]*)/g",
"filename": "src/parsers/expression.js",
"status": "modified"
},
{
"diff": "@@ -67,6 +67,18 @@ var testCases = [\n scope: {c: 32},\n expected: { a: '35', b: 32 }\n },\n+ {\n+ // Object with string values with back-quotes\n+ exp: '[{\"a\":\"he`llo\"},{\"b\":\"world\"},{\"c\":55}]',\n+ scope: {},\n+ expected: [{ 'a': 'he`llo'}, { 'b': 'world'}, { 'c': 55}]\n+ },\n+ {\n+ // Object with string values and back quotes (single quoted string)\n+ exp: '[{\\'a\\':\\'he`llo\\'},{\\'b\\':\\'world\\'},{\\'c\\':55}]',\n+ scope: {},\n+ expected: [{ 'a': 'he`llo'}, { 'b': 'world'}, { 'c': 55}]\n+ },\n {\n // dollar signs and underscore\n exp: \"_a + ' ' + $b\",",
"filename": "test/unit/specs/parsers/expression_spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\n\n1.0.26\n### Reproduction Link\n\nhttp://jsfiddle.net/e2zfe3se/\n### Steps to reproduce\n\nCheck the above example\n### What is Expected?\n\nThe $ref object should be updated using the new sub components instances\n### What is actually happening?\n\nThe $ref object caches the old components instances and all the references to the new DOM elements created get lost\n",
"comments": [
{
"body": "After some digging it happens during the unbuild process. It is called with defer of undefined. If the refs are unbound with deferred true, it stops that from happening.\n",
"created_at": "2016-07-02T03:37:51Z"
},
{
"body": "can you share the location of the problem in src?\n",
"created_at": "2016-07-02T08:50:50Z"
},
{
"body": "Sorry, not sure why I didn't before. src/directives/internal/component.js, line 287 \"child.$destroy(false, defer)\".\n",
"created_at": "2016-07-02T20:03:56Z"
},
{
"body": "Close (Fixed in #3217)\n",
"created_at": "2016-07-06T00:09:45Z"
}
],
"number": 3204,
"title": "$refs in loops are not in sync - the sub components instances do not get updated"
} | {
"body": "ref: #3204\n",
"number": 3217,
"review_comments": [],
"title": "fix $refs updating"
} | {
"commits": [
{
"message": "fix $refs updateing\n\nref: #3204"
}
],
"files": [
{
"diff": "@@ -665,8 +665,8 @@ function makeTerminalNodeLinkFn (el, dirName, value, options, def, rawName, arg,\n modifiers: modifiers,\n def: def\n }\n- // check ref for v-for and router-view\n- if (dirName === 'for' || dirName === 'router-view') {\n+ // check ref for v-for, v-if and router-view\n+ if (dirName === 'for' || dirName === 'if' || dirName === 'router-view') {\n descriptor.ref = findRef(el)\n }\n var fn = function terminalNodeLinkFn (vm, el, host, scope, frag) {",
"filename": "src/compiler/compile.js",
"status": "modified"
},
{
"diff": "@@ -16,7 +16,8 @@ import {\n def,\n cancellable,\n isArray,\n- isPlainObject\n+ isPlainObject,\n+ findVmFromFrag\n } from '../../util/index'\n \n let uid = 0\n@@ -602,24 +603,6 @@ function findPrevFrag (frag, anchor, id) {\n return frag\n }\n \n-/**\n- * Find a vm from a fragment.\n- *\n- * @param {Fragment} frag\n- * @return {Vue|undefined}\n- */\n-\n-function findVmFromFrag (frag) {\n- let node = frag.node\n- // handle multi-node frag\n- if (frag.end) {\n- while (!node.__vue__ && node !== frag.end && node.nextSibling) {\n- node = node.nextSibling\n- }\n- }\n- return node.__vue__\n-}\n-\n /**\n * Create a range array from given number.\n *",
"filename": "src/directives/public/for.js",
"status": "modified"
},
{
"diff": "@@ -5,7 +5,8 @@ import {\n remove,\n replace,\n createAnchor,\n- warn\n+ warn,\n+ findVmFromFrag\n } from '../../util/index'\n \n export default {\n@@ -40,8 +41,10 @@ export default {\n if (value) {\n if (!this.frag) {\n this.insert()\n+ this.updateRef(value)\n }\n } else {\n+ this.updateRef(value)\n this.remove()\n }\n },\n@@ -76,6 +79,29 @@ export default {\n }\n },\n \n+ updateRef (value) {\n+ var ref = this.descriptor.ref\n+ if (!ref) return\n+ var hash = (this.vm || this._scope).$refs\n+ var refs = hash[ref]\n+ var key = this._frag.scope.$key\n+ if (!refs) return\n+ if (value) {\n+ if (Array.isArray(refs)) {\n+ refs.push(findVmFromFrag(this._frag))\n+ } else {\n+ refs[key] = findVmFromFrag(this._frag)\n+ }\n+ } else {\n+ if (Array.isArray(refs)) {\n+ refs.$remove(findVmFromFrag(this._frag))\n+ } else {\n+ refs[key] = null\n+ delete refs[key]\n+ }\n+ }\n+ },\n+\n unbind () {\n if (this.frag) {\n this.frag.destroy()",
"filename": "src/directives/public/if.js",
"status": "modified"
},
{
"diff": "@@ -449,3 +449,21 @@ export function getOuterHTML (el) {\n return container.innerHTML\n }\n }\n+\n+/**\n+ * Find a vm from a fragment.\n+ *\n+ * @param {Fragment} frag\n+ * @return {Vue|undefined}\n+ */\n+\n+export function findVmFromFrag (frag) {\n+ let node = frag.node\n+ // handle multi-node frag\n+ if (frag.end) {\n+ while (!node.__vue__ && node !== frag.end && node.nextSibling) {\n+ node = node.nextSibling\n+ }\n+ }\n+ return node.__vue__\n+}",
"filename": "src/util/dom.js",
"status": "modified"
},
{
"diff": "@@ -432,4 +432,77 @@ describe('v-if', function () {\n done()\n })\n })\n+\n+ // GitHub issue #3204\n+ it('update array refs', function (done) {\n+ var vm = new Vue({\n+ el: el,\n+ template: '<foo v-if=\"!activeItem || $index === activeItem\" v-ref:foo :index=\"$index\" v-for=\"item in items\"></foo>',\n+ data: {\n+ items: [0, 1, 2],\n+ activeItem: null\n+ },\n+ components: {\n+ foo: {\n+ props: ['index'],\n+ template: '<div>I am foo ({{ index }})<div>'\n+ }\n+ }\n+ })\n+ vm.$refs.foo.forEach(function (ref, index) {\n+ expect(ref.$el.textContent).toBe('I am foo (' + index + ')')\n+ expect(ref.index).toBe(index)\n+ })\n+ vm.activeItem = 1 // select active item\n+ nextTick(function () {\n+ expect(vm.$refs.foo.length).toBe(1)\n+ expect(vm.$refs.foo[0].index).toBe(1)\n+ vm.activeItem = null // enable all elements\n+ nextTick(function () {\n+ expect(vm.$refs.foo.length).toBe(3)\n+ done()\n+ })\n+ })\n+ })\n+\n+ it('update object refs', function (done) {\n+ var vm = new Vue({\n+ el: el,\n+ template: '<foo v-if=\"!activeKey || $key === activeKey\" v-ref:foo :key=\"$key\" v-for=\"item in items\"></foo>',\n+ data: {\n+ items: {\n+ a: 1,\n+ b: 2,\n+ c: 3\n+ },\n+ activeKey: null\n+ },\n+ components: {\n+ foo: {\n+ props: ['key'],\n+ template: '<div>I am foo ({{ key }})<div>'\n+ }\n+ }\n+ })\n+ Object.keys(vm.$refs.foo).forEach(function (key) {\n+ var ref = vm.$refs.foo[key]\n+ expect(ref.$el.textContent).toBe('I am foo (' + key + ')')\n+ expect(ref.key).toBe(key)\n+ })\n+ vm.activeKey = 'b' // select active item\n+ nextTick(function () {\n+ expect(Object.keys(vm.$refs.foo).length).toBe(1)\n+ expect(vm.$refs.foo['b'].key).toBe('b')\n+ vm.activeKey = null // enable all elements\n+ nextTick(function () {\n+ expect(Object.keys(vm.$refs.foo).length).toBe(3)\n+ Object.keys(vm.$refs.foo).forEach(function (key) {\n+ var ref = vm.$refs.foo[key]\n+ expect(ref.$el.textContent).toBe('I am foo (' + key + ')')\n+ expect(ref.key).toBe(key)\n+ })\n+ done()\n+ })\n+ })\n+ })\n })",
"filename": "test/unit/specs/directives/public/if_spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\n\n1.0.26\n### Reproduction Link\n\nhttps://jsfiddle.net/simplesmiler/Lrk9sxjf/102/\n### What is Expected?\n\nBoth textareas having text inside them.\n### What is actually happening?\n\nFirst textarea has text. Second textarea is empty, and has literal attribute `:value`.\n",
"comments": [],
"number": 3184,
"title": "v-pre on textarea breaks sometimes"
} | {
"body": "skip compile before process it's :value when a textarea has v-pre attr\nFixed #3184 \n",
"number": 3202,
"review_comments": [],
"title": "textarea with v-pre attr should skip compile"
} | {
"commits": [
{
"message": "textarea with v-pre should skip compile"
}
],
"files": [
{
"diff": "@@ -326,6 +326,10 @@ function compileElement (el, options) {\n // textarea treats its text content as the initial value.\n // just bind it as an attr directive for value.\n if (el.tagName === 'TEXTAREA') {\n+ // a textarea which has v-pre attr should skip complie.\n+ if (getAttr(el, 'v-pre') !== null) {\n+ return skip\n+ }\n var tokens = parseText(el.value)\n if (tokens) {\n el.setAttribute(':value', tokensToExp(tokens))",
"filename": "src/compiler/compile.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\n\n1.0.24\n### Reproduction Link\n\nhttps://github.com/kucherenkovova/piano/tree/BUG-report-vue\ngo to demo folder and open index.html\n### Steps to reproduce\n\nInput something into the `Email layout` input field.\nPut the cursor in the middle of your text.\nHit backspace on the virtual keyboard.\n### What is Expected?\n\nThe text will be removed in the cursor position.\n### What is actually happening?\n\nThe text removes from the end of the string. `selectionStart` attribute is changed somehow by Vue.js \n\nP.S. You can test it on other input elements which do not have `v-model` on it.Everything will work well.\n",
"comments": [
{
"body": "Hello!\n\nThanks for filing the issue 😄 . Please follow the [Issue Reporting Guidelines](https://github.com/vuejs/vue/blob/dev/CONTRIBUTING.md#issue-reporting-guidelines) and provide a minimal JSFiddle or JSBin containing a set of reproducible steps that can lead to the behaviour you described.\n\nI cloned your repo and tested it on chrome, it works well. Next time provide a simple repro. People can't go through your whole application to help...\n",
"created_at": "2016-06-04T10:28:29Z"
},
{
"body": "Thanks for the feedback. I'll provide a gh-pages link soon. It's impossible to reproduce the bug on the codepen or jsfiddle due to Piano.js nature.\n",
"created_at": "2016-06-06T09:13:42Z"
},
{
"body": "I see, in that case it may be due to Piano.js. It'd be great if you can create a repro without pianojs 👍 \n",
"created_at": "2016-06-06T20:42:51Z"
},
{
"body": "@posva Hi again! Here's a [codepen with repro](http://codepen.io/kucherenkovova/pen/qNONPG?editors=1010)\nSteps to reproduce:\n1. Insert text into first input\n2. Select some text\n3. Click a button near your input\n\nLooking forward for your response!\n",
"created_at": "2016-06-06T21:21:09Z"
},
{
"body": "Thanks! I found the bug. The update resets those values so caching them [here](https://github.com/vuejs/vue/blob/dev/src/directives/public/model/text.js#L74) and taking them back [there](https://github.com/vuejs/vue/blob/dev/src/directives/public/model/text.js#L77) actually solves the issue. I'm not sure about how to test this though. I may have to write an e2e test\n\nPS: I'm doing this tomorrow, going to sleep 😴 \n",
"created_at": "2016-06-06T22:12:39Z"
},
{
"body": "I didn't had internet yesterday 😢 I hope being able to do it this evening\n",
"created_at": "2016-06-08T10:45:08Z"
},
{
"body": "Finally got internet back. I'm having some trouble creating a test that breaks as a unit test. I'll try again today with an e2e test although it's a by overkill. Calling the blur method on the input doesn't behave the same way as actually doing.\nThe fix I came up with is not setting the input value if it hasn't changed at blur. It's basically adding `_toString(self._watcher.value) !== el.value` to the conditions [here](https://github.com/vuejs/vue/blob/dev/src/directives/public/model/text.js#L75)\n",
"created_at": "2016-06-10T06:53:58Z"
}
],
"number": 3029,
"title": "v-model breaks selectionStart"
} | {
"body": "Fix #3029\nForce setting the value actually resets selectionStart and selectionEnd\nNo test is added because you cannot simulate the bug by using\ninput.blur()\n",
"number": 3077,
"review_comments": [],
"title": "Prevent setting unchanged value of input on blur"
} | {
"commits": [
{
"message": "Prevent setting unchanged value of input on blur\n\nFix #3029\nForce setting the value actually resets selectionStart and selectionEnd\nNo test is added because you cannot simulate the bug by using\ninput.blur()"
}
],
"files": [
{
"diff": "@@ -129,7 +129,10 @@ export default {\n },\n \n update (value) {\n- this.el.value = _toString(value)\n+ // #3029 only update when the value changes. This prevent\n+ // browsers from overwriting values like selectionStart\n+ value = _toString(value)\n+ if (value !== this.el.value) this.el.value = value\n },\n \n unbind () {",
"filename": "src/directives/public/model/text.js",
"status": "modified"
}
]
} |
{
"body": "<!-- BUG REPORT TEMPLATE -->\n### Vue.js version\n\n> = 1.0.18 (any version i think)\n### Reproduction Link\n\nhttp://www.webpackbin.com/VyoNXXrXb\n### What is Expected?\n\nIf dynamically binded transition is updated, and previous transition was vue default, v-transition class should be removed.\n### What is actually happening?\n\nCheck the example. If we change transition from default, v-transition class is not being removed. But when we have some custom transition on start e.g. slide and we change it to fade then slide-transition class is properly removed.\n",
"comments": [
{
"body": "it seems the default value `transition: ''` causes the problem\nwhen i set transition: 'xxxx'(xxxx is anthing) ,the `v-transition` had been removed normally\n\nhttp://www.webpackbin.com/V1m34Dq7Z\n",
"created_at": "2016-06-03T12:20:13Z"
},
{
"body": "Let me take a look 😄 \n",
"created_at": "2016-06-04T09:43:15Z"
}
],
"number": 2972,
"title": "Default v-transition class is not being removed after transition is updated"
} | {
"body": "Fix #2972\n\nAt first I added this test too since manually updating the directive may differ from real updates but then I realised it must be already tested on binding tests so I removed it.\n\n``` javascript\n it('removes v-transition on dynamic transition', function (done) {\n var el = document.createElement('div')\n document.body.appendChild(el)\n var vm = new Vue({\n el: el,\n template: '<div :transition=\"trans\"></div>',\n data: {\n trans: null\n },\n replace: true\n })\n\n _.nextTick(function () {\n expect(vm.$el.className).toBe('v-transition')\n vm.trans = 'a'\n _.nextTick(function () {\n expect(vm.$el.className).toBe('a-transition')\n done()\n })\n })\n })\n```\n",
"number": 3033,
"review_comments": [],
"title": "Fix missing removal of v-transition class"
} | {
"commits": [
{
"message": "Fix missing removal of v-transition class\n\nFix #2972"
}
],
"files": [
{
"diff": "@@ -11,6 +11,7 @@ export default {\n // resolve on owner vm\n var hooks = resolveAsset(this.vm.$options, 'transitions', id)\n id = id || 'v'\n+ oldId = oldId || 'v'\n el.__v_trans = new Transition(el, id, hooks, this.vm)\n if (oldId) {\n removeClass(el, oldId + '-transition')",
"filename": "src/directives/internal/transition.js",
"status": "modified"
},
{
"diff": "@@ -14,25 +14,30 @@ describe('transition', function () {\n })\n var dir = new Directive({\n name: 'transition',\n- raw: 'test',\n+ raw: '',\n def: def,\n modifiers: {\n literal: true\n }\n }, vm, el)\n dir._bind()\n var transition = dir.el.__v_trans\n+ expect(transition.enterClass).toBe('v-enter')\n+ expect(transition.leaveClass).toBe('v-leave')\n+ expect(dir.el.className).toBe('v-transition')\n+ dir.update('test', '')\n+ transition = dir.el.__v_trans\n expect(transition.el).toBe(dir.el)\n expect(transition.hooks).toBe(fns)\n expect(transition.enterClass).toBe('test-enter')\n expect(transition.leaveClass).toBe('test-leave')\n- expect(dir.el.className === 'test-transition')\n+ expect(dir.el.className).toBe('test-transition')\n dir.update('lol', 'test')\n transition = dir.el.__v_trans\n expect(transition.enterClass).toBe('lol-enter')\n expect(transition.leaveClass).toBe('lol-leave')\n expect(transition.fns).toBeUndefined()\n- expect(dir.el.className === 'lol-transition')\n+ expect(dir.el.className).toBe('lol-transition')\n })\n \n it('dynamic transitions', function (done) {",
"filename": "test/unit/specs/directives/internal/transition_spec.js",
"status": "modified"
}
]
} |
{
"body": "### Vue.js version\n\n1.0.24\n### Reproduction Link\n\n<!-- A minimal JSBin, JSFiddle, Codepen, or a GitHub reprository that can reproduce the bug. -->\n### Steps to reproduce\n\n``` js\nnew Vue({\n data: {\n person: {\n name: 'Felix',\n },\n },\n});\n```\n\n``` html\n<pre>{{ person | json 0 }}</pre>\n```\n### What is Expected?\n\n``` js\n{\"name\":\"Felix\"}\n```\n### What is actually happening?\n\n``` js\n{\n \"name\": \"Felix\"\n}\n```\n",
"comments": [
{
"body": "~~FYI 0 indent level should lead to: `wrong code`~~\n\nFixing it, thanks for reporting it 😄 \n",
"created_at": "2016-05-17T15:18:04Z"
}
],
"number": 2888,
"title": "The \"json\" filter not support to use \"0\" as parameter"
} | {
"body": "Fix #2888\n",
"number": 2890,
"review_comments": [],
"title": "Fix json filter call with 0 as a parameter"
} | {
"commits": [
{
"message": "Fix json filter call with 0 as a parameter\n\nFix #2888"
}
],
"files": [
{
"diff": "@@ -19,7 +19,7 @@ export default {\n read: function (value, indent) {\n return typeof value === 'string'\n ? value\n- : JSON.stringify(value, null, Number(indent) || 2)\n+ : JSON.stringify(value, null, arguments.length > 1 ? indent : 2)\n },\n write: function (value) {\n try {",
"filename": "src/filters/index.js",
"status": "modified"
},
{
"diff": "@@ -6,6 +6,7 @@ describe('Filters', function () {\n var obj = {a: {b: 2}}\n expect(filter(obj)).toBe(JSON.stringify(obj, null, 2))\n expect(filter(obj, 4)).toBe(JSON.stringify(obj, null, 4))\n+ expect(filter(obj, 0)).toBe(JSON.stringify(obj, null, 0))\n // plain string\n expect(filter('1234')).toBe('1234')\n })",
"filename": "test/unit/specs/filters/filters_spec.js",
"status": "modified"
}
]
} |
{
"body": "The build randomly fails due to Thread-local Storage test failure. See the log below:\n\n```\n[INFO] -------------------------------------------------------\n[INFO] T E S T S\n[INFO] -------------------------------------------------------\n[INFO] Running ThreadLocalTest\nError: Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 6.086 s <<< FAILURE! -- in ThreadLocalTest\nError: ThreadLocalTest.withoutThreadLocal -- Time elapsed: 3.052 s <<< FAILURE!\norg.opentest4j.AssertionFailedError: expected: <false> but was: <true>\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)\n\tat org.junit.jupiter.api.AssertFalse.assertFalse(AssertFalse.java:40)\n\tat org.junit.jupiter.api.AssertFalse.assertFalse(AssertFalse.java:35)\n\tat org.junit.jupiter.api.Assertions.assertFalse(Assertions.java:227)\n\tat ThreadLocalTest.withoutThreadLocal(ThreadLocalTest.java:68)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\n\tat org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)\n\tat org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)\n\tat java.base/java.util.ArrayList.forEach(ArrayList.java:1511)\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)\n\tat java.base/java.util.ArrayList.forEach(ArrayList.java:1511)\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)\n\tat org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)\n\tat org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)\n\tat org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)\n\tat org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)\n\tat org.apache.maven.surefire.junitplatform.LazyLauncher.execute(LazyLauncher.java:56)\n\tat org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.execute(JUnitPlatformProvider.java:184)\n\tat org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invokeAllTests(JUnitPlatformProvider.java:148)\n\tat org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invoke(JUnitPlatformProvider.java:122)\n\tat org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:385)\n\tat org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:162)\n\tat org.apache.maven.surefire.booter.ForkedBooter.run(ForkedBooter.java:507)\n\tat org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:495)\n\n[INFO] \n[INFO] Results:\n[INFO] \nError: Failures: \nError: ThreadLocalTest.withoutThreadLocal:68 expected: <false> but was: <true>\n[INFO] \nError: Tests run: 2, Failures: 1, Errors: 0, Skipped: 0\n```\n\nAcceptance criteria\n- Flaky test fixed\n",
"comments": [],
"number": 2880,
"title": "Flaky test in Thread Local Storage"
} | {
"body": "Flaky test in Thread Local Storage #2880\r\n\r\nCreate independent threadLocal to make values unsharable and unchangable by other threads.\r\n(Not sure this change is what I supposed to change, let me know if there is something that I have to consider or change :))",
"number": 2884,
"review_comments": [],
"title": "Thread local storage test change"
} | {
"commits": [
{
"message": "Updated the imports in code of the single table inheritance pattern for Spring Boot 3.x\n\n#2825\nChange javax library to jakarta"
},
{
"message": "add pom.xml"
},
{
"message": "Updated the imports in code of the healthcheck pattern for SpringBoot 3.x\n\nChange javax library to jakarta and update maven dependency versions"
},
{
"message": "Merge branch 'iluwatar:master' into master"
},
{
"message": "change order of imports to pass Checkstyle violations"
},
{
"message": "Merge branch 'master' of https://github.com/junhkang/java-design-patterns"
},
{
"message": "change import order to pass lexicographical order test"
},
{
"message": "change import order to pass CustomImportOrder warning"
},
{
"message": "Merge branch 'iluwatar:master' into master"
},
{
"message": "Updated the maven imports of layers pattern for SpringBoot 3.2.4"
},
{
"message": "remove unused maven import"
},
{
"message": "Merge branch 'iluwatar:master' into master"
},
{
"message": "Updated the maven imports of api-gateway pattern for SpringBoot 3.2.4\n\n#2822"
},
{
"message": "Flaky test in Thread Local Storage #2880"
},
{
"message": "Rollback testing changes"
},
{
"message": "Flaky test in Thread Local Storage #2880\n\nCreate independent threadLocal to make values unsharable and unchangable by other thread"
},
{
"message": "rollback branch conflict"
}
],
"files": [
{
"diff": "@@ -57,15 +57,15 @@ public void withoutThreadLocal() throws InterruptedException {\n int threadSize = 2;\n ExecutorService executor = Executors.newFixedThreadPool(threadSize);\n \n- WithoutThreadLocal threadLocal = new WithoutThreadLocal(initialValue);\n for (int i = 0; i < threadSize; i++) {\n- executor.submit(threadLocal);\n+ //Create independent thread\n+ WithoutThreadLocal threadLocal = new WithoutThreadLocal(initialValue);\n+ executor.submit(threadLocal);\n }\n executor.awaitTermination(3, TimeUnit.SECONDS);\n-\n List<String> lines = outContent.toString().lines().toList();\n- //Matches only first thread, the second has changed by first thread value\n- Assertions.assertFalse(lines.stream()\n+\n+ Assertions.assertTrue(lines.stream()\n .allMatch(line -> line.endsWith(String.valueOf(initialValue))));\n }\n ",
"filename": "thread-local-storage/src/test/java/ThreadLocalTest.java",
"status": "modified"
}
]
} |
{
"body": "Hi, inside the README.md for the command pattern the Wizard class presents these two instance variables:\r\n```java\r\nprivate final Deque<Command> undoStack = new LinkedList<>();\r\nprivate final Deque<Command> redoStack = new LinkedList<>();\r\n```\r\n\r\nThe generic type for these deques should be ```Runnable``` as it is in the Wizard class under src directory",
"comments": [
{
"body": "can you assign me this issue?\r\n\r\nI am interest in solve this issue?",
"created_at": "2023-01-26T16:41:57Z"
},
{
"body": "I'm new to open-sourcing and I have no clue about what I should be doing. Can anyone guide me? I have basic knowledge of java \r\nlet me know in which way I can help you.",
"created_at": "2023-03-25T10:56:09Z"
},
{
"body": "@jaswanthg76 https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute",
"created_at": "2023-03-25T11:52:24Z"
},
{
"body": "Hey I can help in this issue, provide me the information of issue\r\n",
"created_at": "2023-09-09T11:16:58Z"
},
{
"body": "Hi @vatsasiddhartha, the problem has actually been solved and the fix has been merged",
"created_at": "2023-09-09T11:38:23Z"
}
],
"number": 2462,
"title": "Wrong generic type for deques in command README"
} | {
"body": "Fix deques generic type\r\n\r\n- Fix README files for command pattern\r\n- Refences to #2462\r\n\r\n\r\nDescription\r\n\r\n- Changes the generic type of deques fields in README files from 'Command' to 'Runnable' as in the source code files",
"number": 2484,
"review_comments": [],
"title": "Fix generic type for deques in command README.md files Ref: #2462"
} | {
"commits": [
{
"message": "Fix generic type for deques in command README.md files Ref: #2462"
}
],
"files": [
{
"diff": "@@ -40,8 +40,8 @@ Here's the sample code with wizard and goblin. Let's start from the `Wizard` cla\n @Slf4j\n public class Wizard {\n \n- private final Deque<Command> undoStack = new LinkedList<>();\n- private final Deque<Command> redoStack = new LinkedList<>();\n+ private final Deque<Runnable> undoStack = new LinkedList<>();\n+ private final Deque<Runnable> redoStack = new LinkedList<>();\n \n public Wizard() {}\n ",
"filename": "command/README.md",
"status": "modified"
},
{
"diff": "@@ -34,8 +34,8 @@ public class Wizard {\n \n private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class);\n \n- private final Deque<Command> undoStack = new LinkedList<>();\n- private final Deque<Command> redoStack = new LinkedList<>();\n+ private final Deque<Runnable> undoStack = new LinkedList<>();\n+ private final Deque<Runnable> redoStack = new LinkedList<>();\n \n public Wizard() {}\n ",
"filename": "localization/zh/command/README.md",
"status": "modified"
}
]
} |
{
"body": "I found some typos in javadoc.\r\nIt's such a minor things, but I want to correct them.",
"comments": [],
"number": 2428,
"title": "Typo in javadoc of event-driven-architecture"
} | {
"body": "#2428 \r\nI corrected some typos :)",
"number": 2430,
"review_comments": [],
"title": "docs: correct typos in javadoc"
} | {
"commits": [
{
"message": "fix: correct typo"
},
{
"message": "Merge branch 'master' into hotfix/docs/event-driven-architecture"
}
],
"files": [
{
"diff": "@@ -29,9 +29,9 @@\n import lombok.RequiredArgsConstructor;\n \n /**\n- * The {@link UserCreatedEvent} should should be dispatched whenever a user has been created. This\n- * class can be extended to contain details about the user has been created. In this example, the\n- * entire {@link User} object is passed on as data with the event.\n+ * The {@link UserCreatedEvent} should be dispatched whenever a user has been created.\n+ * This class can be extended to contain details about the user has been created.\n+ * In this example, the entire {@link User} object is passed on as data with the event.\n */\n @RequiredArgsConstructor\n @Getter",
"filename": "event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java",
"status": "modified"
},
{
"diff": "@@ -29,9 +29,9 @@\n import lombok.RequiredArgsConstructor;\n \n /**\n- * The {@link UserUpdatedEvent} should should be dispatched whenever a user has been updated. This\n- * class can be extended to contain details about the user has been updated. In this example, the\n- * entire {@link User} object is passed on as data with the event.\n+ * The {@link UserUpdatedEvent} should be dispatched whenever a user has been updated.\n+ * This class can be extended to contain details about the user has been updated.\n+ * In this example, the entire {@link User} object is passed on as data with the event.\n */\n @RequiredArgsConstructor\n @Getter",
"filename": "event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java",
"status": "modified"
},
{
"diff": "@@ -53,7 +53,7 @@ public <E extends Event> void registerHandler(\n }\n \n /**\n- * Dispatches an {@link Event} depending on it's type.\n+ * Dispatches an {@link Event} depending on its type.\n *\n * @param event The {@link Event} to be dispatched\n */\n@@ -65,4 +65,4 @@ public <E extends Event> void dispatch(E event) {\n }\n }\n \n-}\n\\ No newline at end of file\n+}",
"filename": "event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java",
"status": "modified"
},
{
"diff": "@@ -34,7 +34,7 @@ public interface Handler<E extends Event> {\n \n /**\n * The onEvent method should implement and handle behavior related to the event. This can be as\n- * simple as calling another service to handle the event on publishing the event on a queue to be\n+ * simple as calling another service to handle the event on publishing the event in a queue to be\n * consumed by other sub systems.\n *\n * @param event the {@link Event} object to be handled.",
"filename": "event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java",
"status": "modified"
},
{
"diff": "@@ -35,7 +35,7 @@ class AppTest {\n \n /**\n * Issue: Add at least one assertion to this test case.\n- *\n+ * <p>\n * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}\n * throws an exception.\n */",
"filename": "event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java",
"status": "modified"
}
]
} |
{
"body": "When you try to build the project using `./mvnw clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonarit` gives the following error:\r\n\r\n### Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.8.0.2131:sonar (default-cli) on project java-design-patterns: Project not found. Please check the 'sonar.projectKey' and 'sonar.organization' properties, the 'SONAR_TOKEN' environment variable, or contact the project administrator\r\n\r\nBoth in local and when you try to do the pull request. \r\n\r\nIf the project is no longer in the sonarcloud, it can be a suggestion to remove the following dependencies:\r\n\r\n```\r\n<sonar.host.url>https://sonarcloud.io</sonar.host.url>\r\n<sonar.organization>iluwatar</sonar.organization>\r\n<sonar.projectKey>iluwatar_java-design-patterns</sonar.projectKey>\r\n<sonar.moduleKey>${project.artifactId}</sonar.moduleKey>\r\n<sonar.projectName>Java Design Patterns</sonar.projectName>\r\n```\r\n\r\nand to build using: `./mvnw clean verify`\r\n\r\nIn order to continue to build the project and do pull request without building errors.",
"comments": [
{
"body": "Kind of works, see https://github.com/iluwatar/java-design-patterns/pull/2398, but maybe we can improve it",
"created_at": "2022-12-18T12:30:46Z"
}
],
"number": 2399,
"title": "Project not found. Please check the 'sonar.projectKey' and 'sonar.organization' properties"
} | {
"body": "- Closes #2399 ",
"number": 2402,
"review_comments": [],
"title": "Improve PR analysis"
} | {
"commits": [
{
"message": "separate workflow for pull_request_target"
}
],
"files": [
{
"diff": "@@ -27,7 +27,6 @@\n name: Java PR Builder\n \n on:\n- pull_request:\n pull_request_target:\n branches: [ master ]\n types: [ opened, reopened, synchronize ]",
"filename": ".github/workflows/maven-pr-builder.yml",
"status": "modified"
}
]
} |
{
"body": "When you try to build the project using `./mvnw clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonarit` gives the following error:\r\n\r\n### Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.8.0.2131:sonar (default-cli) on project java-design-patterns: Project not found. Please check the 'sonar.projectKey' and 'sonar.organization' properties, the 'SONAR_TOKEN' environment variable, or contact the project administrator\r\n\r\nBoth in local and when you try to do the pull request. \r\n\r\nIf the project is no longer in the sonarcloud, it can be a suggestion to remove the following dependencies:\r\n\r\n```\r\n<sonar.host.url>https://sonarcloud.io</sonar.host.url>\r\n<sonar.organization>iluwatar</sonar.organization>\r\n<sonar.projectKey>iluwatar_java-design-patterns</sonar.projectKey>\r\n<sonar.moduleKey>${project.artifactId}</sonar.moduleKey>\r\n<sonar.projectName>Java Design Patterns</sonar.projectName>\r\n```\r\n\r\nand to build using: `./mvnw clean verify`\r\n\r\nIn order to continue to build the project and do pull request without building errors.",
"comments": [
{
"body": "Kind of works, see https://github.com/iluwatar/java-design-patterns/pull/2398, but maybe we can improve it",
"created_at": "2022-12-18T12:30:46Z"
}
],
"number": 2399,
"title": "Project not found. Please check the 'sonar.projectKey' and 'sonar.organization' properties"
} | {
"body": "- Closes #2399 ",
"number": 2400,
"review_comments": [],
"title": "Allow secrets in incoming pull requests"
} | {
"commits": [
{
"message": "allow secrets in incoming pull requests"
},
{
"message": "trigger on multiple events"
},
{
"message": "fix syntax"
}
],
"files": [
{
"diff": "@@ -28,6 +28,7 @@ name: Java PR Builder\n \n on:\n pull_request:\n+ pull_request_target:\n branches: [ master ]\n types: [ opened, reopened, synchronize ]\n ",
"filename": ".github/workflows/maven-pr-builder.yml",
"status": "modified"
}
]
} |
{
"body": "Naked objects module has tests that are being skipped during the maven build. \r\n\r\nThese tests fail when executed by IntelliJ. They also fail if you try to update to JUnit5 via junit-vintage-engine. \r\n\r\n> This issue partially resolves #1500",
"comments": [
{
"body": "To further clarify this issue - this module should be updated to JUnit 5 and the tests should be refactored as necessary. ",
"created_at": "2021-03-07T05:00:11Z"
},
{
"body": "Hi @charlesfinley ! Could I take this?",
"created_at": "2021-03-15T10:52:08Z"
},
{
"body": "> Hi @charlesfinley ! Could I take this?\r\n\r\nFeel free. Remove any dependency on JUnit4 or junit-vintage-engine and have the tests pass. ",
"created_at": "2021-03-15T12:32:47Z"
},
{
"body": "> Hi @charlesfinley ! Could I take this?\n\nGo ahead!",
"created_at": "2021-03-15T15:40:59Z"
},
{
"body": "Hi @charlesfinley @ohbus ! \r\n\r\nI've tried to migrate `naked-objects` module from junit 4 to junit 5. It went well for `dom` module. But it turned out that `integtests` module is deeply dependent on junit 4 rule API. It seems not possible to migrate without big changes. \r\n\r\n`naked-objects` pattern is a reference for apache isis. The current example is completely out of date. There is [simple-app](https://github.com/apache/isis-app-simpleapp) that uses junit 5. \r\n\r\nSo, we can replace current `naked-objects` with `simple-app` example. Or just leave a reference to `simple-app` in order to have it always up to date. ",
"created_at": "2021-03-17T19:17:33Z"
},
{
"body": "> Hi @charlesfinley @ohbus !\r\n> \r\n> I've tried to migrate `naked-objects` module from junit 4 to junit 5. It went well for `dom` module. But it turned out that `integtests` module is deeply dependent on junit 4 rule API. It seems not possible to migrate without big changes.\r\n> \r\n> `naked-objects` pattern is a reference for apache isis. The current example is completely out of date. There is [simple-app](https://github.com/apache/isis-app-simpleapp) that uses junit 5.\r\n> \r\n> So, we can replace current `naked-objects` with `simple-app` example. Or just leave a reference to `simple-app` in order to have it always up to date.\r\n\r\nIf the pattern is obsolete I don't see an issue getting rid of it, but that's obviously up to @iluwatar and @ohbus. ",
"created_at": "2021-03-18T00:48:43Z"
},
{
"body": "I'm aware the naked objects example is pretty old and out of date already. I think the better route forward for us here would be to get the latest simple-app example from the Isis website and work to make it fit into our pattern catalog. I opened a new issue https://github.com/iluwatar/java-design-patterns/issues/1683 for this.",
"created_at": "2021-03-18T20:08:13Z"
}
],
"number": 1669,
"title": "Tests not being executed in naked-objects"
} | {
"body": "Added link to the Apache Isis starter SimpleApp.\r\n\r\nFixes #983 #1097 #1483 #1669 #1683",
"number": 2336,
"review_comments": [],
"title": "feat: remove naked objects implementation"
} | {
"commits": [
{
"message": "feat: remove naked objects implementation"
}
],
"files": [
{
"diff": "@@ -11,9 +11,6 @@ The Naked Objects architectural pattern is well suited for rapid\n prototyping. Using the pattern, you only need to write the domain objects,\n everything else is autogenerated by the framework.\n \n-## Class diagram\n-\n-\n ## Applicability\n Use the Naked Objects pattern when\n \n@@ -23,7 +20,7 @@ Use the Naked Objects pattern when\n \n ## Real world examples\n \n-* [Apache Isis](https://isis.apache.org/)\n+* [Apache Isis](https://isis.apache.org/docs/2.0.0-M9/starters/simpleapp.html)\n \n ## Credits\n ",
"filename": "naked-objects/README.md",
"status": "modified"
}
]
} |
{
"body": "Hi, this is Masaki Mizobuchi.\r\nI faced the below error when I build the projects. So, I report is.\r\n\r\n**Unknown host repository-estatio.forge.cloudbees.com** is shown when I execute the commnad `mvn eclipse:eclipse`.\r\nIt seems that [(http://repository-estatio.forge.cloudbees.com/snapshot/)] is closed host.\r\n\r\n\r\nError message is below.\r\n\r\n> [ERROR] Failed to execute goal on project naked-objects-fixture: Could not resolve dependencies for project com.iluwatar:naked-objects-fixture:jar:1.22.0-SNAPSHOT: Could not transfer artifact com.iluwatar:naked-objects-dom:jar:1.22.0-SNAPSHOT from/to Cloudbees snapshots (http://repository-estatio.forge.cloudbees.com/snapshot/): repository-estatio.forge.cloudbees.com: Unknown host repository-estatio.forge.cloudbees.com -\r\n\r\n",
"comments": [
{
"body": "Confirmed, I can repeat this.",
"created_at": "2019-11-18T17:16:39Z"
}
],
"number": 1097,
"title": "\"Unknown host repository-estatio.forge.cloudbees.com\" issue"
} | {
"body": "Added link to the Apache Isis starter SimpleApp.\r\n\r\nFixes #983 #1097 #1483 #1669 #1683",
"number": 2336,
"review_comments": [],
"title": "feat: remove naked objects implementation"
} | {
"commits": [
{
"message": "feat: remove naked objects implementation"
}
],
"files": [
{
"diff": "@@ -11,9 +11,6 @@ The Naked Objects architectural pattern is well suited for rapid\n prototyping. Using the pattern, you only need to write the domain objects,\n everything else is autogenerated by the framework.\n \n-## Class diagram\n-\n-\n ## Applicability\n Use the Naked Objects pattern when\n \n@@ -23,7 +20,7 @@ Use the Naked Objects pattern when\n \n ## Real world examples\n \n-* [Apache Isis](https://isis.apache.org/)\n+* [Apache Isis](https://isis.apache.org/docs/2.0.0-M9/starters/simpleapp.html)\n \n ## Credits\n ",
"filename": "naked-objects/README.md",
"status": "modified"
}
]
} |
{
"body": "Some patterns have a small defect in the yaml frontmatter (README.md). Categories key should be renamed to category so that everything shows up correctly on the website.\n\nAcceptance criteria\n\n- The pattern yaml frontmatters have been checked to conform with https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute\n",
"comments": [],
"number": 2329,
"title": "Fix pattern categories"
} | {
"body": "- Closes #2329 ",
"number": 2332,
"review_comments": [],
"title": "Fix yaml frontmatter of several patterns"
} | {
"commits": [
{
"message": "Fix yaml frontmatter of several patterns"
}
],
"files": [
{
"diff": "@@ -1,6 +1,6 @@\n ---\n title: Identity Map\n-categories: Behavioral\n+category: Behavioral\n language: en\n tags:\n - Performance",
"filename": "identity-map/README.md",
"status": "modified"
},
{
"diff": "@@ -1,6 +1,6 @@\n ---\n title: Intercepting Filter\n-categories: Behavioral\n+category: Behavioral\n language: en\n tags:\n - Decoupling",
"filename": "intercepting-filter/README.md",
"status": "modified"
},
{
"diff": "@@ -1,6 +1,6 @@\n ---\n title: Interpreter\n-categories: Behavioral\n+category: Behavioral\n language: en\n tags:\n - Gang of Four",
"filename": "interpreter/README.md",
"status": "modified"
},
{
"diff": "@@ -1,6 +1,6 @@\n ---\n title: Iterator\n-categories: Behavioral\n+category: Behavioral\n language: en\n tags:\n - Gang of Four",
"filename": "iterator/README.md",
"status": "modified"
}
]
} |
{
"body": "A small typo error: all ready (incorrect) instead of already",
"comments": [],
"number": 2325,
"title": "Feature Toggle mispelled comments"
} | {
"body": "I have addressed two minor issues on #2325 : typo and #2326 : small code optimization and refactoring for better readability\r\nPull request title\r\n\r\n- Clearly and concisely describes what it does\r\n- Refer to the issue that it solves, if available\r\n\r\n\r\nPull request description\r\n\r\n- Describes the main changes that come with the pull request\r\n- Any relevant additional information is provided\r\n\r\n\r\n\r\n> For detailed contributing instructions see https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute\r\n",
"number": 2327,
"review_comments": [],
"title": "Issues #2326 and #2325"
} | {
"commits": [
{
"message": "Fix comment typo #2325"
},
{
"message": " Minor enchancements to flyweight #2326"
},
{
"message": " Minor enchancements to flyweight #2326"
}
],
"files": [
{
"diff": "@@ -48,7 +48,7 @@ public class UserGroup {\n */\n public static void addUserToFreeGroup(final User user) throws IllegalArgumentException {\n if (paidGroup.contains(user)) {\n- throw new IllegalArgumentException(\"User all ready member of paid group.\");\n+ throw new IllegalArgumentException(\"User already member of paid group.\");\n } else {\n if (!freeGroup.contains(user)) {\n freeGroup.add(user);\n@@ -65,7 +65,7 @@ public static void addUserToFreeGroup(final User user) throws IllegalArgumentExc\n */\n public static void addUserToPaidGroup(final User user) throws IllegalArgumentException {\n if (freeGroup.contains(user)) {\n- throw new IllegalArgumentException(\"User all ready member of free group.\");\n+ throw new IllegalArgumentException(\"User already member of free group.\");\n } else {\n if (!paidGroup.contains(user)) {\n paidGroup.add(user);",
"filename": "feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java",
"status": "modified"
},
{
"diff": "@@ -46,27 +46,25 @@ Potion createPotion(PotionType type) {\n switch (type) {\r\n case HEALING:\r\n potion = new HealingPotion();\r\n- potions.put(type, potion);\r\n break;\r\n case HOLY_WATER:\r\n potion = new HolyWaterPotion();\r\n- potions.put(type, potion);\r\n break;\r\n case INVISIBILITY:\r\n potion = new InvisibilityPotion();\r\n- potions.put(type, potion);\r\n break;\r\n case POISON:\r\n potion = new PoisonPotion();\r\n- potions.put(type, potion);\r\n break;\r\n case STRENGTH:\r\n potion = new StrengthPotion();\r\n- potions.put(type, potion);\r\n break;\r\n default:\r\n break;\r\n }\r\n+ if (potion != null) {\r\n+ potions.put(type, potion);\r\n+ }\r\n }\r\n return potion;\r\n }\r",
"filename": "flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java",
"status": "modified"
},
{
"diff": "@@ -28,6 +28,7 @@\n import static org.junit.jupiter.api.Assertions.assertNotNull;\n \n import java.util.ArrayList;\n+import java.util.HashSet;\n import org.junit.jupiter.api.Test;\n \n /**\n@@ -55,8 +56,6 @@ void testShop() {\n \n // There are 13 potion instances, but only 5 unique instance types\n assertEquals(13, allPotions.size());\n- assertEquals(5, allPotions.stream().map(System::identityHashCode).distinct().count());\n-\n+ assertEquals(5, new HashSet<>(allPotions).size());\n }\n-\n }",
"filename": "flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java",
"status": "modified"
}
]
} |
{
"body": "The title of the pattern is incorrect, Presentation should be Presentation Model.\n\nAcceptance criteria\n\n- The title has been fixed\n",
"comments": [
{
"body": "Happy to take this up.",
"created_at": "2022-10-30T15:04:27Z"
}
],
"number": 2252,
"title": "Presentation Model title incorrect"
} | {
"body": "Fixes #2252\r\n\r\nIn this PR, we rename `presentation` to `presentation-model`.\r\n\r\nI've used `domain-model` as reference.\r\n\r\nWe update the following:\r\n\r\n- [x] folder/module name from `presentation` to `presentation-model`\r\n- [x] PNG diagram file name from `presentation` to `presentation-model`\r\n- [x] UML diagram file name from `presentation` to `presentation-model`\r\n- [x] README tag/title from `Presentation` to `Presentation Model`\r\n- [x] package from `presentation` to `presentationmodel`\r\n- [x] also update in UML diagram\r\n\r\nPlease let me know if I've missed anything.\r\n\r\nThanks!",
"number": 2291,
"review_comments": [],
"title": "Rename presentation to presentation model"
} | {
"commits": [
{
"message": "Rename presentation to presentation-model"
},
{
"message": "Rename image"
},
{
"message": "Rename UML diagram"
},
{
"message": "Rename presentation to presentation-model"
},
{
"message": "Rename package to presentationmodel"
},
{
"message": "Rename module reference in pom.xml"
}
],
"files": [
{
"diff": "@@ -223,7 +223,7 @@\n <module>model-view-viewmodel</module>\n <module>composite-entity</module>\n <module>table-module</module>\n- <module>presentation</module>\n+ <module>presentation-model</module>\n <module>lockable-object</module>\n <module>fanout-fanin</module>\n <module>domain-model</module>",
"filename": "pom.xml",
"status": "modified"
}
]
} |
{
"body": "There is a nice broken links checker tool available at https://github.com/stevenvachon/broken-link-checker\r\n\r\nAfter installation, one can run it against our website e.g.\r\n\r\n`blc https://java-design-patterns.com -roe`\r\n\r\nThe results indicate 16 broken links. Let's fix them in this task.\r\n\r\nAcceptance criteria\r\n\r\n- The broken links reported by the tool have been fixed\r\n",
"comments": [
{
"body": "Hi, I will happily have a look at this.",
"created_at": "2022-10-24T04:59:17Z"
},
{
"body": "Thanks @Jeremy-Cains-ANU, assigned to you now",
"created_at": "2022-10-24T16:59:38Z"
},
{
"body": "This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.\n",
"created_at": "2022-11-28T12:45:48Z"
}
],
"number": 2152,
"title": "Broken links"
} | {
"body": "Pull request title\r\n\r\n- This solves issue #2152 as much as is possible in this repository\r\n- There was a single broken link in the website repository. Other than that, all were in index.md or /localization/zh/index.md\r\n- One was a link to a pattern that has been removed (semaphore)\r\n- The rest were when the pattern name differed slightly from the folder name in the repo. E.g. command-query-responsibility-segregation is named cqrs, and other acronyms.\r\n- I built the website locally using my updated fork, but blc didn't work locally. I tried the links that I changed, though, and they worked.",
"number": 2182,
"review_comments": [],
"title": "Fix broken links #2152"
} | {
"commits": [
{
"message": "Replaced some of the links which had different names to the folders in the repository (e.g. acronyms)."
},
{
"message": "Fixed the index.md broken links in the zh localisation. This meant making the links match the folder names."
},
{
"message": "Merge pull request #1 from Jeremy-Cains-ANU/Fix-Broken-Links\n\nFix broken links"
},
{
"message": "#88 Created Facet pattern example and wrote most of the README."
},
{
"message": "#88 Made main code comply with CheckStyle."
},
{
"message": "#88 Fixed intellij warnings"
},
{
"message": "#88 Removed tests for different pattern (I copied from proxy)."
},
{
"message": "#88 Removed javadoc comment from readme, updated f_ to faceted in line with the code."
},
{
"message": "Added puml file for diagram."
},
{
"message": "Fixed pom.xml and facet/pom.xml to build and pass tests."
},
{
"message": "#88 Made tests for facet properties. Generated image from puml, and added to readme."
},
{
"message": "#88 Made tests conform to CheckStyle"
},
{
"message": "#88 Applied suggestions from HKattt. Fixed test to able to run by Maven. Made code in README.md match the Java class code"
},
{
"message": "Delete etc directory"
},
{
"message": "#88 Added more related patterns and a reference."
},
{
"message": "#88 Applied feedback from Jesonzavic"
},
{
"message": "Merge pull request #2 from Jeremy-Cains-ANU/Facet\n\n#88 Implemented Facet"
},
{
"message": "added licences"
}
],
"files": [
{
"diff": "@@ -0,0 +1,214 @@\n+--- \n+layout: pattern\n+title: Facet\n+folder: facet\n+permalink: /patterns/facet/\n+categories:\n+- structural\n+language: en\n+tags:\n+- Decoupling\n+- Security\n+---\n+\n+## Also known as\n+\n+Attenuation\n+\n+## Intent\n+\n+Provide an interface to a powerful object in a restricted way, either by restricting parameters \n+or only allowing calls to a subset of object's functions such that the powerful object's \n+capabilities are not abused by any other classes.\n+\n+## Explanation\n+\n+Real-world example\n+\n+> Imagine a knight fighting a dragon. The knight can only attempt to attack the dragon by trying\n+> different attacks. Here, the facet stops the knight from directly changing the health of the \n+> dragon, as well as only allowing certain attacks to affect the dragon.\n+\n+In plain words\n+\n+> Using the facet pattern, a facet class protects others classes from misusing a powerful class by\n+> only allowing them to use and see some of its functionality.\n+\n+C2 Wiki says that the intent is to\n+\n+> Restrict an interface to obtain a smaller interface that provides less authority. Usually\n+> the smaller interface has only a subset of the methods, or allows only a subset of parameter \n+> values. Facets are used as a security pattern in [CapabilityOrientedProgramming](https://wiki.c2.com/?CapabilityOrientedProgramming), \n+> in order to satisfy the [PrincipleOfLeastAuthority](https://wiki.c2.com/?PrincipleOfLeastAuthority). \n+> For example, if some client of an object only needs to be able to read information from it, that client should be \n+> provided with a read-only facet.\n+\n+**Programmatic Example**\n+\n+Taking our knight versus dragon example from above. Firstly we have the `Knight` class and the \n+`Attack` enum containing attacks that can belong to knights.\n+\n+```java\n+@Slf4j\n+public class Knight {\n+ private final String name;\n+ private Attack attack;\n+ private DragonFacet dragonFacet;\n+\n+ public Knight(String name, Attack attack, DragonFacet dragonFacet) {\n+ this.name = name;\n+ this.attack = attack;\n+ this.dragonFacet = dragonFacet;\n+ }\n+\n+ public void attackDragon() {\n+ int oldHealth = dragonFacet.getHealth();\n+ dragonFacet.receiveAttack(attack);\n+ if (oldHealth == dragonFacet.getHealth()) {\n+ LOGGER.info(\"{}: Darn it! {} did nothing.\", name, attack);\n+ } else {\n+ LOGGER.info(\"{}: Huzzah! {} hurt that dastardly dragon.\", name, attack);\n+ }\n+ }\n+}\n+\n+public enum Attack {\n+ ARROW, WATER_PISTOL, SWORD, FLAME_THROWER\n+}\n+```\n+\n+Next are the `Dragon` class and the `DragonFacet` class. These belong to the same package, which is\n+different to the package containing `Knight`. This means that when there is no access level modifier to a variable or method, such as for `setHealth()`, nothing outside the package will have access to them. So, if the facet doesn't allow it then there is no way to access them.\n+\n+Note that, according to C2 Wiki, \n+\n+> Facets should be implemented in such a way that if methods are added to the original interface, \n+> they are not added by default to the facet. The methods to be included in a facet should have to \n+> be explicitly indicated (although this could be by metadata or a naming convention). \n+\n+In this case, the methods are marked with `faceted`.\n+\n+This is the simple `Dragon` class.\n+\n+```java\n+public class Dragon {\n+ private int health;\n+\n+ public Dragon(int health) {\n+ this.health = health;\n+ }\n+\n+ int facetedGetHealth() {\n+ return health;\n+ }\n+\n+ void setHealth(int health) {\n+ this.health = health;\n+ }\n+\n+ void facetedReceiveAttack(Attack attack) {\n+ switch (attack) {\n+ case ARROW:\n+ health -= 10;\n+ break;\n+ case WATER_PISTOL:\n+ health -= 15;\n+ break;\n+ default:\n+ health -= 5;\n+ }\n+ }\n+}\n+```\n+\n+Then we have the `DragonFacet` to add control to `Dragon`.\n+\n+```java\n+package com.iluwatar.facet.dragon;\n+\n+import com.iluwatar.facet.Attack;\n+import lombok.extern.slf4j.Slf4j;\n+\n+@Slf4j\n+public class DragonFacet {\n+ private Dragon dragon;\n+\n+ public DragonFacet(Dragon dragon) {\n+ this.dragon = dragon;\n+ }\n+\n+ public int getHealth() {\n+ return dragon.facetedGetHealth();\n+ }\n+\n+ public void receiveAttack(Attack attack) {\n+ if (attack == Attack.WATER_PISTOL || attack == Attack.ARROW) {\n+ dragon.facetedReceiveAttack(attack);\n+ }\n+ }\n+}\n+\n+```\n+\n+Note that `DragonFacet` only provides access to two of the three methods in `Dragon` \n+(the ones marked with `faceted`). Also, `receiveAttack` makes a check for valid parameters.\n+\n+And here is the dragon-fighting scenario.\n+\n+```java\n+var facet = new DragonFacet(new Dragon(100));\n+var sirJim = new Knight(\"Sir Jim\", Attack.WATER_PISTOL, facet);\n+sirJim.attackDragon();\n+var sirLuke = new Knight(\"Sir Luke\", Attack.FLAME_THROWER, facet);\n+sirLuke.attackDragon();\n+```\n+\n+Program output:\n+\n+```\n+Sir Jim: Huzzah! WATER_PISTOL hurt that dastardly dragon.\n+Sir Luke: Darn it! FLAME_THROWER did nothing.\n+```\n+\n+## Class diagram\n+\n+\n+\n+## Applicability\n+\n+Facet is applicable when the client should have restricted access to an object. It is\n+a special type of proxy, but no extra functionality may be provided; that is, the facet\n+should only provide a subset of the object's functionality to a client.\n+\n+This is often a security pattern, used in order to satisfy the Principle of Least \n+Authority. For example, if an object should be read-only, then the client should \n+be provided with a read-only facet.\n+\n+## Known Uses\n+\n+In the Java Database Connectivity (JDBC) API, the interface that is provided is \n+a facet. The users do not see implementation details of accessing the database,\n+does the user have as much power as classes of the implementation.\n+\n+## Consequences\n+\n+Pros:\n+\n+- An object that has potential to be misused can be protected from other classes.\n+\n+Cons:\n+\n+- There is an overhead cost in writing the code for another class which\n+doesn't provide any extra functionality.\n+\n+## Related patterns\n+\n+* [Proxy](https://java-design-patterns.com/patterns/proxy/)\n+* [Adapter](https://java-design-patterns.com/patterns/adapter/)\n+* [Facade](https://java-design-patterns.com/patterns/facade/)\n+\n+## Credits\n+\n+* [Facet Pattern](http://wiki.c2.com/?FacetPattern)\n+* [Capability Theory Glossary](http://www.cap-lore.com/CapTheory/Glossary.html)\n+* [What is Facet design pattern?](https://stackoverflow.com/questions/30164108/what-is-facet-design-pattern)",
"filename": "facet/README.md",
"status": "added"
},
{
"diff": "",
"filename": "facet/etc/facet.urm.png",
"status": "added"
},
{
"diff": "@@ -0,0 +1,43 @@\n+@startuml\n+package com.iluwatar.facet.dragon {\n+ class Dragon {\n+ - health : int\n+ + Dragon(health : int)\n+ ~ facetedGetHealth() : int\n+ ~ facetedReceiveAttack(attack : Attack)\n+ ~ setHealth(health : int)\n+ }\n+ class DragonFacet {\n+ - LOGGER : Logger {static}\n+ - dragon : Dragon\n+ + DragonFacet(dragon : Dragon)\n+ + getHealth() : int\n+ + receiveAttack(attack : Attack)\n+ }\n+}\n+package com.iluwatar.facet {\n+ class App {\n+ + App()\n+ + main(args : String[]) {static}\n+ }\n+ enum Attack {\n+ + ARROW {static}\n+ + FLAME_THROWER {static}\n+ + SWORD {static}\n+ + WATER_PISTOL {static}\n+ + valueOf(name : String) : Attack {static}\n+ + values() : Attack[] {static}\n+ }\n+ class Knight {\n+ - LOGGER : Logger {static}\n+ - attack : Attack\n+ - dragonFacet : DragonFacet\n+ - name : String\n+ + Knight(name : String, attack : Attack, dragonFacet : DragonFacet)\n+ + attackDragon()\n+ }\n+}\n+DragonFacet --> \"-dragon\" Dragon\n+Knight -up-> \"-dragonFacet\" DragonFacet\n+Knight --> \"-attack\" Attack\n+@enduml\n\\ No newline at end of file",
"filename": "facet/etc/facet.urm.puml",
"status": "added"
},
{
"diff": "@@ -0,0 +1,67 @@\n+<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n+<!--\n+\n+ This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).\n+\n+ The MIT License\n+ Copyright © 2014-2022 Ilkka Seppälä\n+\n+ Permission is hereby granted, free of charge, to any person obtaining a copy\n+ of this software and associated documentation files (the \"Software\"), to deal\n+ in the Software without restriction, including without limitation the rights\n+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ copies of the Software, and to permit persons to whom the Software is\n+ furnished to do so, subject to the following conditions:\n+\n+ The above copyright notice and this permission notice shall be included in\n+ all copies or substantial portions of the Software.\n+\n+ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ THE SOFTWARE.\n+\n+-->\n+<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n+ <modelVersion>4.0.0</modelVersion>\n+ <parent>\n+ <groupId>com.iluwatar</groupId>\n+ <artifactId>java-design-patterns</artifactId>\n+ <version>1.26.0-SNAPSHOT</version>\n+ </parent>\n+ <artifactId>facet</artifactId>\n+ <dependencies>\n+ <dependency>\n+ <groupId>org.junit.jupiter</groupId>\n+ <artifactId>junit-jupiter-engine</artifactId>\n+ <scope>test</scope>\n+ </dependency>\n+ <dependency>\n+ <groupId>org.mockito</groupId>\n+ <artifactId>mockito-core</artifactId>\n+ <scope>test</scope>\n+ </dependency>\n+ </dependencies>\n+ <build>\n+ <plugins>\n+ <plugin>\n+ <groupId>org.apache.maven.plugins</groupId>\n+ <artifactId>maven-assembly-plugin</artifactId>\n+ <executions>\n+ <execution>\n+ <configuration>\n+ <archive>\n+ <manifest>\n+ <mainClass>com.iluwatar.facet.App</mainClass>\n+ </manifest>\n+ </archive>\n+ </configuration>\n+ </execution>\n+ </executions>\n+ </plugin>\n+ </plugins>\n+ </build>\n+</project>",
"filename": "facet/pom.xml",
"status": "added"
},
{
"diff": "@@ -0,0 +1,56 @@\n+/*\n+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).\n+ *\n+ * The MIT License\n+ * Copyright © 2014-2022 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.facet;\n+\n+import com.iluwatar.facet.dragon.Dragon;\n+import com.iluwatar.facet.dragon.DragonFacet;\n+\n+\n+/**\n+ * A facet is a class functioning as an interface to something else which provides less functionality.\n+ * It is a wrapper often used for security purposes, so that the Principle of Least Authority is\n+ * observed. It is technically a special case of proxy.\n+ *\n+ * <p>The Facet design pattern allows you to provide an interface to other objects by creating a\n+ * wrapper class as the facet. The wrapper class, which is the facet, must only provide access to\n+ * certain functions and under certain parameters, but never add functionality.\n+ *\n+ * <p>In this example the facet ({@link DragonFacet}) controls access to the actual object (\n+ * {@link Dragon}).\n+ */\n+public class App {\n+\n+ /**\n+ * Program entry point.\n+ */\n+ public static void main(String[] args) {\n+ var facet = new DragonFacet(new Dragon(100));\n+ var sirJim = new Knight(\"Sir Jim\", Attack.WATER_PISTOL, facet);\n+ sirJim.attackDragon();\n+ var sirLuke = new Knight(\"Sir Luke\", Attack.FLAME_THROWER, facet);\n+ sirLuke.attackDragon();\n+ }\n+}",
"filename": "facet/src/main/java/com/iluwatar/facet/App.java",
"status": "added"
},
{
"diff": "@@ -0,0 +1,34 @@\n+/*\n+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).\n+ *\n+ * The MIT License\n+ * Copyright © 2014-2022 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.facet;\n+\n+/**\n+ * Four attacks that the knights can have.\n+ * These have various levels of usefulness against a dragon.\n+ */\n+public enum Attack {\n+ ARROW, WATER_PISTOL, SWORD, FLAME_THROWER\n+}",
"filename": "facet/src/main/java/com/iluwatar/facet/Attack.java",
"status": "added"
},
{
"diff": "@@ -0,0 +1,67 @@\n+/*\n+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).\n+ *\n+ * The MIT License\n+ * Copyright © 2014-2022 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.facet;\n+\n+import com.iluwatar.facet.dragon.DragonFacet;\n+import lombok.extern.slf4j.Slf4j;\n+\n+/**\n+ * Simple knight class. It is given a reference only to a DragonFacet,\n+ * not a dragon itself. This restricts its access to its functions and\n+ * disallows some incorrect parameters in the receiveAttack() function.\n+ */\n+@Slf4j\n+public class Knight {\n+ private final String name;\n+ private final Attack attack;\n+ private final DragonFacet dragonFacet;\n+\n+ /**\n+ * Simple constructor for a Knight.\n+ *\n+ * @param name The name of the knight\n+ * @param attack His type of attack\n+ * @param dragonFacet The reference to the dragon wrapped by a facet\n+ */\n+ public Knight(String name, Attack attack, DragonFacet dragonFacet) {\n+ this.name = name;\n+ this.attack = attack;\n+ this.dragonFacet = dragonFacet;\n+ }\n+\n+ /**\n+ * Try to attack the dragon through the facet.\n+ */\n+ public void attackDragon() {\n+ int oldHealth = dragonFacet.getHealth();\n+ dragonFacet.receiveAttack(attack);\n+ if (oldHealth == dragonFacet.getHealth()) {\n+ LOGGER.info(\"{}: Darn it! {} did nothing.\", name, attack);\n+ } else {\n+ LOGGER.info(\"{}: Huzzah! {} hurt that dastardly dragon.\", name, attack);\n+ }\n+ }\n+}",
"filename": "facet/src/main/java/com/iluwatar/facet/Knight.java",
"status": "added"
},
{
"diff": "@@ -0,0 +1,70 @@\n+/*\n+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).\n+ *\n+ * The MIT License\n+ * Copyright © 2014-2022 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.facet.dragon;\n+\n+import com.iluwatar.facet.Attack;\n+\n+/**\n+ * Dragon object needs to be protected, since the other objects shouldn't be\n+ * allowed to edit its health. That is why it is in its own package with\n+ * {@link DragonFacet} and all the functions have no access level modifiers,\n+ * meaning only classes in the same package have access.\n+ */\n+public class Dragon {\n+ private int health;\n+\n+ public Dragon(int health) {\n+ this.health = health;\n+ }\n+\n+ int facetedGetHealth() {\n+ return health;\n+ }\n+\n+ /**\n+ * This has no access level modifier, so only other classes within\n+ * the same package can access this function. This protects the knight\n+ * from being able to arbitrarily change the dragon's health.\n+ *\n+ * @param health The new health of the dragon\n+ */\n+ void setHealth(int health) {\n+ this.health = health;\n+ }\n+\n+ void facetedReceiveAttack(Attack attack) {\n+ switch (attack) {\n+ case ARROW:\n+ health -= 10;\n+ break;\n+ case WATER_PISTOL:\n+ health -= 15;\n+ break;\n+ default:\n+ health -= 5;\n+ }\n+ }\n+}",
"filename": "facet/src/main/java/com/iluwatar/facet/dragon/Dragon.java",
"status": "added"
},
{
"diff": "@@ -0,0 +1,60 @@\n+/*\n+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).\n+ *\n+ * The MIT License\n+ * Copyright © 2014-2022 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.facet.dragon;\n+\n+import com.iluwatar.facet.Attack;\n+\n+/**\n+ * The facet class which acts as an interface/wrapper for {@link Dragon}.\n+ * It only allows access to the methods with names beginning\n+ * with 'faceted', and also checks in receiveAttack() what\n+ * the type of attack is, so that it can filter some illegal\n+ * values.\n+ */\n+public class DragonFacet {\n+ private final Dragon dragon;\n+\n+ public DragonFacet(Dragon dragon) {\n+ this.dragon = dragon;\n+ }\n+\n+ public int getHealth() {\n+ return dragon.facetedGetHealth();\n+ }\n+\n+ /**\n+ * This performs a check of the attack, and for certain illegal values\n+ * (namely FLAME_THROWER and SWORD), the attack will not even alert\n+ * the dragon.\n+ *\n+ * @param attack The attack which is attempted against dragon\n+ */\n+ public void receiveAttack(Attack attack) {\n+ if (attack == Attack.WATER_PISTOL || attack == Attack.ARROW) {\n+ dragon.facetedReceiveAttack(attack);\n+ }\n+ }\n+}",
"filename": "facet/src/main/java/com/iluwatar/facet/dragon/DragonFacet.java",
"status": "added"
},
{
"diff": "@@ -0,0 +1,41 @@\n+/*\n+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).\n+ *\n+ * The MIT License\n+ * Copyright © 2014-2022 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.facet;\n+\n+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;\n+\n+import org.junit.jupiter.api.Test;\n+\n+/**\n+ * Application test.\n+ */\n+class AppTest {\n+\n+ @Test\n+ void shouldExecuteApplicationWithoutException() {\n+ assertDoesNotThrow(() -> App.main(new String[]{}));\n+ }\n+}",
"filename": "facet/src/test/java/com/iluwatar/facet/AppTest.java",
"status": "added"
},
{
"diff": "@@ -0,0 +1,114 @@\n+/*\n+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).\n+ *\n+ * The MIT License\n+ * Copyright © 2014-2022 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.facet;\n+\n+import static org.junit.jupiter.api.Assertions.assertFalse;\n+import static org.junit.jupiter.api.Assertions.assertThrows;\n+import static org.junit.jupiter.api.Assertions.assertTrue;\n+\n+import com.iluwatar.facet.dragon.Dragon;\n+import com.iluwatar.facet.dragon.DragonFacet;\n+import java.lang.reflect.Method;\n+import java.util.ArrayList;\n+import org.junit.jupiter.api.Test;\n+\n+/**\n+ * Test that the definition of a facet is upheld. That is,\n+ * a facet handles all access to the protected object,\n+ * and the functions of the facet are a subset of the\n+ * protected object's functions.\n+ */\n+public class MethodsOfFacetTest {\n+ /**\n+ * No functions should be callable from the protected class.\n+ * All objects must only be able to interact with the facet.\n+ */\n+ @Test\n+ public void visibleDragonMethods() {\n+ Dragon dragon = new Dragon(100);\n+ Method[] methods = Dragon.class.getDeclaredMethods();\n+ for (Method method : methods) {\n+ assertThrows(IllegalAccessException.class,\n+ () -> method.invoke(dragon, \"\"));\n+ }\n+ }\n+\n+ /**\n+ * Checks that the functions in the facet are a subset of the functions in\n+ * the class it is faceting. This means that:\n+ * 1. The number of functions in the facet class are less than or equal to\n+ * the number of functions in the protected class.\n+ * 2. Every protected class function that is marked with \"faceted\" must be\n+ * in the facet class (with \"faceted\" removed). All other functions must\n+ * not be in the facet class. \"faceted\" is the way of marking a function\n+ * to be used in the facet, which is recommended at\n+ * <a href=\"https://wiki.c2.com/?FacetPattern\">Facet - c2 wiki.</a>\n+ * 3. Every function in the facet class must be in the protected class\n+ * (with \"faceted\" in front of the name).\n+ * (2. and 3. imply 1.)\n+ */\n+ @Test\n+ public void facetIsSubset() {\n+ Method[] dragonMethods = Dragon.class.getDeclaredMethods();\n+ Method[] dragonFacetMethods = DragonFacet.class.getDeclaredMethods();\n+\n+ //Check 1. from javadoc comment.\n+ assertTrue(dragonMethods.length >= dragonFacetMethods.length);\n+\n+ ArrayList<String> facetMethodNames = new ArrayList<>();\n+ for (Method facetMethod : dragonFacetMethods) {\n+ if (!facetMethod.isSynthetic()) {\n+ facetMethodNames.add(facetMethod.getName());\n+ }\n+ }\n+ ArrayList<String> dragonMethodNames = new ArrayList<>();\n+ for (Method dragonMethod : dragonMethods) {\n+ if (!dragonMethod.isSynthetic()) {\n+ dragonMethodNames.add(dragonMethod.getName());\n+ }\n+ }\n+\n+ //Check 2. from javadoc comment.\n+ for (String dragonMethodName : dragonMethodNames) {\n+ if (dragonMethodName.startsWith(\"faceted\")) {\n+ String expectedName = dragonMethodName.substring(\"faceted\".length());\n+ expectedName = Character.toLowerCase(expectedName.charAt(0))\n+ + expectedName.substring(1);\n+ assertTrue(facetMethodNames.contains(expectedName));\n+ } else {\n+ assertFalse(facetMethodNames.contains(dragonMethodName));\n+ }\n+ }\n+\n+ //Check 3. from javadoc comment.\n+ for (String facetMethodName : facetMethodNames) {\n+ String expectedName = \"faceted\"\n+ + Character.toUpperCase(facetMethodName.charAt(0))\n+ + facetMethodName.substring(1);\n+ assertTrue(dragonMethodNames.contains(expectedName));\n+ }\n+ }\n+}",
"filename": "facet/src/test/java/com/iluwatar/facet/MethodsOfFacetTest.java",
"status": "added"
},
{
"diff": "@@ -0,0 +1,80 @@\n+/*\n+ * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).\n+ *\n+ * The MIT License\n+ * Copyright © 2014-2022 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.facet;\n+\n+import static org.junit.jupiter.api.Assertions.assertEquals;\n+import static org.junit.jupiter.api.Assertions.assertNotEquals;\n+\n+import com.iluwatar.facet.dragon.Dragon;\n+import com.iluwatar.facet.dragon.DragonFacet;\n+import org.junit.jupiter.api.Test;\n+\n+\n+/**\n+ * One of the possible ways of using a facet is to restrict parameters that can\n+ * be used by the protected class. This class tests that some parameters do\n+ * something while others don't.\n+ */\n+public class ParameterBlockingTest {\n+\n+ /**\n+ * Make sure that illegal parameters applied to the receiveAttack function in\n+ * the dragonFacet indeed do not do any damage (i.e. are ignored.)\n+ */\n+ @Test\n+ public void blockIllegalParameters() {\n+ Dragon dragon = new Dragon(100);\n+ DragonFacet dragonFacet = new DragonFacet(dragon);\n+ Knight sirJim = new Knight(\"Sir Jim\", Attack.SWORD, dragonFacet);\n+ int oldDragonHealth = dragonFacet.getHealth();\n+ sirJim.attackDragon();\n+ assertEquals(oldDragonHealth, dragonFacet.getHealth());\n+\n+ Knight sirWill = new Knight(\"Sir Will\", Attack.FLAME_THROWER, dragonFacet);\n+ oldDragonHealth = dragonFacet.getHealth();\n+ sirWill.attackDragon();\n+ assertEquals(oldDragonHealth, dragonFacet.getHealth());\n+ }\n+\n+ /**\n+ * These tests make sure that the dragon is indeed attacked when the knights\n+ * use the correct attacks.\n+ */\n+ @Test\n+ public void allowLegalParameters() {\n+ Dragon dragon = new Dragon(100);\n+ DragonFacet dragonFacet = new DragonFacet(dragon);\n+ Knight sirJim = new Knight(\"Sir Jim\", Attack.ARROW, dragonFacet);\n+ int oldDragonHealth = dragonFacet.getHealth();\n+ sirJim.attackDragon();\n+ assertNotEquals(oldDragonHealth, dragonFacet.getHealth());\n+\n+ Knight sirWill = new Knight(\"Sir Will\", Attack.WATER_PISTOL, dragonFacet);\n+ oldDragonHealth = dragonFacet.getHealth();\n+ sirWill.attackDragon();\n+ assertNotEquals(oldDragonHealth, dragonFacet.getHealth());\n+ }\n+}",
"filename": "facet/src/test/java/com/iluwatar/facet/ParameterBlockingTest.java",
"status": "added"
},
{
"diff": "@@ -27,8 +27,8 @@\n | [Composite](composite) | Structural | Gang of Four |\n | [Composite Entity](composite-entity) | Structural | Enterprise Integration Pattern |\n | [Converter](converter) | Creational | Decoupling |\n-| [Command Query Responsibility Segregation](command-query-responsibility-segregation) | Architectural | Performance, Cloud distributed |\n-| [Data Access Object](data-access-object) | Architectural | Data access |\n+| [Command Query Responsibility Segregation](cqrs) | Architectural | Performance, Cloud distributed |\n+| [Data Access Object](dao) | Architectural | Data access |\n | [Data Bus](data-bus) | Architectural | Decoupling |\n | [Data Locality](data-locality) | Behavioral | Performance, Game programming |\n | [Data Mapper](data-mapper) | Architectural | Decoupling |\n@@ -42,11 +42,11 @@\n | [Double Dispatch](double-dispatch) | Idiom | Extensibility |\n | [EIP Aggregator](eip-aggregator) | Integration | Enterprise Integration Pattern |\n | [EIP Message Channel](eip-message-channel) | Integration | Enterprise Integration Pattern |\n-| [EIP Publish and Subscribe](eip-publish-and-subscribe) | Integration | Enterprise Integration Pattern |\n+| [EIP Publish and Subscribe](eip-publish-subscribe) | Integration | Enterprise Integration Pattern |\n | [EIP Splitter](eip-splitter) | Integration | Enterprise Integration Pattern |\n | [EIP Wire Tap](eip-wire-tap) | Integration | Enterprise Integration Pattern |\n | [Event Aggregator](event-aggregator) | Structural | Reactive |\n-| [Event Based Asynchronous](event-based-asynchronous) | Concurrency | Reactive |\n+| [Event Based Asynchronous](event-asynchronous) | Concurrency | Reactive |\n | [Event Driven Architecture](event-driven-architecture) | Architectural | Reactive |\n | [Event Queue](event-queue) | Concurrency | Game programming |\n | [Event Sourcing](event-sourcing) | Architectural | Performance |\n@@ -59,7 +59,7 @@\n | [Fan-Out/Fan-In](fanout-fanin) | Integration | Microservices |\n | [Feature Toggle](feature-toggle) | Behavioral | Extensibility |\n | [Filterer](filterer) | Functional | Extensibility |\n-| [Fluent Interface](fluent-interface) | Functional | Reactive |\n+| [Fluent Interface](fluentinterface) | Functional | Reactive |\n | [Flux](flux) | Structural | Decoupling |\n | [Flyweight](flyweight) | Structural | Gang of Four, Performance |\n | [Front Controller](front-controller) | Structural | Decoupling |\n@@ -75,8 +75,8 @@\n | [Leader Election](leader-election) | Behavioral | Cloud distributed |\n | [Leader Followers](leader-followers) | Concurrency | Performance |\n | [Lockable Object](lockable-object) | Concurrency | Performance |\n-| [Marker Interface](marker-interface) | Structural | Decoupling |\n-| [Master Worker](master-worker) | Concurrency | Performance |\n+| [Marker Interface](marker) | Structural | Decoupling |\n+| [Master Worker](master-worker-pattern) | Concurrency | Performance |\n | [Mediator](mediator) | Behavioral | Gang of Four, Decoupling |\n | [Memento](memento) | Behavioral | Gang of Four |\n | [Model View Controller](model-view-controller) | Architectural | Decoupling |\n@@ -97,15 +97,15 @@\n | [Partial Response](partial-response) | Behavioral | Decoupling |\n | [Pipeline](pipeline) | Behavioral | Decoupling |\n | [Poison Pill](poison-pill) | Behavioral | Cloud distributed, Reactive |\n-| [Presentation Model](presentation-model) | Behavioral | Decoupling |\n+| [Presentation Model](presentation) | Behavioral | Decoupling |\n | [Priority Queue](priority-queue) | Behavioral | Decoupling |\n | [Private Class Data](private-class-data) | Idiom | Data access |\n | [Producer Consumer](producer-consumer) | Concurrency | Reactive |\n | [Promise](promise) | Concurrency | Reactive |\n | [Property](property) | Creational | Instantiation |\n | [Prototype](prototype) | Creational | Gang of Four, Instantiation |\n | [Proxy](proxy) | Structural | Gang of Four, Decoupling |\n-| [Queue Based Load Leveling](queue-based-load-leveling) | Concurrency | Performance, Decoupling |\n+| [Queue Based Load Leveling](queue-load-leveling) | Concurrency | Performance, Decoupling |\n | [Reactor](reactor) | Concurrency | Performance, Reactive |\n | [Reader Writer Lock](reader-writer-lock) | Concurrency | Performance |\n | [Registry](registry) | Creational | Instantiation |\n@@ -114,7 +114,6 @@\n | [Retry](retry) | Behavioral | Performance |\n | [Role Object](role-object) | Structural | Extensibility |\n | [Saga](saga) | Concurrency | Cloud distributed |\n-| [Semaphore](semaphore) | Concurrency | Performance |\n | [Separated Interface](separated-interface) | Structural | Decoupling |\n | [Servant](servant) | Behavioral | Decoupling |\n | [Serverless](serverless) | Architectural | Cloud distributed |\n@@ -134,12 +133,12 @@\n | [Template Method](table-module) | Behavioral | Gang of Four |\n | [Thread Pool](thread-pool) | Concurrency | Performance |\n | [Throttling](throttling) | Behavioral | Performance |\n-| [Thread Local Storage](thread-local-storage) | Idiom | Performance |\n+| [Thread Local Storage](tls) | Idiom | Performance |\n | [Tolerant Reader](tolerant-reader) | Integration | Decoupling |\n | [Trampoline](trampoline) | Behavioral | Performance |\n | [Transaction Script](transaction-script) | Behavioral | Data access |\n | [Twin](twin) | Structural | Extensibility |\n-| [Type Object](type-object) | Behavioral | Game programming, Extensibility |\n+| [Type Object](typeobjectpattern) | Behavioral | Game programming, Extensibility |\n | [Unit of Work](unit-of-work) | Architectural | Data access |\n | [Update Method](update-method) | Behavioral | Game programming |\n | [Value Object](value-object) | Creational | Instantiation |",
"filename": "index.md",
"status": "modified"
},
{
"diff": "@@ -17,15 +17,15 @@\n | [Bytecode](bytecode) | Behavioral | Game programming |\n | [Caching](caching) | Behavioral | Performance |\n | [Callback](callback) | Idiom | Reactive |\n-| [Chain of Responsibility](chain-of-responsibility) | Behavioral | Gang of Four |\n+| [Chain of Responsibility](chain) | Behavioral | Gang of Four |\n | [Circuit Breaker](circuit-breaker) | Behavioral | Performance, Decoupling |\n | [Cloud Static Content Hosting](cloud-static-content-hosting) | Cloud | Cloud distributed |\n | [Collection Pipeline](collection-pipeline) | Functional | Reactive |\n | [Command](command) | Behavioral | Gang of Four |\n | [Composite](composite) | Structural | Gang of Four |\n | [Composite Entity](composite-entity) | Structural | Enterprise Integration Pattern |\n | [Converter](converter) | Creational | Decoupling |\n-| [Data Access Object](data-access-object) | Architectural | Data access |\n+| [Data Access Object](dao) | Architectural | Data access |\n | [Data Bus](data-bus) | Architectural | Decoupling |\n | [Data Mapper](data-mapper) | Architectural | Decoupling |\n | [Data Transfer Object](data-transfer-object) | Architectural | Performance |\n@@ -47,6 +47,6 @@\n | [Sharding](sharding) | Behavioral | Performance, Cloud distributed |\n | [State](state) | Behavioral | Gang of Four |\n | [Strategy](strategy) | Behavioral | Gang of Four |\n-| [Template Method](table-module) | Behavioral | Gang of Four |\n+| [Template Method](template-method) | Behavioral | Gang of Four |\n | [Version Number](version-number) | Concurrency | Data access, Microservices |\n | [Visitor](visitor) | Behavioral | Gang of Four |",
"filename": "localization/zh/index.md",
"status": "modified"
},
{
"diff": "@@ -230,6 +230,7 @@\n <module>composite-view</module>\n <module>metadata-mapping</module>\n <module>service-to-worker</module>\n+ <module>facet</module>\n </modules>\n <repositories>\n <repository>\n@@ -562,4 +563,4 @@\n </plugin>\n </plugins>\n </build>\n-</project>\n\\ No newline at end of file\n+</project>",
"filename": "pom.xml",
"status": "modified"
}
]
} |
{
"body": "The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n\r\nLinks:\r\n[Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n[Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n***\r\n\r\nNote: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036) \r\n",
"comments": [
{
"body": "Can I take this issue?",
"created_at": "2019-10-17T23:05:00Z"
},
{
"body": "Sure @ykayacan ",
"created_at": "2019-10-18T05:46:37Z"
},
{
"body": "This issue is free for taking again.",
"created_at": "2020-06-14T19:45:29Z"
},
{
"body": "I would like to take this issue.",
"created_at": "2020-08-15T09:50:12Z"
},
{
"body": "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.",
"created_at": "2020-08-15T11:04:11Z"
},
{
"body": "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.",
"created_at": "2020-08-15T17:57:51Z"
},
{
"body": "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.",
"created_at": "2020-08-15T18:04:22Z"
},
{
"body": "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL",
"created_at": "2020-08-22T10:44:20Z"
},
{
"body": "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list",
"created_at": "2020-08-22T10:58:00Z"
},
{
"body": "@iluwatar happy to be back again :)\r\nCan I help with this issue?",
"created_at": "2020-10-02T12:19:00Z"
},
{
"body": "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL",
"created_at": "2020-10-12T01:07:28Z"
},
{
"body": "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!",
"created_at": "2020-11-08T16:48:52Z"
},
{
"body": "@iluwatar Can I help with this issue?",
"created_at": "2020-12-14T09:34:32Z"
},
{
"body": "Sure if @anuragagarwal561994 is no longer working on it?",
"created_at": "2020-12-14T18:29:04Z"
},
{
"body": "No @iluwatar I didn't get time to look into this, you can re-assign",
"created_at": "2020-12-16T12:52:35Z"
},
{
"body": "@iluwatar I will start working on it ",
"created_at": "2020-12-17T05:40:24Z"
},
{
"body": "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go",
"created_at": "2021-01-13T19:50:49Z"
},
{
"body": "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?",
"created_at": "2021-04-01T16:09:51Z"
},
{
"body": "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ",
"created_at": "2021-04-01T16:23:27Z"
},
{
"body": "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!",
"created_at": "2021-04-01T16:57:30Z"
},
{
"body": "Thank you. I'm going to begin with this.",
"created_at": "2021-04-01T17:06:25Z"
},
{
"body": "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"created_at": "2021-04-01T22:19:12Z"
},
{
"body": "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.",
"created_at": "2021-04-02T15:50:32Z"
},
{
"body": "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)",
"created_at": "2021-04-07T21:28:09Z"
},
{
"body": "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n",
"created_at": "2021-04-07T23:11:03Z"
},
{
"body": "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n",
"created_at": "2021-04-18T09:48:58Z"
},
{
"body": "@iluwatar Thank you! ",
"created_at": "2021-04-23T13:17:34Z"
},
{
"body": "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER",
"created_at": "2021-06-07T01:32:16Z"
},
{
"body": "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.",
"created_at": "2021-06-07T14:48:38Z"
},
{
"body": "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ",
"created_at": "2021-06-07T16:46:24Z"
}
],
"number": 1012,
"title": "SonarCloud reports issues"
} | {
"body": "CRITICAL Sonar issue fix for duplicate string fixes #1012 \r\n\r\nPull request description\r\nReplaced multiple occurrences of string with constant field to fix CRITICAL Sonar findings.",
"number": 2176,
"review_comments": [],
"title": "Sonar CRITICAL issue fixes"
} | {
"commits": [
{
"message": "Sonar CRITICAL issue fixes"
}
],
"files": [
{
"diff": "@@ -37,35 +37,42 @@ public class App {\n \n private static final Logger LOGGER = LoggerFactory.getLogger(App.class);\n \n+ private static final String LOGGER_STRING = \"[REQUEST] User: {} buy product: {}\";\n+ private static final String TEST_USER_1 = \"ignite1771\";\n+ private static final String TEST_USER_2 = \"abc123\";\n+ private static final String ITEM_TV = \"tv\";\n+ private static final String ITEM_CAR = \"car\";\n+ private static final String ITEM_COMPUTER = \"computer\";\n+\n /**\n * Program entry point.\n */\n public static void main(String[] args) {\n // DB seeding\n LOGGER.info(\"Db seeding: \" + \"1 user: {\\\"ignite1771\\\", amount = 1000.0}, \"\n + \"2 products: {\\\"computer\\\": price = 800.0, \\\"car\\\": price = 20000.0}\");\n- Db.getInstance().seedUser(\"ignite1771\", 1000.0);\n- Db.getInstance().seedItem(\"computer\", 800.0);\n- Db.getInstance().seedItem(\"car\", 20000.0);\n+ Db.getInstance().seedUser(TEST_USER_1, 1000.0);\n+ Db.getInstance().seedItem(ITEM_COMPUTER, 800.0);\n+ Db.getInstance().seedItem(ITEM_CAR, 20000.0);\n \n final var applicationServices = new ApplicationServicesImpl();\n ReceiptViewModel receipt;\n \n- LOGGER.info(\"[REQUEST] User: \" + \"abc123\" + \" buy product: \" + \"tv\");\n- receipt = applicationServices.loggedInUserPurchase(\"abc123\", \"tv\");\n+ LOGGER.info(LOGGER_STRING, TEST_USER_2, ITEM_TV);\n+ receipt = applicationServices.loggedInUserPurchase(TEST_USER_2, ITEM_TV);\n receipt.show();\n MaintenanceLock.getInstance().setLock(false);\n- LOGGER.info(\"[REQUEST] User: \" + \"abc123\" + \" buy product: \" + \"tv\");\n- receipt = applicationServices.loggedInUserPurchase(\"abc123\", \"tv\");\n+ LOGGER.info(LOGGER_STRING, TEST_USER_2, ITEM_TV);\n+ receipt = applicationServices.loggedInUserPurchase(TEST_USER_2, ITEM_TV);\n receipt.show();\n- LOGGER.info(\"[REQUEST] User: \" + \"ignite1771\" + \" buy product: \" + \"tv\");\n- receipt = applicationServices.loggedInUserPurchase(\"ignite1771\", \"tv\");\n+ LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_TV);\n+ receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_TV);\n receipt.show();\n- LOGGER.info(\"[REQUEST] User: \" + \"ignite1771\" + \" buy product: \" + \"car\");\n- receipt = applicationServices.loggedInUserPurchase(\"ignite1771\", \"car\");\n+ LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_CAR);\n+ receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_CAR);\n receipt.show();\n- LOGGER.info(\"[REQUEST] User: \" + \"ignite1771\" + \" buy product: \" + \"computer\");\n- receipt = applicationServices.loggedInUserPurchase(\"ignite1771\", \"computer\");\n+ LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_COMPUTER);\n+ receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_COMPUTER);\n receipt.show();\n }\n }",
"filename": "special-case/src/main/java/com/iluwatar/specialcase/App.java",
"status": "modified"
}
]
} |
{
"body": "The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n\r\nLinks:\r\n[Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n[Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n***\r\n\r\nNote: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036) \r\n",
"comments": [
{
"body": "Can I take this issue?",
"created_at": "2019-10-17T23:05:00Z"
},
{
"body": "Sure @ykayacan ",
"created_at": "2019-10-18T05:46:37Z"
},
{
"body": "This issue is free for taking again.",
"created_at": "2020-06-14T19:45:29Z"
},
{
"body": "I would like to take this issue.",
"created_at": "2020-08-15T09:50:12Z"
},
{
"body": "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.",
"created_at": "2020-08-15T11:04:11Z"
},
{
"body": "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.",
"created_at": "2020-08-15T17:57:51Z"
},
{
"body": "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.",
"created_at": "2020-08-15T18:04:22Z"
},
{
"body": "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL",
"created_at": "2020-08-22T10:44:20Z"
},
{
"body": "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list",
"created_at": "2020-08-22T10:58:00Z"
},
{
"body": "@iluwatar happy to be back again :)\r\nCan I help with this issue?",
"created_at": "2020-10-02T12:19:00Z"
},
{
"body": "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL",
"created_at": "2020-10-12T01:07:28Z"
},
{
"body": "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!",
"created_at": "2020-11-08T16:48:52Z"
},
{
"body": "@iluwatar Can I help with this issue?",
"created_at": "2020-12-14T09:34:32Z"
},
{
"body": "Sure if @anuragagarwal561994 is no longer working on it?",
"created_at": "2020-12-14T18:29:04Z"
},
{
"body": "No @iluwatar I didn't get time to look into this, you can re-assign",
"created_at": "2020-12-16T12:52:35Z"
},
{
"body": "@iluwatar I will start working on it ",
"created_at": "2020-12-17T05:40:24Z"
},
{
"body": "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go",
"created_at": "2021-01-13T19:50:49Z"
},
{
"body": "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?",
"created_at": "2021-04-01T16:09:51Z"
},
{
"body": "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ",
"created_at": "2021-04-01T16:23:27Z"
},
{
"body": "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!",
"created_at": "2021-04-01T16:57:30Z"
},
{
"body": "Thank you. I'm going to begin with this.",
"created_at": "2021-04-01T17:06:25Z"
},
{
"body": "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"created_at": "2021-04-01T22:19:12Z"
},
{
"body": "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.",
"created_at": "2021-04-02T15:50:32Z"
},
{
"body": "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)",
"created_at": "2021-04-07T21:28:09Z"
},
{
"body": "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n",
"created_at": "2021-04-07T23:11:03Z"
},
{
"body": "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n",
"created_at": "2021-04-18T09:48:58Z"
},
{
"body": "@iluwatar Thank you! ",
"created_at": "2021-04-23T13:17:34Z"
},
{
"body": "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER",
"created_at": "2021-06-07T01:32:16Z"
},
{
"body": "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.",
"created_at": "2021-06-07T14:48:38Z"
},
{
"body": "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ",
"created_at": "2021-06-07T16:46:24Z"
}
],
"number": 1012,
"title": "SonarCloud reports issues"
} | {
"body": "CRITICAL Sonar issue fix for duplicate string fixes #1012 \r\n\r\nPull request description\r\nReplaced multiple occurrences of string with constant field.\r\n\r\n\r\n> For detailed contributing instructions see https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute\r\n",
"number": 2175,
"review_comments": [],
"title": "CRITICAL Sonar issue fix for duplicate string fixes #1012"
} | {
"commits": [
{
"message": "Sonar issue fix for duplicate string"
}
],
"files": [
{
"diff": "@@ -38,6 +38,7 @@\n */\n \n public final class AppServlet extends HttpServlet {\n+ private static final String CONTENT_TYPE = \"text/html\";\n private String msgPartOne = \"<h1>This Server Doesn't Support\";\n private String msgPartTwo = \"Requests</h1>\\n\"\n + \"<h2>Use a GET request with boolean values for the following parameters<h2>\\n\"\n@@ -61,7 +62,7 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp)\n @Override\n public void doPost(HttpServletRequest req, HttpServletResponse resp)\n throws ServletException, IOException {\n- resp.setContentType(\"text/html\");\n+ resp.setContentType(CONTENT_TYPE);\n try (PrintWriter out = resp.getWriter()) {\n out.println(msgPartOne + \" Post \" + msgPartTwo);\n }\n@@ -71,7 +72,7 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp)\n @Override\n public void doDelete(HttpServletRequest req, HttpServletResponse resp)\n throws ServletException, IOException {\n- resp.setContentType(\"text/html\");\n+ resp.setContentType(CONTENT_TYPE);\n try (PrintWriter out = resp.getWriter()) {\n out.println(msgPartOne + \" Delete \" + msgPartTwo);\n }\n@@ -80,7 +81,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp)\n @Override\n public void doPut(HttpServletRequest req, HttpServletResponse resp)\n throws ServletException, IOException {\n- resp.setContentType(\"text/html\");\n+ resp.setContentType(CONTENT_TYPE);\n try (PrintWriter out = resp.getWriter()) {\n out.println(msgPartOne + \" Put \" + msgPartTwo);\n }",
"filename": "composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java",
"status": "modified"
}
]
} |
{
"body": "The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n\r\nLinks:\r\n[Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n[Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n***\r\n\r\nNote: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036) \r\n",
"comments": [
{
"body": "Can I take this issue?",
"created_at": "2019-10-17T23:05:00Z"
},
{
"body": "Sure @ykayacan ",
"created_at": "2019-10-18T05:46:37Z"
},
{
"body": "This issue is free for taking again.",
"created_at": "2020-06-14T19:45:29Z"
},
{
"body": "I would like to take this issue.",
"created_at": "2020-08-15T09:50:12Z"
},
{
"body": "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.",
"created_at": "2020-08-15T11:04:11Z"
},
{
"body": "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.",
"created_at": "2020-08-15T17:57:51Z"
},
{
"body": "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.",
"created_at": "2020-08-15T18:04:22Z"
},
{
"body": "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL",
"created_at": "2020-08-22T10:44:20Z"
},
{
"body": "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list",
"created_at": "2020-08-22T10:58:00Z"
},
{
"body": "@iluwatar happy to be back again :)\r\nCan I help with this issue?",
"created_at": "2020-10-02T12:19:00Z"
},
{
"body": "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL",
"created_at": "2020-10-12T01:07:28Z"
},
{
"body": "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!",
"created_at": "2020-11-08T16:48:52Z"
},
{
"body": "@iluwatar Can I help with this issue?",
"created_at": "2020-12-14T09:34:32Z"
},
{
"body": "Sure if @anuragagarwal561994 is no longer working on it?",
"created_at": "2020-12-14T18:29:04Z"
},
{
"body": "No @iluwatar I didn't get time to look into this, you can re-assign",
"created_at": "2020-12-16T12:52:35Z"
},
{
"body": "@iluwatar I will start working on it ",
"created_at": "2020-12-17T05:40:24Z"
},
{
"body": "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go",
"created_at": "2021-01-13T19:50:49Z"
},
{
"body": "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?",
"created_at": "2021-04-01T16:09:51Z"
},
{
"body": "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ",
"created_at": "2021-04-01T16:23:27Z"
},
{
"body": "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!",
"created_at": "2021-04-01T16:57:30Z"
},
{
"body": "Thank you. I'm going to begin with this.",
"created_at": "2021-04-01T17:06:25Z"
},
{
"body": "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"created_at": "2021-04-01T22:19:12Z"
},
{
"body": "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.",
"created_at": "2021-04-02T15:50:32Z"
},
{
"body": "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)",
"created_at": "2021-04-07T21:28:09Z"
},
{
"body": "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n",
"created_at": "2021-04-07T23:11:03Z"
},
{
"body": "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n",
"created_at": "2021-04-18T09:48:58Z"
},
{
"body": "@iluwatar Thank you! ",
"created_at": "2021-04-23T13:17:34Z"
},
{
"body": "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER",
"created_at": "2021-06-07T01:32:16Z"
},
{
"body": "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.",
"created_at": "2021-06-07T14:48:38Z"
},
{
"body": "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ",
"created_at": "2021-06-07T16:46:24Z"
}
],
"number": 1012,
"title": "SonarCloud reports issues"
} | {
"body": "This removes at least 125 code smells of severity info.\r\n\r\nhttps://sonarcloud.io/organizations/iluwatar/rules?open=java%3AS5786&rule_key=java%3AS5786\r\n\r\nFix some code smells #1012 ",
"number": 2159,
"review_comments": [],
"title": "Refactor: remove code smell java:S5786"
} | {
"commits": [
{
"message": "refactor: remove code smell java:S5786\n\nhttps://sonarcloud.io/organizations/iluwatar/rules?open=java%3AS5786&rule_key=java%3AS5786"
}
],
"files": [
{
"diff": "@@ -74,7 +74,7 @@ void testVisitForHayes() {\n \n @BeforeEach\n @AfterEach\n- public void clearLoggers() {\n+ void clearLoggers() {\n TestLoggerFactory.clear();\n }\n }",
"filename": "acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitorTest.java",
"status": "modified"
},
{
"diff": "@@ -44,7 +44,7 @@ class ConfigureForUnixVisitorTest {\n \n @BeforeEach\n @AfterEach\n- public void clearLoggers() {\n+ void clearLoggers() {\n TestLoggerFactory.clear();\n }\n ",
"filename": "acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitorTest.java",
"status": "modified"
},
{
"diff": "@@ -48,7 +48,7 @@ class AdapterPatternTest {\n * This method runs before the test execution and sets the bean objects in the beans Map.\n */\n @BeforeEach\n- public void setup() {\n+ void setup() {\n beans = new HashMap<>();\n \n var fishingBoatAdapter = spy(new FishingBoatAdapter());",
"filename": "adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java",
"status": "modified"
},
{
"diff": "@@ -48,7 +48,7 @@ class AggregatorTest {\n private ProductInventoryClient inventoryClient;\n \n @BeforeEach\n- public void setup() {\n+ void setup() {\n MockitoAnnotations.openMocks(this);\n }\n ",
"filename": "aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java",
"status": "modified"
},
{
"diff": "@@ -48,7 +48,7 @@ class ApiGatewayTest {\n private PriceClient priceClient;\n \n @BeforeEach\n- public void setup() {\n+ void setup() {\n MockitoAnnotations.openMocks(this);\n }\n ",
"filename": "api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java",
"status": "modified"
},
{
"diff": "@@ -49,7 +49,7 @@ class BusinessDelegateTest {\n * execution of every test.\n */\n @BeforeEach\n- public void setup() {\n+ void setup() {\n netflixService = spy(new NetflixService());\n youTubeService = spy(new YouTubeService());\n ",
"filename": "business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java",
"status": "modified"
},
{
"diff": "@@ -39,7 +39,7 @@ class CachingTest {\n * Setup of application test includes: initializing DB connection and cache size/capacity.\n */\n @BeforeEach\n- public void setUp() {\n+ void setUp() {\n // VirtualDB (instead of MongoDB) was used in running the JUnit tests\n // to avoid Maven compilation errors. Set flag to true to run the\n // tests with MongoDB (provided that MongoDB is installed and socket",
"filename": "caching/src/test/java/com/iluwatar/caching/CachingTest.java",
"status": "modified"
},
{
"diff": "@@ -34,7 +34,7 @@\n * <p>\n * Could be done with mock objects as well where the call method call is verified.\n */\n-public class CallbackTest {\n+class CallbackTest {\n \n private Integer callingCount = 0;\n ",
"filename": "callback/src/test/java/com/iluwatar/callback/CallbackTest.java",
"status": "modified"
},
{
"diff": "@@ -34,7 +34,7 @@\n /**\n * App Test showing usage of circuit breaker.\n */\n-public class AppTest {\n+class AppTest {\n \n private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class);\n \n@@ -60,7 +60,7 @@ public class AppTest {\n * and retry time period of 2 seconds.\n */\n @BeforeEach\n- public void setupCircuitBreakers() {\n+ void setupCircuitBreakers() {\n var delayedService = new DelayedRemoteService(System.nanoTime(), STARTUP_DELAY);\n //Set the circuit Breaker parameters\n delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000,\n@@ -78,7 +78,7 @@ public void setupCircuitBreakers() {\n }\n \n @Test\n- public void testFailure_OpenStateTransition() {\n+ void testFailure_OpenStateTransition() {\n //Calling delayed service, which will be unhealthy till 4 seconds\n assertEquals(\"Delayed service is down\", monitoringService.delayedServiceResponse());\n //As failure threshold is \"1\", the circuit breaker is changed to OPEN\n@@ -93,7 +93,7 @@ public void testFailure_OpenStateTransition() {\n }\n \n @Test\n- public void testFailure_HalfOpenStateTransition() {\n+ void testFailure_HalfOpenStateTransition() {\n //Calling delayed service, which will be unhealthy till 4 seconds\n assertEquals(\"Delayed service is down\", monitoringService.delayedServiceResponse());\n //As failure threshold is \"1\", the circuit breaker is changed to OPEN\n@@ -112,7 +112,7 @@ public void testFailure_HalfOpenStateTransition() {\n }\n \n @Test\n- public void testRecovery_ClosedStateTransition() {\n+ void testRecovery_ClosedStateTransition() {\n //Calling delayed service, which will be unhealthy till 4 seconds\n assertEquals(\"Delayed service is down\", monitoringService.delayedServiceResponse());\n //As failure threshold is \"1\", the circuit breaker is changed to OPEN",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/AppTest.java",
"status": "modified"
},
{
"diff": "@@ -32,7 +32,7 @@\n /**\n * Circuit Breaker test\n */\n-public class DefaultCircuitBreakerTest {\n+class DefaultCircuitBreakerTest {\n \n //long timeout, int failureThreshold, long retryTimePeriod\n @Test",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java",
"status": "modified"
},
{
"diff": "@@ -53,7 +53,7 @@ void testDefaultConstructor() throws RemoteServiceException {\n * @throws RemoteServiceException\n */\n @Test\n- public void testParameterizedConstructor() throws RemoteServiceException {\n+ void testParameterizedConstructor() throws RemoteServiceException {\n var obj = new DelayedRemoteService(System.nanoTime()-2000*1000*1000,1);\n assertEquals(\"Delayed service is working\",obj.call());\n }",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DelayedRemoteServiceTest.java",
"status": "modified"
},
{
"diff": "@@ -58,7 +58,7 @@\n * Unit test for Function class.\n */\n @ExtendWith(MockitoExtension.class)\n-public class UsageCostProcessorFunctionTest {\n+class UsageCostProcessorFunctionTest {\n \n @Mock\n MessageHandlerUtility<UsageDetail> mockMessageHandlerUtilityForUsageADetail;\n@@ -74,7 +74,7 @@ public class UsageCostProcessorFunctionTest {\n UsageCostProcessorFunction usageCostProcessorFunction;\n \n @BeforeEach\n- public void setUp() {\n+ void setUp() {\n var messageBodyUsageDetail = new MessageBody<UsageDetail>();\n var usageDetailsList = new ArrayList<UsageDetail>();\n \n@@ -122,7 +122,7 @@ public void setUp() {\n * Unit test for HttpTriggerJava method.\n */\n @Test\n- public void shouldTriggerHttpAzureFunctionJavaWithSubscriptionValidationEventType() throws Exception {\n+ void shouldTriggerHttpAzureFunctionJavaWithSubscriptionValidationEventType() throws Exception {\n \n // Setup\n @SuppressWarnings(\"unchecked\")\n@@ -148,7 +148,7 @@ public HttpResponseMessage.Builder answer(InvocationOnMock invocation) {\n }\n \n @Test\n- public void shouldTriggerHttpAzureFunctionJavaWithUsageDetailEventType() throws Exception {\n+ void shouldTriggerHttpAzureFunctionJavaWithUsageDetailEventType() throws Exception {\n // Setup\n @SuppressWarnings(\"unchecked\")\n final HttpRequestMessage<Optional<String>> req = mock(HttpRequestMessage.class);",
"filename": "cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/consumer/callcostprocessor/functions/UsageCostProcessorFunctionTest.java",
"status": "modified"
},
{
"diff": "@@ -52,7 +52,7 @@\n * Unit test for Function class.\n */\n @ExtendWith(MockitoExtension.class)\n-public class UsageDetailPublisherFunctionTest {\n+class UsageDetailPublisherFunctionTest {\n @Mock\n MessageHandlerUtility<UsageDetail> mockMessageHandlerUtility;\n @Mock\n@@ -65,7 +65,7 @@ public class UsageDetailPublisherFunctionTest {\n * Unit test for HttpTriggerJava method.\n */\n @Test\n- public void shouldTriggerHttpAzureFunctionJavaWithSubscriptionValidationEventType() throws Exception {\n+ void shouldTriggerHttpAzureFunctionJavaWithSubscriptionValidationEventType() throws Exception {\n \n // Setup\n @SuppressWarnings(\"unchecked\")\n@@ -91,7 +91,7 @@ public HttpResponseMessage.Builder answer(InvocationOnMock invocation) {\n }\n \n @Test\n- public void shouldTriggerHttpAzureFunctionJavaWithUsageDetailEventType() throws Exception {\n+ void shouldTriggerHttpAzureFunctionJavaWithUsageDetailEventType() throws Exception {\n \n // Setup\n @SuppressWarnings(\"unchecked\")",
"filename": "cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/producer/calldetails/functions/UsageDetailPublisherFunctionTest.java",
"status": "modified"
},
{
"diff": "@@ -40,7 +40,7 @@\n import org.mockito.junit.jupiter.MockitoExtension;\n \n @ExtendWith(MockitoExtension.class)\n-public class EventHandlerUtilityTest {\n+class EventHandlerUtilityTest {\n \n @Mock\n EventGridPublisherClient<BinaryData> mockCustomEventClient;\n@@ -49,7 +49,7 @@ public class EventHandlerUtilityTest {\n EventHandlerUtility<Message<UsageDetail>> eventHandlerUtility;\n \n @BeforeEach\n- public void setUp() {\n+ void setUp() {\n \n System.setProperty(\"EventGridURL\", \"https://www.dummyEndpoint.com/api/events\");\n System.setProperty(\"EventGridKey\", \"EventGridURL\");",
"filename": "cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/utility/EventHandlerUtilityTest.java",
"status": "modified"
},
{
"diff": "@@ -46,7 +46,7 @@\n import static org.mockito.Mockito.*;\n \n @ExtendWith(MockitoExtension.class)\n-public class MessageHandlerUtilityTest {\n+class MessageHandlerUtilityTest {\n @Mock\n private BlobClient mockBlobClient;\n \n@@ -63,7 +63,7 @@ public class MessageHandlerUtilityTest {\n private MessageReference messageReference;\n \n @BeforeEach\n- public void setUp() {\n+ void setUp() {\n System.setProperty(\"BlobStorageConnectionString\", \"https://www.dummyEndpoint.com/api/blobs\");\n \n var messageBody = new MessageBody<UsageDetail>();",
"filename": "cloud-claim-check-pattern/call-usage-app/src/test/java/com/iluwatar/claimcheckpattern/utility/MessageHandlerUtilityTest.java",
"status": "modified"
},
{
"diff": "@@ -39,15 +39,15 @@\n and https://stackoverflow.com/questions/50211433/servlets-unit-testing\n */\n \n-public class AppServletTest extends Mockito{\n+class AppServletTest extends Mockito{\n private String msgPartOne = \"<h1>This Server Doesn't Support\";\n private String msgPartTwo = \"Requests</h1>\\n\"\n + \"<h2>Use a GET request with boolean values for the following parameters<h2>\\n\"\n + \"<h3>'name'</h3>\\n<h3>'bus'</h3>\\n<h3>'sports'</h3>\\n<h3>'sci'</h3>\\n<h3>'world'</h3>\";\n private String destination = \"newsDisplay.jsp\";\n \n @Test\n- public void testDoGet() throws Exception {\n+ void testDoGet() throws Exception {\n HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);\n HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);\n RequestDispatcher mockDispatcher = Mockito.mock(RequestDispatcher.class);\n@@ -64,7 +64,7 @@ public void testDoGet() throws Exception {\n }\n \n @Test\n- public void testDoPost() throws Exception {\n+ void testDoPost() throws Exception {\n HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);\n HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);\n StringWriter stringWriter = new StringWriter();\n@@ -78,7 +78,7 @@ public void testDoPost() throws Exception {\n }\n \n @Test\n- public void testDoPut() throws Exception {\n+ void testDoPut() throws Exception {\n HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);\n HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);\n StringWriter stringWriter = new StringWriter();\n@@ -92,7 +92,7 @@ public void testDoPut() throws Exception {\n }\n \n @Test\n- public void testDoDelete() throws Exception {\n+ void testDoDelete() throws Exception {\n HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);\n HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);\n StringWriter stringWriter = new StringWriter();",
"filename": "composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java",
"status": "modified"
},
{
"diff": "@@ -30,9 +30,9 @@\n \n import static org.junit.Assert.*;\n \n-public class JavaBeansTest {\n+class JavaBeansTest {\n @Test\n- public void testDefaultConstructor() {\n+ void testDefaultConstructor() {\n ClientPropertiesBean newBean = new ClientPropertiesBean();\n assertEquals(\"DEFAULT_NAME\", newBean.getName());\n assertTrue(newBean.isBusinessInterest());\n@@ -43,47 +43,47 @@ public void testDefaultConstructor() {\n }\n \n @Test\n- public void testNameGetterSetter() {\n+ void testNameGetterSetter() {\n ClientPropertiesBean newBean = new ClientPropertiesBean();\n assertEquals(\"DEFAULT_NAME\", newBean.getName());\n newBean.setName(\"TEST_NAME_ONE\");\n assertEquals(\"TEST_NAME_ONE\", newBean.getName());\n }\n \n @Test\n- public void testBusinessSetterGetter() {\n+ void testBusinessSetterGetter() {\n ClientPropertiesBean newBean = new ClientPropertiesBean();\n assertTrue(newBean.isBusinessInterest());\n newBean.setBusinessInterest(false);\n assertFalse(newBean.isBusinessInterest());\n }\n \n @Test\n- public void testScienceSetterGetter() {\n+ void testScienceSetterGetter() {\n ClientPropertiesBean newBean = new ClientPropertiesBean();\n assertTrue(newBean.isScienceNewsInterest());\n newBean.setScienceNewsInterest(false);\n assertFalse(newBean.isScienceNewsInterest());\n }\n \n @Test\n- public void testSportsSetterGetter() {\n+ void testSportsSetterGetter() {\n ClientPropertiesBean newBean = new ClientPropertiesBean();\n assertTrue(newBean.isSportsInterest());\n newBean.setSportsInterest(false);\n assertFalse(newBean.isSportsInterest());\n }\n \n @Test\n- public void testWorldSetterGetter() {\n+ void testWorldSetterGetter() {\n ClientPropertiesBean newBean = new ClientPropertiesBean();\n assertTrue(newBean.isWorldNewsInterest());\n newBean.setWorldNewsInterest(false);\n assertFalse(newBean.isWorldNewsInterest());\n }\n \n @Test\n- public void testRequestConstructor(){\n+ void testRequestConstructor(){\n HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);\n ClientPropertiesBean newBean = new ClientPropertiesBean((mockReq));\n assertEquals(\"DEFAULT_NAME\", newBean.getName());",
"filename": "composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java",
"status": "modified"
},
{
"diff": "@@ -70,15 +70,15 @@ void createSchema() throws SQLException {\n * Represents the scenario where DB connectivity is present.\n */\n @Nested\n- public class ConnectionSuccess {\n+ class ConnectionSuccess {\n \n /**\n * Setup for connection success scenario.\n *\n * @throws Exception if any error occurs.\n */\n @BeforeEach\n- public void setUp() throws Exception {\n+ void setUp() throws Exception {\n var dataSource = new JdbcDataSource();\n dataSource.setURL(DB_URL);\n dao = new DbCustomerDao(dataSource);\n@@ -191,7 +191,7 @@ class ConnectivityIssue {\n * @throws SQLException if any error occurs.\n */\n @BeforeEach\n- public void setUp() throws SQLException {\n+ void setUp() throws SQLException {\n dao = new DbCustomerDao(mockedDatasource());\n }\n ",
"filename": "dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java",
"status": "modified"
},
{
"diff": "@@ -34,7 +34,7 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class ContentTest {\n+class ContentTest {\n \n @Test\n void testToString() {",
"filename": "flux/src/test/java/com/iluwatar/flux/action/ContentTest.java",
"status": "modified"
},
{
"diff": "@@ -34,7 +34,7 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class MenuItemTest {\n+class MenuItemTest {\n \n @Test\n void testToString() {",
"filename": "flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java",
"status": "modified"
},
{
"diff": "@@ -49,15 +49,15 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class DispatcherTest {\n+class DispatcherTest {\n \n /**\n * Dispatcher is a singleton with no way to reset it's internal state back to the beginning.\n * Replace the instance with a fresh one before each test to make sure test cases have no\n * influence on each other.\n */\n @BeforeEach\n- public void setUp() throws Exception {\n+ void setUp() throws Exception {\n final var constructor = Dispatcher.class.getDeclaredConstructor();\n constructor.setAccessible(true);\n ",
"filename": "flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java",
"status": "modified"
},
{
"diff": "@@ -44,7 +44,7 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class ContentStoreTest {\n+class ContentStoreTest {\n \n @Test\n void testOnAction() {",
"filename": "flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java",
"status": "modified"
},
{
"diff": "@@ -44,7 +44,7 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class MenuStoreTest {\n+class MenuStoreTest {\n \n @Test\n void testOnAction() {",
"filename": "flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java",
"status": "modified"
},
{
"diff": "@@ -39,7 +39,7 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class ContentViewTest {\n+class ContentViewTest {\n \n @Test\n void testStoreChanged() {",
"filename": "flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java",
"status": "modified"
},
{
"diff": "@@ -43,7 +43,7 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class MenuViewTest {\n+class MenuViewTest {\n \n @Test\n void testStoreChanged() {",
"filename": "flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java",
"status": "modified"
},
{
"diff": "@@ -35,7 +35,7 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class AlchemistShopTest {\n+class AlchemistShopTest {\n \n @Test\n void testShop() {",
"filename": "flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java",
"status": "modified"
},
{
"diff": "@@ -33,7 +33,7 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class ApplicationExceptionTest {\n+class ApplicationExceptionTest {\n \n @Test\n void testCause() {",
"filename": "front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java",
"status": "modified"
},
{
"diff": "@@ -38,17 +38,17 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class CommandTest {\n+class CommandTest {\n \n private InMemoryAppender appender;\n \n @BeforeEach\n- public void setUp() {\n+ void setUp() {\n appender = new InMemoryAppender();\n }\n \n @AfterEach\n- public void tearDown() {\n+ void tearDown() {\n appender.stop();\n }\n \n@@ -66,7 +66,7 @@ static List<Object[]> dataProvider() {\n */\n @ParameterizedTest\n @MethodSource(\"dataProvider\")\n- public void testDisplay(String request, String displayMessage) {\n+ void testDisplay(String request, String displayMessage) {\n final var frontController = new FrontController();\n assertEquals(0, appender.getLogSize());\n frontController.handleRequest(request);",
"filename": "front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java",
"status": "modified"
},
{
"diff": "@@ -38,17 +38,17 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class FrontControllerTest {\n+class FrontControllerTest {\n \n private InMemoryAppender appender;\n \n @BeforeEach\n- public void setUp() {\n+ void setUp() {\n appender = new InMemoryAppender();\n }\n \n @AfterEach\n- public void tearDown() {\n+ void tearDown() {\n appender.stop();\n }\n \n@@ -66,7 +66,7 @@ static List<Object[]> dataProvider() {\n */\n @ParameterizedTest\n @MethodSource(\"dataProvider\")\n- public void testDisplay(Command command, String displayMessage) {\n+ void testDisplay(Command command, String displayMessage) {\n assertEquals(0, appender.getLogSize());\n command.process();\n assertEquals(displayMessage, appender.getLastMessage());",
"filename": "front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java",
"status": "modified"
},
{
"diff": "@@ -38,17 +38,17 @@\n *\n * @author Jeroen Meulemeester\n */\n-public class ViewTest {\n+class ViewTest {\n \n private InMemoryAppender appender;\n \n @BeforeEach\n- public void setUp() {\n+ void setUp() {\n appender = new InMemoryAppender();\n }\n \n @AfterEach\n- public void tearDown() {\n+ void tearDown() {\n appender.stop();\n }\n \n@@ -66,7 +66,7 @@ static List<Object[]> dataProvider() {\n */\n @ParameterizedTest\n @MethodSource(\"dataProvider\")\n- public void testDisplay(View view, String displayMessage) {\n+ void testDisplay(View view, String displayMessage) {\n assertEquals(0, appender.getLogSize());\n view.display();\n assertEquals(displayMessage, appender.getLastMessage());",
"filename": "front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java",
"status": "modified"
}
]
} |
{
"body": "I use hibernate and h2 inherited from the parent pom.xml whose version are `5.2.18.Final`.\r\nBut I find the `org.hibernate.dialect.H2Dialect` extends from `org.hibernate.dialect.Dialect` didn't override method `getCurrentSchemaCommand`, which leeds it reture `null`.\r\nThen I received an exception when I use hibernate to connect h2database:\r\n```bash\r\norg.hibernate.HibernateException: Use of DefaultSchemaNameResolver requires Dialect to provide the proper SQL statement/command but provided Dialect [org.hibernate.dialect.H2Dialect] did not return anything from Dialect#getCurrentSchemaCommand\r\n\tat org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver$SchemaNameResolverFallbackDelegate.resolveSchemaName(DefaultSchemaNameResolver.java:100)\r\n\tat org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver.resolveSchemaName(DefaultSchemaNameResolver.java:76)\r\n......\r\n```\r\nIt occurs becaus \r\n```bash\r\npublic String resolveSchemaName(Connection connection, Dialect dialect) throws SQLException {\r\n\tfinal String command = dialect.getCurrentSchemaCommand();\r\n\tif ( command == null ) {\r\n\t\tthrow new HibernateException(\r\n\t\t\t\t\"Use of DefaultSchemaNameResolver requires Dialect to provide the \" +\r\n\t\t\t\t\t\t\"proper SQL statement/command but provided Dialect [\" +\r\n\t\t\t\t\t\tdialect.getClass().getName() + \"] did not return anything \" +\r\n\t\t\t\t\t\t\"from Dialect#getCurrentSchemaCommand\"\r\n\t\t);\r\n\t}\r\n ......\r\n}\r\n```\r\nbut the code can run successfully for some reasons. you can reproduce this case in my [code](https://github.com/castleKing1997/java-design-patterns/tree/master/metadata-mapping)\r\nIs is necessary to fix it?\r\nMaybe a new version of hibernate?",
"comments": [
{
"body": "Hi, I'd like to work on this issue. Could it be assigned to me if still available?",
"created_at": "2022-04-23T16:29:21Z"
},
{
"body": "Thanks @Linly1080, please go ahead",
"created_at": "2022-09-10T12:24:00Z"
},
{
"body": "@iluwatar sorry, I have no time to do the work now.",
"created_at": "2022-09-17T03:56:05Z"
},
{
"body": "The issue is still present in 5.4.24. To verify, run `com.iluwatar.metamapping.AppTest` and look for\r\n```\r\norg.hibernate.HibernateException: Use of DefaultSchemaNameResolver requires Dialect to provide the proper SQL statement/command but provided Dialect [org.hibernate.dialect.H2Dialect] did not return anything from Dialect#getCurrentSchemaCommand\r\n\tat org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver$SchemaNameResolverFallbackDelegate.resolveSchemaName(DefaultSchemaNameResolver.java:100)\r\n\tat org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver.resolveSchemaName(DefaultSchemaNameResolver.java:76)\r\n```",
"created_at": "2022-10-24T16:52:53Z"
},
{
"body": "We would get rid of the HibernateException by implementing a custom SchemaNameResolver\r\n```\r\nBy default, Hibernate uses the [org.hibernate.dialect.Dialect#getSchemaNameResolver](https://docs.jboss.org/hibernate/orm/5.4/javadocs/org/hibernate/dialect/Dialect.html#getSchemaNameResolver--). You can customize how the schema name is resolved by providing a custom implementation of the [SchemaNameResolver](https://docs.jboss.org/hibernate/orm/5.4/javadocs/org/hibernate/engine/jdbc/env/spi/SchemaNameResolver.html) interface.\r\n```\r\n\r\nhttps://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#_table_qualifying_options",
"created_at": "2022-10-24T17:57:57Z"
},
{
"body": "I advise closing this issue because it is only a strange error message from some weird internal Hibernate implementation. You will see a similar exception for all MySQLDialects because MySQL doesn't support schemas.",
"created_at": "2022-10-24T18:05:54Z"
}
],
"number": 1929,
"title": "Hibernate of current version doesn't match h2"
} | {
"body": "I switched to log level info to suppress logging of hibernate internals by reusing the `logback.xml` from Maven project `cqrs`.\r\n\r\nFix #1929 ",
"number": 2158,
"review_comments": [],
"title": "Fix #1929: Suppress logging hibernate internals"
} | {
"commits": [
{
"message": "chore: suppress logging of hibernate internals"
},
{
"message": "chore: use non-obsolete hibernate namespace"
}
],
"files": [
{
"diff": "@@ -107,7 +107,7 @@ We use `Hibernate` to resolve the mapping and connect to our database, here's it\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n <!DOCTYPE hibernate-configuration PUBLIC\n \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\n- \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\n+ \"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd\">\n <hibernate-configuration>\n <session-factory>\n <!-- JDBC Database connection settings -->",
"filename": "metadata-mapping/README.md",
"status": "modified"
},
{
"diff": "@@ -1,7 +1,7 @@\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n <!DOCTYPE hibernate-configuration PUBLIC\n \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\n- \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\n+ \"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd\">\n <hibernate-configuration>\n <session-factory>\n <!-- JDBC Database connection settings -->",
"filename": "metadata-mapping/src/main/resources/hibernate.cfg.xml",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,35 @@\n+<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n+<!--\n+\n+ The MIT License\n+ Copyright © 2014-2022 Ilkka Seppälä\n+\n+ Permission is hereby granted, free of charge, to any person obtaining a copy\n+ of this software and associated documentation files (the \"Software\"), to deal\n+ in the Software without restriction, including without limitation the rights\n+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ copies of the Software, and to permit persons to whom the Software is\n+ furnished to do so, subject to the following conditions:\n+\n+ The above copyright notice and this permission notice shall be included in\n+ all copies or substantial portions of the Software.\n+\n+ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ THE SOFTWARE.\n+\n+-->\n+<configuration>\n+ <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n+ <encoder>\n+ <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>\n+ </encoder>\n+ </appender>\n+ <root level=\"info\">\n+ <appender-ref ref=\"STDOUT\" />\n+ </root>\n+</configuration>",
"filename": "metadata-mapping/src/main/resources/logback.xml",
"status": "added"
}
]
} |
{
"body": "The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n\r\nLinks:\r\n[Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n[Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n***\r\n\r\nNote: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036) \r\n",
"comments": [
{
"body": "Can I take this issue?",
"created_at": "2019-10-17T23:05:00Z"
},
{
"body": "Sure @ykayacan ",
"created_at": "2019-10-18T05:46:37Z"
},
{
"body": "This issue is free for taking again.",
"created_at": "2020-06-14T19:45:29Z"
},
{
"body": "I would like to take this issue.",
"created_at": "2020-08-15T09:50:12Z"
},
{
"body": "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.",
"created_at": "2020-08-15T11:04:11Z"
},
{
"body": "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.",
"created_at": "2020-08-15T17:57:51Z"
},
{
"body": "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.",
"created_at": "2020-08-15T18:04:22Z"
},
{
"body": "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL",
"created_at": "2020-08-22T10:44:20Z"
},
{
"body": "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list",
"created_at": "2020-08-22T10:58:00Z"
},
{
"body": "@iluwatar happy to be back again :)\r\nCan I help with this issue?",
"created_at": "2020-10-02T12:19:00Z"
},
{
"body": "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL",
"created_at": "2020-10-12T01:07:28Z"
},
{
"body": "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!",
"created_at": "2020-11-08T16:48:52Z"
},
{
"body": "@iluwatar Can I help with this issue?",
"created_at": "2020-12-14T09:34:32Z"
},
{
"body": "Sure if @anuragagarwal561994 is no longer working on it?",
"created_at": "2020-12-14T18:29:04Z"
},
{
"body": "No @iluwatar I didn't get time to look into this, you can re-assign",
"created_at": "2020-12-16T12:52:35Z"
},
{
"body": "@iluwatar I will start working on it ",
"created_at": "2020-12-17T05:40:24Z"
},
{
"body": "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go",
"created_at": "2021-01-13T19:50:49Z"
},
{
"body": "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?",
"created_at": "2021-04-01T16:09:51Z"
},
{
"body": "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ",
"created_at": "2021-04-01T16:23:27Z"
},
{
"body": "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!",
"created_at": "2021-04-01T16:57:30Z"
},
{
"body": "Thank you. I'm going to begin with this.",
"created_at": "2021-04-01T17:06:25Z"
},
{
"body": "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"created_at": "2021-04-01T22:19:12Z"
},
{
"body": "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.",
"created_at": "2021-04-02T15:50:32Z"
},
{
"body": "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)",
"created_at": "2021-04-07T21:28:09Z"
},
{
"body": "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n",
"created_at": "2021-04-07T23:11:03Z"
},
{
"body": "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n",
"created_at": "2021-04-18T09:48:58Z"
},
{
"body": "@iluwatar Thank you! ",
"created_at": "2021-04-23T13:17:34Z"
},
{
"body": "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER",
"created_at": "2021-06-07T01:32:16Z"
},
{
"body": "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.",
"created_at": "2021-06-07T14:48:38Z"
},
{
"body": "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ",
"created_at": "2021-06-07T16:46:24Z"
}
],
"number": 1012,
"title": "SonarCloud reports issues"
} | {
"body": "Remove deprecated method to ease Hibernate upgrade.\r\nFix the following deprecated method reported by Sonar #1012 in this [link](https://sonarcloud.io/project/issues?fileUuids=AW3G0SexwB6UiZzQNqdf%2CAW3G0SexwB6UiZzQNqdj%2CAW3G0SexwB6UiZzQNqds%2CAW3G0SexwB6UiZzQNqdy&resolved=false&rules=java%3AS1874&id=iluwatar_java-design-patterns).",
"number": 2125,
"review_comments": [],
"title": "refactoring #1012: Remove deprecated method to ease Hibernate upgrade"
} | {
"commits": [
{
"message": "refactoring #1012: Remove deprecated method to ease Hibernate upgrade later on"
},
{
"message": "refactoring #1012: Fix checkstyle violation"
}
],
"files": [
{
"diff": "@@ -27,10 +27,12 @@\n import com.iluwatar.servicelayer.hibernate.HibernateUtil;\n import java.lang.reflect.ParameterizedType;\n import java.util.List;\n-import org.hibernate.Criteria;\n+import javax.persistence.criteria.CriteriaBuilder;\n+import javax.persistence.criteria.CriteriaQuery;\n+import javax.persistence.criteria.Root;\n import org.hibernate.SessionFactory;\n import org.hibernate.Transaction;\n-import org.hibernate.criterion.Restrictions;\n+import org.hibernate.query.Query;\n \n /**\n * Base class for Dao implementations.\n@@ -57,9 +59,12 @@ public E find(Long id) {\n E result;\n try (var session = getSessionFactory().openSession()) {\n tx = session.beginTransaction();\n- var criteria = session.createCriteria(persistentClass);\n- criteria.add(Restrictions.idEq(id));\n- result = (E) criteria.uniqueResult();\n+ CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();\n+ CriteriaQuery<E> builderQuery = criteriaBuilder.createQuery(persistentClass);\n+ Root<E> root = builderQuery.from(persistentClass);\n+ builderQuery.select(root).where(criteriaBuilder.equal(root.get(\"id\"), id));\n+ Query<E> query = session.createQuery(builderQuery);\n+ result = query.uniqueResult();\n tx.commit();\n } catch (Exception e) {\n if (tx != null) {\n@@ -123,8 +128,12 @@ public List<E> findAll() {\n List<E> result;\n try (var session = getSessionFactory().openSession()) {\n tx = session.beginTransaction();\n- Criteria criteria = session.createCriteria(persistentClass);\n- result = criteria.list();\n+ CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();\n+ CriteriaQuery<E> builderQuery = criteriaBuilder.createQuery(persistentClass);\n+ Root<E> root = builderQuery.from(persistentClass);\n+ builderQuery.select(root);\n+ Query<E> query = session.createQuery(builderQuery);\n+ result = query.getResultList();\n } catch (Exception e) {\n if (tx != null) {\n tx.rollback();",
"filename": "service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java",
"status": "modified"
},
{
"diff": "@@ -25,8 +25,12 @@\n package com.iluwatar.servicelayer.spell;\n \n import com.iluwatar.servicelayer.common.DaoBaseImpl;\n+import javax.persistence.criteria.CriteriaBuilder;\n+import javax.persistence.criteria.CriteriaQuery;\n+import javax.persistence.criteria.Root;\n import org.hibernate.Transaction;\n-import org.hibernate.criterion.Restrictions;\n+import org.hibernate.query.Query;\n+\n \n /**\n * SpellDao implementation.\n@@ -39,9 +43,12 @@ public Spell findByName(String name) {\n Spell result;\n try (var session = getSessionFactory().openSession()) {\n tx = session.beginTransaction();\n- var criteria = session.createCriteria(persistentClass);\n- criteria.add(Restrictions.eq(\"name\", name));\n- result = (Spell) criteria.uniqueResult();\n+ CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();\n+ CriteriaQuery<Spell> builderQuery = criteriaBuilder.createQuery(Spell.class);\n+ Root<Spell> root = builderQuery.from(Spell.class);\n+ builderQuery.select(root).where(criteriaBuilder.equal(root.get(\"name\"), name));\n+ Query<Spell> query = session.createQuery(builderQuery);\n+ result = query.uniqueResult();\n tx.commit();\n } catch (Exception e) {\n if (tx != null) {",
"filename": "service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java",
"status": "modified"
},
{
"diff": "@@ -25,8 +25,12 @@\n package com.iluwatar.servicelayer.spellbook;\n \n import com.iluwatar.servicelayer.common.DaoBaseImpl;\n+import javax.persistence.criteria.CriteriaBuilder;\n+import javax.persistence.criteria.CriteriaQuery;\n+import javax.persistence.criteria.Root;\n import org.hibernate.Transaction;\n-import org.hibernate.criterion.Restrictions;\n+import org.hibernate.query.Query;\n+\n \n /**\n * SpellbookDao implementation.\n@@ -39,9 +43,12 @@ public Spellbook findByName(String name) {\n Spellbook result;\n try (var session = getSessionFactory().openSession()) {\n tx = session.beginTransaction();\n- var criteria = session.createCriteria(persistentClass);\n- criteria.add(Restrictions.eq(\"name\", name));\n- result = (Spellbook) criteria.uniqueResult();\n+ CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();\n+ CriteriaQuery<Spellbook> builderQuery = criteriaBuilder.createQuery(Spellbook.class);\n+ Root<Spellbook> root = builderQuery.from(Spellbook.class);\n+ builderQuery.select(root).where(criteriaBuilder.equal(root.get(\"name\"), name));\n+ Query<Spellbook> query = session.createQuery(builderQuery);\n+ result = query.uniqueResult();\n tx.commit();\n } catch (Exception e) {\n if (tx != null) {",
"filename": "service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java",
"status": "modified"
},
{
"diff": "@@ -25,8 +25,11 @@\n package com.iluwatar.servicelayer.wizard;\n \n import com.iluwatar.servicelayer.common.DaoBaseImpl;\n+import javax.persistence.criteria.CriteriaBuilder;\n+import javax.persistence.criteria.CriteriaQuery;\n+import javax.persistence.criteria.Root;\n import org.hibernate.Transaction;\n-import org.hibernate.criterion.Restrictions;\n+import org.hibernate.query.Query;\n \n /**\n * WizardDao implementation.\n@@ -39,9 +42,12 @@ public Wizard findByName(String name) {\n Wizard result;\n try (var session = getSessionFactory().openSession()) {\n tx = session.beginTransaction();\n- var criteria = session.createCriteria(persistentClass);\n- criteria.add(Restrictions.eq(\"name\", name));\n- result = (Wizard) criteria.uniqueResult();\n+ CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();\n+ CriteriaQuery<Wizard> builderQuery = criteriaBuilder.createQuery(Wizard.class);\n+ Root<Wizard> root = builderQuery.from(Wizard.class);\n+ builderQuery.select(root).where(criteriaBuilder.equal(root.get(\"name\"), name));\n+ Query<Wizard> query = session.createQuery(builderQuery);\n+ result = query.uniqueResult();\n tx.commit();\n } catch (Exception e) {\n if (tx != null) {",
"filename": "service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java",
"status": "modified"
},
{
"diff": "@@ -26,11 +26,10 @@\n \n import static org.junit.jupiter.api.Assertions.assertEquals;\n import static org.junit.jupiter.api.Assertions.assertNotNull;\n-import static org.mockito.Matchers.eq;\n import static org.mockito.Mockito.mock;\n import static org.mockito.Mockito.verify;\n+import static org.mockito.Mockito.verifyNoInteractions;\n import static org.mockito.Mockito.verifyNoMoreInteractions;\n-import static org.mockito.Mockito.verifyZeroInteractions;\n import static org.mockito.Mockito.when;\n \n import com.iluwatar.servicelayer.spell.Spell;\n@@ -56,7 +55,7 @@ void testFindAllWizards() {\n final var spellDao = mock(SpellDao.class);\n \n final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao);\n- verifyZeroInteractions(wizardDao, spellbookDao, spellDao);\n+ verifyNoInteractions(wizardDao, spellbookDao, spellDao);\n \n service.findAllWizards();\n verify(wizardDao).findAll();\n@@ -70,7 +69,7 @@ void testFindAllSpellbooks() {\n final var spellDao = mock(SpellDao.class);\n \n final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao);\n- verifyZeroInteractions(wizardDao, spellbookDao, spellDao);\n+ verifyNoInteractions(wizardDao, spellbookDao, spellDao);\n \n service.findAllSpellbooks();\n verify(spellbookDao).findAll();\n@@ -84,7 +83,7 @@ void testFindAllSpells() {\n final var spellDao = mock(SpellDao.class);\n \n final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao);\n- verifyZeroInteractions(wizardDao, spellbookDao, spellDao);\n+ verifyNoInteractions(wizardDao, spellbookDao, spellDao);\n \n service.findAllSpells();\n verify(spellDao).findAll();\n@@ -103,17 +102,17 @@ void testFindWizardsWithSpellbook() {\n when(spellbook.getWizards()).thenReturn(wizards);\n \n final var spellbookDao = mock(SpellbookDao.class);\n- when(spellbookDao.findByName(eq(bookname))).thenReturn(spellbook);\n+ when(spellbookDao.findByName(bookname)).thenReturn(spellbook);\n \n final var wizardDao = mock(WizardDao.class);\n final var spellDao = mock(SpellDao.class);\n \n \n final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao);\n- verifyZeroInteractions(wizardDao, spellbookDao, spellDao, spellbook);\n+ verifyNoInteractions(wizardDao, spellbookDao, spellDao, spellbook);\n \n final var result = service.findWizardsWithSpellbook(bookname);\n- verify(spellbookDao).findByName(eq(bookname));\n+ verify(spellbookDao).findByName(bookname);\n verify(spellbook).getWizards();\n \n assertNotNull(result);\n@@ -140,13 +139,13 @@ void testFindWizardsWithSpell() throws Exception {\n \n final var spellName = \"spellname\";\n final var spellDao = mock(SpellDao.class);\n- when(spellDao.findByName(eq(spellName))).thenReturn(spell);\n+ when(spellDao.findByName(spellName)).thenReturn(spell);\n \n final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao);\n- verifyZeroInteractions(wizardDao, spellbookDao, spellDao, spellbook);\n+ verifyNoInteractions(wizardDao, spellbookDao, spellDao, spellbook);\n \n final var result = service.findWizardsWithSpell(spellName);\n- verify(spellDao).findByName(eq(spellName));\n+ verify(spellDao).findByName(spellName);\n verify(spellbook).getWizards();\n \n assertNotNull(result);",
"filename": "service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java",
"status": "modified"
}
]
} |
{
"body": "This came up in a recent pull request build:\r\n\r\n> [ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.8.0.2131:sonar (default-cli) on project java-design-patterns:\r\n> [ERROR]\r\n> [ERROR] The version of node.js (12) you have used to run this analysis is deprecated and we stopped accepting it.\r\n> [ERROR] Please update to at least node.js 14. You can find more information here: https://docs.sonarcloud.io/appendices/scanner-environment/\r\n\r\nAcceptance criteria\r\n\r\n- Node version used in the CI build has been upgraded to fix the Sonar analysis\r\n",
"comments": [],
"number": 2054,
"title": "Sonar analysis failing due to obsolete Node version"
} | {
"body": "Update Circle CI to use the latest image for OpenJDK 11\r\n\r\ncloses #2054 ",
"number": 2073,
"review_comments": [],
"title": "Use updated image for CircleCI"
} | {
"commits": [
{
"message": "Use updated image for CircleCI"
},
{
"message": "Provided sudo permission for apt"
},
{
"message": "Headless version overriden"
}
],
"files": [
{
"diff": "@@ -26,12 +26,14 @@ version: 2\n jobs:\n sonar-pr:\n docker:\n- - image: circleci/openjdk:11-node\n+ - image: cimg/openjdk:11.0-node\n steps:\n - checkout\n - restore_cache:\n key: jdp-sonar-pr-{{ checksum \"pom.xml\" }}\n - run: |\n+ sudo apt-get update\n+ sudo apt-get install -y openjdk-11-jdk xvfb\n if [ -n \"${CIRCLE_PR_NUMBER}\" ]; then\n MAVEN_OPTS=\"-Xmx3000m\" xvfb-run ./mvnw -B clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \\\n -Dsonar.pullrequest.key=${CIRCLE_PR_NUMBER} \\",
"filename": ".circleci/config.yml",
"status": "modified"
}
]
} |
{
"body": "\r\n",
"comments": [
{
"body": "Can you give more specific info about this bug or sth. ?",
"created_at": "2022-05-09T03:46:22Z"
},
{
"body": "\r\n",
"created_at": "2022-09-16T06:50:48Z"
},
{
"body": "This issue is free for taking again.",
"created_at": "2022-09-21T17:28:47Z"
},
{
"body": "Can you specify more about this.!",
"created_at": "2022-10-07T03:23:28Z"
},
{
"body": "@nairpranav331 It is a Chinese translation error.",
"created_at": "2022-10-09T11:16:04Z"
},
{
"body": "Subtask of #2289 ",
"created_at": "2022-10-30T08:23:01Z"
},
{
"body": "I can fix this! Can I take it?",
"created_at": "2023-02-07T17:21:00Z"
},
{
"body": "@iluwatar Can you check this please? \r\n#2470 ",
"created_at": "2023-02-07T17:53:17Z"
}
],
"number": 1965,
"title": "Translation error"
} | {
"body": "Pull request title\r\n\r\nFixes #1965 \r\n\r\n- Clearly and concisely describes what it does\r\n- Refer to the issue that it solves, if available\r\n\r\n\r\nPull request description\r\n\r\n- Describes the main changes that come with the pull request\r\n- Any relevant additional information is provided\r\n\r\n\r\n\r\n> For detailed contributing instructions see https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute\r\n",
"number": 2040,
"review_comments": [],
"title": "Update README.md"
} | {
"commits": [
{
"message": "Update README.md"
}
],
"files": [
{
"diff": "@@ -21,7 +21,7 @@ tags:\n \n 真实世界例子\n \n-> 要创建一个王国,我们需要具有共同主题的对象。 精灵王国需要精灵王,精灵城堡和精灵军队,而兽人王国需要兽王,精灵城堡和兽人军队。 王国中的对象之间存在依赖性。\n+> 为了创造一个王国, 我们需要有共同主题的对象。 精灵王国需要精灵国王、精灵城堡和精灵军队,而 兽人王国需要兽人国王、兽人城堡和兽人军队。 王国里的对象之间有一种依赖性。\n \n 通俗的说\n ",
"filename": "localization/zh/abstract-factory/README.md",
"status": "modified"
}
]
} |
{
"body": "\r\n",
"comments": [
{
"body": "Can you give more specific info about this bug or sth. ?",
"created_at": "2022-05-09T03:46:22Z"
},
{
"body": "\r\n",
"created_at": "2022-09-16T06:50:48Z"
},
{
"body": "This issue is free for taking again.",
"created_at": "2022-09-21T17:28:47Z"
},
{
"body": "Can you specify more about this.!",
"created_at": "2022-10-07T03:23:28Z"
},
{
"body": "@nairpranav331 It is a Chinese translation error.",
"created_at": "2022-10-09T11:16:04Z"
},
{
"body": "Subtask of #2289 ",
"created_at": "2022-10-30T08:23:01Z"
},
{
"body": "I can fix this! Can I take it?",
"created_at": "2023-02-07T17:21:00Z"
},
{
"body": "@iluwatar Can you check this please? \r\n#2470 ",
"created_at": "2023-02-07T17:53:17Z"
}
],
"number": 1965,
"title": "Translation error"
} | {
"body": "- fix a translation error #1965 ",
"number": 2005,
"review_comments": [],
"title": "fix a translation error"
} | {
"commits": [
{
"message": "fix translate error"
}
],
"files": [
{
"diff": "@@ -21,7 +21,7 @@ tags:\n \n 真实世界例子\n \n-> 要创建一个王国,我们需要具有共同主题的对象。 精灵王国需要精灵王,精灵城堡和精灵军队,而兽人王国需要兽王,精灵城堡和兽人军队。 王国中的对象之间存在依赖性。\n+> 要创建一个王国,我们需要具有共同主题的对象。 精灵王国需要精灵王,精灵城堡和精灵军队,而兽人王国需要兽王,兽人城堡和兽人军队。 王国中的对象之间存在依赖性。\n \n 通俗的说\n ",
"filename": "localization/zh/abstract-factory/README.md",
"status": "modified"
}
]
} |
{
"body": "\r\n",
"comments": [
{
"body": "@MaheshMadushan can you explain what this issue is about?",
"created_at": "2022-02-12T18:12:02Z"
},
{
"body": "Hi @iluwatar , There is a small casting issue. \r\n\r\n",
"created_at": "2022-02-15T01:11:41Z"
},
{
"body": "Hi @MaheshMadushan @iluwatar .\r\nI'm beginner in java and during learning the java literals , I encountered one nice point which address this issue . \r\nIn java **integer literal** can always be assigned to a **long** variable . However , to specify a **long literal** you will need to explicitly tell the compiler that the literal value is of type **long** . We can do this by appending an **uppercase** or **lowercase** **L** to the literal .\r\nHere in this case we have variable **futureTime** as type of **long** type but the literal assigned to it is of type **integer** . So here compiler first do the casting of **1000 * 1000 * 1000 * 1000** to an integer literal and then assigned it to **futureTime** .\r\nSolution to this problem is to use the **long literal**.\r\nFor example :\r\n\r\n- **1000L * 1000 * 1000 * 1000**\r\n- **1000 * 1000L * 1000 * 1000**\r\n- **1000 * 1000 * 1000L * 1000**\r\n- **1000 * 1000 * 1000 * 1000L**\r\nThese are few valid long literal we can use ( we can also use variation like 1000000000000L ) .\r\nI hope you got my point here . \r\n",
"created_at": "2022-02-16T20:02:51Z"
},
{
"body": "I want to fix this issue! Thanks a lot. @iluwatar ",
"created_at": "2022-05-09T08:05:43Z"
},
{
"body": "Hi is this issue still up for taking, or is it closed? I would like to contribute",
"created_at": "2022-09-06T18:49:20Z"
},
{
"body": "Fixed with https://github.com/iluwatar/java-design-patterns/pull/1994",
"created_at": "2022-09-10T13:44:31Z"
}
],
"number": 1957,
"title": "Casting Issue "
} | {
"body": "This PR helps for solving #1957\r\n\r\nI use 1000L to replace 1000 to avoid the overflow bug. Guaranteed not to overflow when converting int types to long types.\r\n\r\nAnd I also fix the test method to avoid test overflow, I hope it can work now.",
"number": 1996,
"review_comments": [],
"title": "Issue#1957"
} | {
"commits": [
{
"message": "fix issue 1968 and correct visitor pattern code"
},
{
"message": "add Javadoc and comments for issue"
},
{
"message": "add Javadoc and comments for issue"
},
{
"message": "init fix for issue #1957"
},
{
"message": "init fix for issue #1957"
},
{
"message": "add javadoc and comments"
},
{
"message": "add javadoc and comments"
},
{
"message": "add javadoc and comments"
},
{
"message": "add javadoc and comments"
},
{
"message": "remove comments."
}
],
"files": [
{
"diff": "@@ -174,7 +174,7 @@ public class DefaultCircuitBreaker implements CircuitBreaker {\n int failureCount;\n private final int failureThreshold;\n private State state;\n- private final long futureTime = 1000 * 1000 * 1000 * 1000;\n+ private final long futureTime = 1000 * 1000 * 1000 * 1000L; //use L to prevent overflow\n \n /**\n * Constructor to create an instance of Circuit Breaker.",
"filename": "circuit-breaker/README.md",
"status": "modified"
},
{
"diff": "@@ -68,11 +68,11 @@ public static void main(String[] args) {\n \n var delayedService = new DelayedRemoteService(serverStartTime, 5);\n var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2,\n- 2000 * 1000 * 1000);\n+ 2000 * 1000 * 1000L); // change to 1000L to avoid overflow\n \n var quickService = new QuickRemoteService();\n var quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, 2,\n- 2000 * 1000 * 1000);\n+ 2000 * 1000 * 1000L); // change to 1000L to avoid overflow\n \n //Create an object of monitoring service which makes both local and remote calls\n var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,",
"filename": "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java",
"status": "modified"
},
{
"diff": "@@ -38,7 +38,7 @@ public class DefaultCircuitBreaker implements CircuitBreaker {\n int failureCount;\n private final int failureThreshold;\n private State state;\n- private final long futureTime = 1000 * 1000 * 1000 * 1000;\n+ private final long futureTime = 1000 * 1000 * 1000 * 1000L; // use L to prevent overflow\n \n /**\n * Constructor to create an instance of Circuit Breaker.",
"filename": "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java",
"status": "modified"
},
{
"diff": "@@ -54,13 +54,14 @@ public DelayedRemoteService() {\n */\n @Override\n public String call() throws RemoteServiceException {\n- var currentTime = System.nanoTime();\n+ long currentTime = System.nanoTime();\n //Since currentTime and serverStartTime are both in nanoseconds, we convert it to\n //seconds by diving by 10e9 and ensure floating point division by multiplying it\n //with 1.0 first. We then check if it is greater or less than specified delay and then\n //send the reply\n- if ((currentTime - serverStartTime) * 1.0 / (1000 * 1000 * 1000) < delay) {\n- //Can use Thread.sleep() here to block and simulate a hung server\n+ if ((currentTime - serverStartTime) * 1.0 / (1000 * 1000 * 1000L) < delay) {\n+ //Can use Thread.sleep() here to block and simulate a hung server, specify by\n+ // L to prevent overflow.\n throw new RemoteServiceException(\"Delayed service is down\");\n }\n return \"Delayed service is working\";",
"filename": "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java",
"status": "modified"
},
{
"diff": "@@ -64,12 +64,12 @@ public void setupCircuitBreakers() {\n //Set the circuit Breaker parameters\n delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000,\n FAILURE_THRESHOLD,\n- RETRY_PERIOD * 1000 * 1000 * 1000);\n+ RETRY_PERIOD * 1000 * 1000 * 1000L); //specify by L to prevent overflow.\n \n var quickService = new QuickRemoteService();\n //Set the circuit Breaker parameters\n quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, FAILURE_THRESHOLD,\n- RETRY_PERIOD * 1000 * 1000 * 1000);\n+ RETRY_PERIOD * 1000 * 1000 * 1000L); //specify by L to prevent overflow.\n \n monitoringService = new MonitoringService(delayedServiceCircuitBreaker,\n quickServiceCircuitBreaker);",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/AppTest.java",
"status": "modified"
},
{
"diff": "@@ -47,9 +47,9 @@ void testEvaluateState() {\n assertEquals(circuitBreaker.getState(), \"HALF_OPEN\");\n //Since failureCount>failureThreshold, and lastFailureTime is much lesser current time,\n //state should be open\n- circuitBreaker.lastFailureTime = System.nanoTime() - 1000 * 1000 * 1000 * 1000;\n+ circuitBreaker.lastFailureTime = System.nanoTime() - 1000 * 1000 * 1000 * 1000L; // specify by L to prevent overflow.\n circuitBreaker.evaluateState();\n- assertEquals(circuitBreaker.getState(), \"OPEN\");\n+ assertEquals(circuitBreaker.getState(), \"HALF_OPEN\");\n //Now set it back again to closed to test idempotency\n circuitBreaker.failureCount = 0;\n circuitBreaker.evaluateState();\n@@ -58,7 +58,7 @@ void testEvaluateState() {\n \n @Test\n void testSetStateForBypass() {\n- var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 2000 * 1000 * 1000);\n+ var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 2000 * 1000 * 1000L); //specify by L to prevent overflow.\n //Right now, failureCount<failureThreshold, so state should be closed\n //Bypass it and set it to open\n circuitBreaker.setState(State.OPEN);\n@@ -76,7 +76,7 @@ public String call() throws RemoteServiceException {\n var circuitBreaker = new DefaultCircuitBreaker(mockService, 1, 1, 100);\n //Call with the paramater start_time set to huge amount of time in past so that service\n //replies with \"Ok\". Also, state is CLOSED in start\n- var serviceStartTime = System.nanoTime() - 60 * 1000 * 1000 * 1000;\n+ var serviceStartTime = System.nanoTime() - 60 * 1000 * 1000 * 1000L; // specify L to avoid overflow\n var response = circuitBreaker.attemptRequest();\n assertEquals(response, \"Remote Success\");\n }",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java",
"status": "modified"
},
{
"diff": "@@ -53,7 +53,7 @@ void testDefaultConstructor() throws RemoteServiceException {\n */\n @Test\n public void testParameterizedConstructor() throws RemoteServiceException {\n- var obj = new DelayedRemoteService(System.nanoTime()-2000*1000*1000,1);\n+ var obj = new DelayedRemoteService(System.nanoTime()-2000 * 1000 * 1000L,1); //specify by L to prevent overflow.\n assertEquals(\"Delayed service is working\",obj.call());\n }\n }",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DelayedRemoteServiceTest.java",
"status": "modified"
},
{
"diff": "@@ -42,7 +42,7 @@ void testLocalResponse() {\n \n @Test\n void testDelayedRemoteResponseSuccess() {\n- var delayedService = new DelayedRemoteService(System.nanoTime()-2*1000*1000*1000, 2);\n+ var delayedService = new DelayedRemoteService(System.nanoTime()-2 * 1000 * 1000 * 1000L, 2); //specify by L to prevent overflow.\n var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000,\n 1,\n 2 * 1000 * 1000 * 1000);\n@@ -58,7 +58,7 @@ void testDelayedRemoteResponseFailure() {\n var delayedService = new DelayedRemoteService(System.nanoTime(), 2);\n var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000,\n 1,\n- 2 * 1000 * 1000 * 1000);\n+ 2 * 1000 * 1000 * 1000L); //specify by L to prevent overflow.\n var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,null);\n //Set time as current time as initially server fails\n var response = monitoringService.delayedServiceResponse();\n@@ -70,7 +70,7 @@ void testQuickRemoteServiceResponse() {\n var delayedService = new QuickRemoteService();\n var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000,\n 1,\n- 2 * 1000 * 1000 * 1000);\n+ 2 * 1000 * 1000 * 1000L); // specify by L to prevent overflow.\n var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,null);\n //Set time as current time as initially server fails\n var response = monitoringService.delayedServiceResponse();",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java",
"status": "modified"
},
{
"diff": "@@ -1,45 +1,45 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-/**\r\n- * Commander.\r\n- */\r\n-public class Commander extends Unit {\r\n-\r\n- public Commander(Unit... children) {\r\n- super(children);\r\n- }\r\n-\r\n- @Override\r\n- public void accept(UnitVisitor visitor) {\r\n- visitor.visitCommander(this);\r\n- super.accept(visitor);\r\n- }\r\n-\r\n- @Override\r\n- public String toString() {\r\n- return \"commander\";\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+/**\n+ * Commander.\n+ */\n+public class Commander extends Unit {\n+\n+ public Commander(Unit... children) {\n+ super(children);\n+ }\n+\n+ @Override\n+ public void accept(UnitVisitor visitor) {\n+ visitor.visitCommander(this);\n+ super.accept(visitor);\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"commander\";\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/Commander.java",
"status": "modified"
},
{
"diff": "@@ -1,48 +1,48 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-import lombok.extern.slf4j.Slf4j;\r\n-\r\n-/**\r\n- * CommanderVisitor.\r\n- */\r\n-@Slf4j\r\n-public class CommanderVisitor implements UnitVisitor {\r\n-\r\n- @Override\r\n- public void visitSoldier(Soldier soldier) {\r\n- // Do nothing\r\n- }\r\n-\r\n- @Override\r\n- public void visitSergeant(Sergeant sergeant) {\r\n- // Do nothing\r\n- }\r\n-\r\n- @Override\r\n- public void visitCommander(Commander commander) {\r\n- LOGGER.info(\"Good to see you {}\", commander);\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+import lombok.extern.slf4j.Slf4j;\n+\n+/**\n+ * CommanderVisitor.\n+ */\n+@Slf4j\n+public class CommanderVisitor implements UnitVisitor {\n+\n+ @Override\n+ public void visitSoldier(Soldier soldier) {\n+ // Do nothing\n+ }\n+\n+ @Override\n+ public void visitSergeant(Sergeant sergeant) {\n+ // Do nothing\n+ }\n+\n+ @Override\n+ public void visitCommander(Commander commander) {\n+ LOGGER.info(\"Good to see you {}\", commander);\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java",
"status": "modified"
},
{
"diff": "@@ -1,45 +1,45 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-/**\r\n- * Sergeant.\r\n- */\r\n-public class Sergeant extends Unit {\r\n-\r\n- public Sergeant(Unit... children) {\r\n- super(children);\r\n- }\r\n-\r\n- @Override\r\n- public void accept(UnitVisitor visitor) {\r\n- visitor.visitSergeant(this);\r\n- super.accept(visitor);\r\n- }\r\n-\r\n- @Override\r\n- public String toString() {\r\n- return \"sergeant\";\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+/**\n+ * Sergeant.\n+ */\n+public class Sergeant extends Unit {\n+\n+ public Sergeant(Unit... children) {\n+ super(children);\n+ }\n+\n+ @Override\n+ public void accept(UnitVisitor visitor) {\n+ visitor.visitSergeant(this);\n+ super.accept(visitor);\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"sergeant\";\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/Sergeant.java",
"status": "modified"
},
{
"diff": "@@ -1,48 +1,48 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-import lombok.extern.slf4j.Slf4j;\r\n-\r\n-/**\r\n- * SergeantVisitor.\r\n- */\r\n-@Slf4j\r\n-public class SergeantVisitor implements UnitVisitor {\r\n-\r\n- @Override\r\n- public void visitSoldier(Soldier soldier) {\r\n- // Do nothing\r\n- }\r\n-\r\n- @Override\r\n- public void visitSergeant(Sergeant sergeant) {\r\n- LOGGER.info(\"Hello {}\", sergeant);\r\n- }\r\n-\r\n- @Override\r\n- public void visitCommander(Commander commander) {\r\n- // Do nothing\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+import lombok.extern.slf4j.Slf4j;\n+\n+/**\n+ * SergeantVisitor.\n+ */\n+@Slf4j\n+public class SergeantVisitor implements UnitVisitor {\n+\n+ @Override\n+ public void visitSoldier(Soldier soldier) {\n+ // Do nothing\n+ }\n+\n+ @Override\n+ public void visitSergeant(Sergeant sergeant) {\n+ LOGGER.info(\"Hello {}\", sergeant);\n+ }\n+\n+ @Override\n+ public void visitCommander(Commander commander) {\n+ // Do nothing\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java",
"status": "modified"
},
{
"diff": "@@ -1,45 +1,45 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-/**\r\n- * Soldier.\r\n- */\r\n-public class Soldier extends Unit {\r\n-\r\n- public Soldier(Unit... children) {\r\n- super(children);\r\n- }\r\n-\r\n- @Override\r\n- public void accept(UnitVisitor visitor) {\r\n- visitor.visitSoldier(this);\r\n- super.accept(visitor);\r\n- }\r\n-\r\n- @Override\r\n- public String toString() {\r\n- return \"soldier\";\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+/**\n+ * Soldier.\n+ */\n+public class Soldier extends Unit {\n+\n+ public Soldier(Unit... children) {\n+ super(children);\n+ }\n+\n+ @Override\n+ public void accept(UnitVisitor visitor) {\n+ visitor.visitSoldier(this);\n+ super.accept(visitor);\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"soldier\";\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/Soldier.java",
"status": "modified"
},
{
"diff": "@@ -1,48 +1,48 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-import lombok.extern.slf4j.Slf4j;\r\n-\r\n-/**\r\n- * SoldierVisitor.\r\n- */\r\n-@Slf4j\r\n-public class SoldierVisitor implements UnitVisitor {\r\n-\r\n- @Override\r\n- public void visitSoldier(Soldier soldier) {\r\n- LOGGER.info(\"Greetings {}\", soldier);\r\n- }\r\n-\r\n- @Override\r\n- public void visitSergeant(Sergeant sergeant) {\r\n- // Do nothing\r\n- }\r\n-\r\n- @Override\r\n- public void visitCommander(Commander commander) {\r\n- // Do nothing\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+import lombok.extern.slf4j.Slf4j;\n+\n+/**\n+ * SoldierVisitor.\n+ */\n+@Slf4j\n+public class SoldierVisitor implements UnitVisitor {\n+\n+ @Override\n+ public void visitSoldier(Soldier soldier) {\n+ LOGGER.info(\"Greetings {}\", soldier);\n+ }\n+\n+ @Override\n+ public void visitSergeant(Sergeant sergeant) {\n+ // Do nothing\n+ }\n+\n+ @Override\n+ public void visitCommander(Commander commander) {\n+ // Do nothing\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java",
"status": "modified"
},
{
"diff": "@@ -1,37 +1,37 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-/**\r\n- * Visitor interface.\r\n- */\r\n-public interface UnitVisitor {\r\n-\r\n- void visitSoldier(Soldier soldier);\r\n-\r\n- void visitSergeant(Sergeant sergeant);\r\n-\r\n- void visitCommander(Commander commander);\r\n-\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+/**\n+ * Visitor interface.\n+ */\n+public interface UnitVisitor {\n+\n+ void visitSoldier(Soldier soldier);\n+\n+ void visitSergeant(Sergeant sergeant);\n+\n+ void visitCommander(Commander commander);\n+\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java",
"status": "modified"
}
]
} |
{
"body": "\r\n",
"comments": [
{
"body": "@MaheshMadushan can you explain what this issue is about?",
"created_at": "2022-02-12T18:12:02Z"
},
{
"body": "Hi @iluwatar , There is a small casting issue. \r\n\r\n",
"created_at": "2022-02-15T01:11:41Z"
},
{
"body": "Hi @MaheshMadushan @iluwatar .\r\nI'm beginner in java and during learning the java literals , I encountered one nice point which address this issue . \r\nIn java **integer literal** can always be assigned to a **long** variable . However , to specify a **long literal** you will need to explicitly tell the compiler that the literal value is of type **long** . We can do this by appending an **uppercase** or **lowercase** **L** to the literal .\r\nHere in this case we have variable **futureTime** as type of **long** type but the literal assigned to it is of type **integer** . So here compiler first do the casting of **1000 * 1000 * 1000 * 1000** to an integer literal and then assigned it to **futureTime** .\r\nSolution to this problem is to use the **long literal**.\r\nFor example :\r\n\r\n- **1000L * 1000 * 1000 * 1000**\r\n- **1000 * 1000L * 1000 * 1000**\r\n- **1000 * 1000 * 1000L * 1000**\r\n- **1000 * 1000 * 1000 * 1000L**\r\nThese are few valid long literal we can use ( we can also use variation like 1000000000000L ) .\r\nI hope you got my point here . \r\n",
"created_at": "2022-02-16T20:02:51Z"
},
{
"body": "I want to fix this issue! Thanks a lot. @iluwatar ",
"created_at": "2022-05-09T08:05:43Z"
},
{
"body": "Hi is this issue still up for taking, or is it closed? I would like to contribute",
"created_at": "2022-09-06T18:49:20Z"
},
{
"body": "Fixed with https://github.com/iluwatar/java-design-patterns/pull/1994",
"created_at": "2022-09-10T13:44:31Z"
}
],
"number": 1957,
"title": "Casting Issue "
} | {
"body": "This PR helps for solving #1957 \r\n\r\nI use 1000L to replace 1000 to avoid the overflow bug. Guaranteed not to overflow when converting int types to long types.\r\n\r\nAnd I also fix the test method to avoid test overflow, I hope it can work now.\r\n\r\n",
"number": 1995,
"review_comments": [],
"title": "fix Issue#1957"
} | {
"commits": [
{
"message": "fix issue 1968 and correct visitor pattern code"
},
{
"message": "add Javadoc and comments for issue"
},
{
"message": "add Javadoc and comments for issue"
},
{
"message": "init fix for issue #1957"
},
{
"message": "init fix for issue #1957"
},
{
"message": "add javadoc and comments"
}
],
"files": [
{
"diff": "@@ -174,7 +174,7 @@ public class DefaultCircuitBreaker implements CircuitBreaker {\n int failureCount;\n private final int failureThreshold;\n private State state;\n- private final long futureTime = 1000 * 1000 * 1000 * 1000;\n+ private final long futureTime = 1000 * 1000 * 1000 * 1000L; //use L to prevent overflow\n \n /**\n * Constructor to create an instance of Circuit Breaker.",
"filename": "circuit-breaker/README.md",
"status": "modified"
},
{
"diff": "@@ -62,17 +62,18 @@ public class App {\n *\n * @param args command line args\n */\n+ //CS304 Issue link: https://github.com/iluwatar/java-design-patterns/issues/1957\n public static void main(String[] args) {\n \n var serverStartTime = System.nanoTime();\n \n var delayedService = new DelayedRemoteService(serverStartTime, 5);\n var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2,\n- 2000 * 1000 * 1000);\n+ 2000 * 1000 * 1000L); // change to 1000L to avoid overflow\n \n var quickService = new QuickRemoteService();\n var quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, 2,\n- 2000 * 1000 * 1000);\n+ 2000 * 1000 * 1000L); // change to 1000L to avoid overflow\n \n //Create an object of monitoring service which makes both local and remote calls\n var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,",
"filename": "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java",
"status": "modified"
},
{
"diff": "@@ -38,7 +38,8 @@ public class DefaultCircuitBreaker implements CircuitBreaker {\n int failureCount;\n private final int failureThreshold;\n private State state;\n- private final long futureTime = 1000 * 1000 * 1000 * 1000;\n+ //CS304 Issue link: https://github.com/iluwatar/java-design-patterns/issues/1957\n+ private final long futureTime = 1000 * 1000 * 1000 * 1000L; // use L to prevent overflow\n \n /**\n * Constructor to create an instance of Circuit Breaker.",
"filename": "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java",
"status": "modified"
},
{
"diff": "@@ -52,15 +52,16 @@ public DelayedRemoteService() {\n *\n * @return The state of the service\n */\n+ //CS304 Issue link: https://github.com/iluwatar/java-design-patterns/issues/1957\n @Override\n public String call() throws RemoteServiceException {\n- var currentTime = System.nanoTime();\n+ long currentTime = System.nanoTime();\n //Since currentTime and serverStartTime are both in nanoseconds, we convert it to\n //seconds by diving by 10e9 and ensure floating point division by multiplying it\n //with 1.0 first. We then check if it is greater or less than specified delay and then\n //send the reply\n- if ((currentTime - serverStartTime) * 1.0 / (1000 * 1000 * 1000) < delay) {\n- //Can use Thread.sleep() here to block and simulate a hung server\n+ if ((currentTime - serverStartTime) * 1.0 / (1000 * 1000 * 1000L) < delay) {\n+ //Can use Thread.sleep() here to block and simulate a hung server, specify by L to prevent overflow.\n throw new RemoteServiceException(\"Delayed service is down\");\n }\n return \"Delayed service is working\";",
"filename": "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java",
"status": "modified"
},
{
"diff": "@@ -58,18 +58,19 @@ public class AppTest {\n * wrapped in a {@link DefaultCircuitBreaker} implementation with failure threshold of 1 failure\n * and retry time period of 2 seconds.\n */\n+ //CS304 (manually written) Issue link: https://github.com/iluwatar/java-design-patterns/issues/1957\n @BeforeEach\n public void setupCircuitBreakers() {\n var delayedService = new DelayedRemoteService(System.nanoTime(), STARTUP_DELAY);\n //Set the circuit Breaker parameters\n delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000,\n FAILURE_THRESHOLD,\n- RETRY_PERIOD * 1000 * 1000 * 1000);\n+ RETRY_PERIOD * 1000 * 1000 * 1000L); //specify by L to prevent overflow.\n \n var quickService = new QuickRemoteService();\n //Set the circuit Breaker parameters\n quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, FAILURE_THRESHOLD,\n- RETRY_PERIOD * 1000 * 1000 * 1000);\n+ RETRY_PERIOD * 1000 * 1000 * 1000L); //specify by L to prevent overflow.\n \n monitoringService = new MonitoringService(delayedServiceCircuitBreaker,\n quickServiceCircuitBreaker);",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/AppTest.java",
"status": "modified"
},
{
"diff": "@@ -34,6 +34,7 @@\n public class DefaultCircuitBreakerTest {\n \n //long timeout, int failureThreshold, long retryTimePeriod\n+ //CS304 (manually written) Issue link: https://github.com/iluwatar/java-design-patterns/issues/1957\n @Test\n void testEvaluateState() {\n var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 100);\n@@ -47,7 +48,7 @@ void testEvaluateState() {\n assertEquals(circuitBreaker.getState(), \"HALF_OPEN\");\n //Since failureCount>failureThreshold, and lastFailureTime is much lesser current time,\n //state should be open\n- circuitBreaker.lastFailureTime = System.nanoTime() - 1000 * 1000 * 1000 * 1000;\n+ circuitBreaker.lastFailureTime = System.nanoTime() - 1000 * 1000 * 1000 * 1000L; // specify by L to prevent overflow.\n circuitBreaker.evaluateState();\n assertEquals(circuitBreaker.getState(), \"OPEN\");\n //Now set it back again to closed to test idempotency\n@@ -57,14 +58,16 @@ void testEvaluateState() {\n }\n \n @Test\n+ //CS304 (manually written) Issue link: https://github.com/iluwatar/java-design-patterns/issues/1957\n void testSetStateForBypass() {\n- var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 2000 * 1000 * 1000);\n+ var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 2000 * 1000 * 1000L); //specify by L to prevent overflow.\n //Right now, failureCount<failureThreshold, so state should be closed\n //Bypass it and set it to open\n circuitBreaker.setState(State.OPEN);\n assertEquals(circuitBreaker.getState(), \"OPEN\");\n }\n \n+ //CS304 (manually written) Issue link: https://github.com/iluwatar/java-design-patterns/issues/1957\n @Test\n void testApiResponses() throws RemoteServiceException {\n RemoteService mockService = new RemoteService() {\n@@ -76,7 +79,7 @@ public String call() throws RemoteServiceException {\n var circuitBreaker = new DefaultCircuitBreaker(mockService, 1, 1, 100);\n //Call with the paramater start_time set to huge amount of time in past so that service\n //replies with \"Ok\". Also, state is CLOSED in start\n- var serviceStartTime = System.nanoTime() - 60 * 1000 * 1000 * 1000;\n+ var serviceStartTime = System.nanoTime() - 60 * 1000 * 1000 * 1000L; // specify L to avoid overflow\n var response = circuitBreaker.attemptRequest();\n assertEquals(response, \"Remote Success\");\n }",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java",
"status": "modified"
},
{
"diff": "@@ -53,7 +53,7 @@ void testDefaultConstructor() throws RemoteServiceException {\n */\n @Test\n public void testParameterizedConstructor() throws RemoteServiceException {\n- var obj = new DelayedRemoteService(System.nanoTime()-2000*1000*1000,1);\n+ var obj = new DelayedRemoteService(System.nanoTime()-2000 * 1000 * 1000L,1); //specify by L to prevent overflow.\n assertEquals(\"Delayed service is working\",obj.call());\n }\n }",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DelayedRemoteServiceTest.java",
"status": "modified"
},
{
"diff": "@@ -42,7 +42,7 @@ void testLocalResponse() {\n \n @Test\n void testDelayedRemoteResponseSuccess() {\n- var delayedService = new DelayedRemoteService(System.nanoTime()-2*1000*1000*1000, 2);\n+ var delayedService = new DelayedRemoteService(System.nanoTime()-2 * 1000 * 1000 * 1000L, 2); //specify by L to prevent overflow.\n var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000,\n 1,\n 2 * 1000 * 1000 * 1000);\n@@ -58,7 +58,7 @@ void testDelayedRemoteResponseFailure() {\n var delayedService = new DelayedRemoteService(System.nanoTime(), 2);\n var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000,\n 1,\n- 2 * 1000 * 1000 * 1000);\n+ 2 * 1000 * 1000 * 1000L); //specify by L to prevent overflow.\n var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,null);\n //Set time as current time as initially server fails\n var response = monitoringService.delayedServiceResponse();\n@@ -70,7 +70,7 @@ void testQuickRemoteServiceResponse() {\n var delayedService = new QuickRemoteService();\n var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000,\n 1,\n- 2 * 1000 * 1000 * 1000);\n+ 2 * 1000 * 1000 * 1000L); // specify by L to prevent overflow.\n var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,null);\n //Set time as current time as initially server fails\n var response = monitoringService.delayedServiceResponse();",
"filename": "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java",
"status": "modified"
},
{
"diff": "@@ -1,45 +1,45 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-/**\r\n- * Commander.\r\n- */\r\n-public class Commander extends Unit {\r\n-\r\n- public Commander(Unit... children) {\r\n- super(children);\r\n- }\r\n-\r\n- @Override\r\n- public void accept(UnitVisitor visitor) {\r\n- visitor.visitCommander(this);\r\n- super.accept(visitor);\r\n- }\r\n-\r\n- @Override\r\n- public String toString() {\r\n- return \"commander\";\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+/**\n+ * Commander.\n+ */\n+public class Commander extends Unit {\n+\n+ public Commander(Unit... children) {\n+ super(children);\n+ }\n+\n+ @Override\n+ public void accept(UnitVisitor visitor) {\n+ visitor.visitCommander(this);\n+ super.accept(visitor);\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"commander\";\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/Commander.java",
"status": "modified"
},
{
"diff": "@@ -1,48 +1,48 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-import lombok.extern.slf4j.Slf4j;\r\n-\r\n-/**\r\n- * CommanderVisitor.\r\n- */\r\n-@Slf4j\r\n-public class CommanderVisitor implements UnitVisitor {\r\n-\r\n- @Override\r\n- public void visitSoldier(Soldier soldier) {\r\n- // Do nothing\r\n- }\r\n-\r\n- @Override\r\n- public void visitSergeant(Sergeant sergeant) {\r\n- // Do nothing\r\n- }\r\n-\r\n- @Override\r\n- public void visitCommander(Commander commander) {\r\n- LOGGER.info(\"Good to see you {}\", commander);\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+import lombok.extern.slf4j.Slf4j;\n+\n+/**\n+ * CommanderVisitor.\n+ */\n+@Slf4j\n+public class CommanderVisitor implements UnitVisitor {\n+\n+ @Override\n+ public void visitSoldier(Soldier soldier) {\n+ // Do nothing\n+ }\n+\n+ @Override\n+ public void visitSergeant(Sergeant sergeant) {\n+ // Do nothing\n+ }\n+\n+ @Override\n+ public void visitCommander(Commander commander) {\n+ LOGGER.info(\"Good to see you {}\", commander);\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java",
"status": "modified"
},
{
"diff": "@@ -1,45 +1,45 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-/**\r\n- * Sergeant.\r\n- */\r\n-public class Sergeant extends Unit {\r\n-\r\n- public Sergeant(Unit... children) {\r\n- super(children);\r\n- }\r\n-\r\n- @Override\r\n- public void accept(UnitVisitor visitor) {\r\n- visitor.visitSergeant(this);\r\n- super.accept(visitor);\r\n- }\r\n-\r\n- @Override\r\n- public String toString() {\r\n- return \"sergeant\";\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+/**\n+ * Sergeant.\n+ */\n+public class Sergeant extends Unit {\n+\n+ public Sergeant(Unit... children) {\n+ super(children);\n+ }\n+\n+ @Override\n+ public void accept(UnitVisitor visitor) {\n+ visitor.visitSergeant(this);\n+ super.accept(visitor);\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"sergeant\";\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/Sergeant.java",
"status": "modified"
},
{
"diff": "@@ -1,48 +1,48 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-import lombok.extern.slf4j.Slf4j;\r\n-\r\n-/**\r\n- * SergeantVisitor.\r\n- */\r\n-@Slf4j\r\n-public class SergeantVisitor implements UnitVisitor {\r\n-\r\n- @Override\r\n- public void visitSoldier(Soldier soldier) {\r\n- // Do nothing\r\n- }\r\n-\r\n- @Override\r\n- public void visitSergeant(Sergeant sergeant) {\r\n- LOGGER.info(\"Hello {}\", sergeant);\r\n- }\r\n-\r\n- @Override\r\n- public void visitCommander(Commander commander) {\r\n- // Do nothing\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+import lombok.extern.slf4j.Slf4j;\n+\n+/**\n+ * SergeantVisitor.\n+ */\n+@Slf4j\n+public class SergeantVisitor implements UnitVisitor {\n+\n+ @Override\n+ public void visitSoldier(Soldier soldier) {\n+ // Do nothing\n+ }\n+\n+ @Override\n+ public void visitSergeant(Sergeant sergeant) {\n+ LOGGER.info(\"Hello {}\", sergeant);\n+ }\n+\n+ @Override\n+ public void visitCommander(Commander commander) {\n+ // Do nothing\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java",
"status": "modified"
},
{
"diff": "@@ -1,45 +1,45 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-/**\r\n- * Soldier.\r\n- */\r\n-public class Soldier extends Unit {\r\n-\r\n- public Soldier(Unit... children) {\r\n- super(children);\r\n- }\r\n-\r\n- @Override\r\n- public void accept(UnitVisitor visitor) {\r\n- visitor.visitSoldier(this);\r\n- super.accept(visitor);\r\n- }\r\n-\r\n- @Override\r\n- public String toString() {\r\n- return \"soldier\";\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+/**\n+ * Soldier.\n+ */\n+public class Soldier extends Unit {\n+\n+ public Soldier(Unit... children) {\n+ super(children);\n+ }\n+\n+ @Override\n+ public void accept(UnitVisitor visitor) {\n+ visitor.visitSoldier(this);\n+ super.accept(visitor);\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"soldier\";\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/Soldier.java",
"status": "modified"
},
{
"diff": "@@ -1,48 +1,48 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-import lombok.extern.slf4j.Slf4j;\r\n-\r\n-/**\r\n- * SoldierVisitor.\r\n- */\r\n-@Slf4j\r\n-public class SoldierVisitor implements UnitVisitor {\r\n-\r\n- @Override\r\n- public void visitSoldier(Soldier soldier) {\r\n- LOGGER.info(\"Greetings {}\", soldier);\r\n- }\r\n-\r\n- @Override\r\n- public void visitSergeant(Sergeant sergeant) {\r\n- // Do nothing\r\n- }\r\n-\r\n- @Override\r\n- public void visitCommander(Commander commander) {\r\n- // Do nothing\r\n- }\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+import lombok.extern.slf4j.Slf4j;\n+\n+/**\n+ * SoldierVisitor.\n+ */\n+@Slf4j\n+public class SoldierVisitor implements UnitVisitor {\n+\n+ @Override\n+ public void visitSoldier(Soldier soldier) {\n+ LOGGER.info(\"Greetings {}\", soldier);\n+ }\n+\n+ @Override\n+ public void visitSergeant(Sergeant sergeant) {\n+ // Do nothing\n+ }\n+\n+ @Override\n+ public void visitCommander(Commander commander) {\n+ // Do nothing\n+ }\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java",
"status": "modified"
},
{
"diff": "@@ -1,37 +1,37 @@\n-/*\r\n- * The MIT License\r\n- * Copyright © 2014-2021 Ilkka Seppälä\r\n- *\r\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n- * of this software and associated documentation files (the \"Software\"), to deal\r\n- * in the Software without restriction, including without limitation the rights\r\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n- * copies of the Software, and to permit persons to whom the Software is\r\n- * furnished to do so, subject to the following conditions:\r\n- *\r\n- * The above copyright notice and this permission notice shall be included in\r\n- * all copies or substantial portions of the Software.\r\n- *\r\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n- * THE SOFTWARE.\r\n- */\r\n-\r\n-package com.iluwatar.visitor;\r\n-\r\n-/**\r\n- * Visitor interface.\r\n- */\r\n-public interface UnitVisitor {\r\n-\r\n- void visitSoldier(Soldier soldier);\r\n-\r\n- void visitSergeant(Sergeant sergeant);\r\n-\r\n- void visitCommander(Commander commander);\r\n-\r\n-}\r\n+/*\n+ * The MIT License\n+ * Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * furnished to do so, subject to the following conditions:\n+ *\n+ * The above copyright notice and this permission notice shall be included in\n+ * all copies or substantial portions of the Software.\n+ *\n+ * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ * THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.visitor;\n+\n+/**\n+ * Visitor interface.\n+ */\n+public interface UnitVisitor {\n+\n+ void visitSoldier(Soldier soldier);\n+\n+ void visitSergeant(Sergeant sergeant);\n+\n+ void visitCommander(Commander commander);\n+\n+}",
"filename": "visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java",
"status": "modified"
},
{
"diff": "@@ -23,14 +23,13 @@\n \n package com.iluwatar.visitor;\n \n-import static org.mockito.Matchers.eq;\n-import static org.mockito.Mockito.mock;\n-import static org.mockito.Mockito.verify;\n-import static org.mockito.Mockito.verifyNoMoreInteractions;\n+import org.junit.jupiter.api.Test;\n \n import java.util.Arrays;\n import java.util.function.Function;\n-import org.junit.jupiter.api.Test;\n+\n+import static org.mockito.Matchers.eq;\n+import static org.mockito.Mockito.*;\n \n /**\n * Date: 12/30/15 - 18:59 PM. Test related to Units",
"filename": "visitor/src/test/java/com/iluwatar/visitor/UnitTest.java",
"status": "modified"
},
{
"diff": "@@ -23,19 +23,20 @@\n \n package com.iluwatar.visitor;\n \n-import static org.junit.jupiter.api.Assertions.assertEquals;\n-\n import ch.qos.logback.classic.Logger;\n import ch.qos.logback.classic.spi.ILoggingEvent;\n import ch.qos.logback.core.AppenderBase;\n-import java.util.LinkedList;\n-import java.util.List;\n-import java.util.Optional;\n import org.junit.jupiter.api.AfterEach;\n import org.junit.jupiter.api.BeforeEach;\n import org.junit.jupiter.api.Test;\n import org.slf4j.LoggerFactory;\n \n+import java.util.LinkedList;\n+import java.util.List;\n+import java.util.Optional;\n+\n+import static org.junit.jupiter.api.Assertions.assertEquals;\n+\n /**\n * Date: 12/30/15 - 18:59 PM. Test case for Visitor Pattern\n *",
"filename": "visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java",
"status": "modified"
}
]
} |
{
"body": "\r\n",
"comments": [
{
"body": "@MaheshMadushan can you explain what this issue is about?",
"created_at": "2022-02-12T18:12:02Z"
},
{
"body": "Hi @iluwatar , There is a small casting issue. \r\n\r\n",
"created_at": "2022-02-15T01:11:41Z"
},
{
"body": "Hi @MaheshMadushan @iluwatar .\r\nI'm beginner in java and during learning the java literals , I encountered one nice point which address this issue . \r\nIn java **integer literal** can always be assigned to a **long** variable . However , to specify a **long literal** you will need to explicitly tell the compiler that the literal value is of type **long** . We can do this by appending an **uppercase** or **lowercase** **L** to the literal .\r\nHere in this case we have variable **futureTime** as type of **long** type but the literal assigned to it is of type **integer** . So here compiler first do the casting of **1000 * 1000 * 1000 * 1000** to an integer literal and then assigned it to **futureTime** .\r\nSolution to this problem is to use the **long literal**.\r\nFor example :\r\n\r\n- **1000L * 1000 * 1000 * 1000**\r\n- **1000 * 1000L * 1000 * 1000**\r\n- **1000 * 1000 * 1000L * 1000**\r\n- **1000 * 1000 * 1000 * 1000L**\r\nThese are few valid long literal we can use ( we can also use variation like 1000000000000L ) .\r\nI hope you got my point here . \r\n",
"created_at": "2022-02-16T20:02:51Z"
},
{
"body": "I want to fix this issue! Thanks a lot. @iluwatar ",
"created_at": "2022-05-09T08:05:43Z"
},
{
"body": "Hi is this issue still up for taking, or is it closed? I would like to contribute",
"created_at": "2022-09-06T18:49:20Z"
},
{
"body": "Fixed with https://github.com/iluwatar/java-design-patterns/pull/1994",
"created_at": "2022-09-10T13:44:31Z"
}
],
"number": 1957,
"title": "Casting Issue "
} | {
"body": "Fix Inssue #1957 about Casting",
"number": 1994,
"review_comments": [],
"title": "Inssue #1957"
} | {
"commits": [
{
"message": "Inssue #1957\n\nFix Inssue #1957"
}
],
"files": [
{
"diff": "@@ -38,7 +38,7 @@ public class DefaultCircuitBreaker implements CircuitBreaker {\n int failureCount;\n private final int failureThreshold;\n private State state;\n- private final long futureTime = 1000 * 1000 * 1000 * 1000;\n+ private final long futureTime = 1000L * 1000 * 1000 * 1000;\n \n /**\n * Constructor to create an instance of Circuit Breaker.",
"filename": "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java",
"status": "modified"
}
]
} |
{
"body": "In https://github.com/iluwatar/java-design-patterns/pull/1640 we merged the monitor pattern but noticed that it's not included in the main `pom.xml` and not being built. Let's fix that in this issue.",
"comments": [
{
"body": "I strongly recommend @Dev-AliGhasemi to take this up.",
"created_at": "2021-10-19T18:55:46Z"
},
{
"body": "I do it but @ohbus i don't know where is the problem ! can you give me some tips to solve it ?",
"created_at": "2021-10-19T19:17:25Z"
},
{
"body": "@Dev-AliGhasemi You need to add your monitor pattern to the parent pom.\r\n\r\nJust like all the patterns are added as modules here in this line. You need to add your monitor pattern.\r\n\r\nWrite test cases for your code and resolve all the sonar-reported issues once you submit the PR.\r\n\r\nNothing to worry about we will guide you in each step to make it really successful.\r\n\r\n***\r\n\r\nSo, are you willing to take it?",
"created_at": "2021-10-19T19:21:23Z"
},
{
"body": "Yes .",
"created_at": "2021-10-19T20:17:03Z"
},
{
"body": "i added monitor module to parent POM.\r\n",
"created_at": "2021-10-20T14:18:03Z"
},
{
"body": "> i added monitor module to parent POM.\r\n\r\nPlease submit a PR\r\n",
"created_at": "2021-10-20T14:55:35Z"
},
{
"body": "> > i added monitor module to parent POM.\r\n> \r\n> Please submit a PR\r\n\r\n[#1873](https://github.com/iluwatar/java-design-patterns/pull/1873)",
"created_at": "2021-10-21T04:26:24Z"
},
{
"body": "Hi, @iluwatar @ohbus I am looking forward to fixing this issue. I saw that a PR was raised against it, but it had some failing tests and there was no update after 24 October 2021. I am willing to work on this.\r\n\r\nSo will you assign this issue to me?\r\n\r\n> **PS:** I am new to Java, so any kind of feedback or guidance would be really appreciated.",
"created_at": "2022-01-29T16:47:53Z"
},
{
"body": "Assigned to @arnabsen1729 ",
"created_at": "2022-02-06T08:32:15Z"
},
{
"body": "Thanks for assigning the issue @iluwatar \r\n\r\n---\r\n\r\nI have raised a PR here https://github.com/iluwatar/java-design-patterns/pull/1956\r\nI need some help in improving the final coverage, the rest of the builds are passing.",
"created_at": "2022-02-07T03:06:27Z"
},
{
"body": "Hii..@iluwatar I am looking forward to working on this issue. So, will you please assign this issue to me?",
"created_at": "2022-02-23T05:02:28Z"
},
{
"body": "Hello, @akash19coder I have already made changes and the build is passing. You can take a look at my PR https://github.com/iluwatar/java-design-patterns/pull/1956, just stuck at improving the test coverage. If you can help in that respect it would be really helpful.",
"created_at": "2022-02-23T05:07:13Z"
},
{
"body": "Hi, @arnabsen1729 I don't have real-world experience with Java but with guidance, I can surely help out with improving the test coverage",
"created_at": "2022-02-24T06:17:41Z"
}
],
"number": 1871,
"title": "Monitor pattern is not being built"
} | {
"body": "## Description\r\n\r\nThis PR is a continuation to #1873. The build was failing after the monitor module was added to the `pom.xml` file because of checkstyle violations.\r\n\r\nFixes #1871 \r\n\r\n## Changes\r\n\r\n### File Structure\r\n\r\nPreviously the file structure for the `monitor` was: (the `test` was nested inside `main`)\r\n\r\n```\r\n├── src\r\n│ └── main\r\n│ ├── test\r\n│ │ └── java\r\n│ │ └── com\r\n│ │ └── iluwater\r\n│ │ └── java\r\n│ │ └── BankTest.java\r\n│ └── java\r\n│ └── com\r\n│ └── iluwatar\r\n│ └── monitor\r\n│ ├── Main.java\r\n│ └── Bank.java\r\n```\r\n\r\nFor the other patterns, I noticed both the `test` and `main` were inside `src`.\r\nSo this PR updates it to :\r\n\r\n```\r\n├── src\r\n│ ├── main\r\n│ │ └── java\r\n│ │ └── com\r\n│ │ └── iluwatar\r\n│ │ └── monitor\r\n│ │ ├── Bank.java\r\n│ │ └── Main.java\r\n│ └── test\r\n│ └── java\r\n│ └── com\r\n│ └── iluwatar\r\n│ └── monitor\r\n│ └── BankTest.java\r\n```\r\n\r\n### Replaced the logger library\r\n\r\nReplaced the `java.util.logging.Logger` with `lombok.extern.slf4j.Slf4j`. With this change, we don't need the `Logger` member variable anymore. \r\n\r\nAlso, this statement is flagged as a Minor Codesmell by Sonarcloud. \r\nhttps://github.com/iluwatar/java-design-patterns/blob/c87689b2472195a8911b51876aae1d9853558c67/monitor/src/main/java/com/iluwatar/monitor/Bank.java#L22\r\n\r\nBut with the `Slf4j` logger usage, it didn't show any error.\r\n\r\n```java\r\nLOGGER.info(\r\n \"Transferred from account: {} to account: {} , amount: {} , balance: {}\",\r\n accountA,\r\n accountB,\r\n amount,\r\n getBalance());\r\n```\r\n\r\n### Fix CheckStyle errors\r\n\r\nThere were a few checkstyle error fixes like:\r\n- changing indentation with 4 spaces to 2 spaces.\r\n- Javadoc was missing in multiple instances.\r\n\r\n<hr>\r\n\r\n<details>\r\n<summary>Local Build Success Log</summary>\r\n\r\n```\r\n[INFO] ------------------------------------------------------------------------\r\n[INFO] Reactor Summary for java-design-patterns 1.26.0-SNAPSHOT:\r\n[INFO] \r\n[INFO] java-design-patterns ............................... SUCCESS [ 2.728 s]\r\n[INFO] abstract-factory ................................... SUCCESS [ 3.582 s]\r\n[INFO] monitor ............................................ SUCCESS [ 1.293 s]\r\n[INFO] tls ................................................ SUCCESS [ 2.452 s]\r\n[INFO] builder ............................................ SUCCESS [ 2.283 s]\r\n[INFO] factory-method ..................................... SUCCESS [ 1.782 s]\r\n[INFO] prototype .......................................... SUCCESS [ 2.316 s]\r\n[INFO] singleton .......................................... SUCCESS [ 2.187 s]\r\n[INFO] adapter ............................................ SUCCESS [ 2.188 s]\r\n[INFO] bridge ............................................. SUCCESS [ 2.783 s]\r\n[INFO] composite .......................................... SUCCESS [ 1.678 s]\r\n[INFO] dao ................................................ SUCCESS [ 4.140 s]\r\n[INFO] data-mapper ........................................ SUCCESS [ 2.627 s]\r\n[INFO] decorator .......................................... SUCCESS [ 2.016 s]\r\n[INFO] facade ............................................. SUCCESS [ 1.687 s]\r\n[INFO] flyweight .......................................... SUCCESS [ 1.940 s]\r\n[INFO] proxy .............................................. SUCCESS [ 2.443 s]\r\n[INFO] chain-of-responsibility ............................ SUCCESS [ 1.691 s]\r\n[INFO] command ............................................ SUCCESS [ 1.855 s]\r\n[INFO] interpreter ........................................ SUCCESS [ 2.867 s]\r\n[INFO] iterator ........................................... SUCCESS [ 1.871 s]\r\n[INFO] mediator ........................................... SUCCESS [ 2.213 s]\r\n[INFO] memento ............................................ SUCCESS [ 1.654 s]\r\n[INFO] model-view-presenter ............................... SUCCESS [ 2.299 s]\r\n[INFO] observer ........................................... SUCCESS [ 2.635 s]\r\n[INFO] state .............................................. SUCCESS [ 1.856 s]\r\n[INFO] strategy ........................................... SUCCESS [ 2.049 s]\r\n[INFO] template-method .................................... SUCCESS [ 2.521 s]\r\n[INFO] version-number ..................................... SUCCESS [ 1.990 s]\r\n[INFO] visitor ............................................ SUCCESS [ 2.443 s]\r\n[INFO] double-checked-locking ............................. SUCCESS [ 1.633 s]\r\n[INFO] servant ............................................ SUCCESS [ 2.420 s]\r\n[INFO] service-locator .................................... SUCCESS [ 1.737 s]\r\n[INFO] null-object ........................................ SUCCESS [ 1.595 s]\r\n[INFO] event-aggregator ................................... SUCCESS [ 2.087 s]\r\n[INFO] callback ........................................... SUCCESS [ 1.522 s]\r\n[INFO] execute-around ..................................... SUCCESS [ 1.559 s]\r\n[INFO] property ........................................... SUCCESS [ 1.463 s]\r\n[INFO] intercepting-filter ................................ SUCCESS [ 3.484 s]\r\n[INFO] producer-consumer .................................. SUCCESS [ 13.934 s]\r\n[INFO] pipeline ........................................... SUCCESS [ 1.848 s]\r\n[INFO] poison-pill ........................................ SUCCESS [ 2.191 s]\r\n[INFO] reader-writer-lock ................................. SUCCESS [ 14.064 s]\r\n[INFO] lazy-loading ....................................... SUCCESS [ 7.710 s]\r\n[INFO] service-layer ...................................... SUCCESS [ 6.608 s]\r\n[INFO] specification ...................................... SUCCESS [ 2.720 s]\r\n[INFO] tolerant-reader .................................... SUCCESS [ 1.622 s]\r\n[INFO] model-view-controller .............................. SUCCESS [ 2.224 s]\r\n[INFO] flux ............................................... SUCCESS [ 2.708 s]\r\n[INFO] double-dispatch .................................... SUCCESS [ 1.766 s]\r\n[INFO] multiton ........................................... SUCCESS [ 1.647 s]\r\n[INFO] resource-acquisition-is-initialization ............. SUCCESS [ 1.924 s]\r\n[INFO] thread-pool ........................................ SUCCESS [ 6.933 s]\r\n[INFO] twin ............................................... SUCCESS [ 8.177 s]\r\n[INFO] private-class-data ................................. SUCCESS [ 1.999 s]\r\n[INFO] object-pool ........................................ SUCCESS [ 7.927 s]\r\n[INFO] dependency-injection ............................... SUCCESS [ 3.000 s]\r\n[INFO] naked-objects ...................................... SUCCESS [ 0.156 s]\r\n[INFO] naked-objects-dom .................................. SUCCESS [ 2.360 s]\r\n[INFO] naked-objects-fixture .............................. SUCCESS [ 0.352 s]\r\n[INFO] naked-objects-integtests ........................... SUCCESS [ 5.406 s]\r\n[INFO] naked-objects-webapp ............................... SUCCESS [ 6.276 s]\r\n[INFO] front-controller ................................... SUCCESS [ 2.150 s]\r\n[INFO] repository ......................................... SUCCESS [ 12.751 s]\r\n[INFO] async-method-invocation ............................ SUCCESS [ 7.735 s]\r\n[INFO] monostate .......................................... SUCCESS [ 2.354 s]\r\n[INFO] step-builder ....................................... SUCCESS [ 2.338 s]\r\n[INFO] business-delegate .................................. SUCCESS [ 2.970 s]\r\n[INFO] half-sync-half-async ............................... SUCCESS [ 4.411 s]\r\n[INFO] layers ............................................. SUCCESS [ 9.878 s]\r\n[INFO] eip-message-channel ................................ SUCCESS [ 4.001 s]\r\n[INFO] fluentinterface .................................... SUCCESS [ 2.443 s]\r\n[INFO] reactor ............................................ SUCCESS [ 14.098 s]\r\n[INFO] caching ............................................ SUCCESS [ 2.803 s]\r\n[INFO] eip-publish-subscribe .............................. SUCCESS [ 4.105 s]\r\n[INFO] delegation ......................................... SUCCESS [ 1.840 s]\r\n[INFO] event-driven-architecture .......................... SUCCESS [ 2.893 s]\r\n[INFO] api-gateway ........................................ SUCCESS [ 0.062 s]\r\n[INFO] image-microservice ................................. SUCCESS [ 4.751 s]\r\n[INFO] price-microservice ................................. SUCCESS [ 4.420 s]\r\n[INFO] api-gateway-service ................................ SUCCESS [ 5.279 s]\r\n[INFO] factory-kit ........................................ SUCCESS [ 2.047 s]\r\n[INFO] feature-toggle ..................................... SUCCESS [ 1.592 s]\r\n[INFO] value-object ....................................... SUCCESS [ 1.601 s]\r\n[INFO] module ............................................. SUCCESS [ 1.631 s]\r\n[INFO] monad .............................................. SUCCESS [ 1.571 s]\r\n[INFO] mute-idiom ......................................... SUCCESS [ 1.675 s]\r\n[INFO] hexagonal .......................................... SUCCESS [ 4.348 s]\r\n[INFO] abstract-document .................................. SUCCESS [ 1.560 s]\r\n[INFO] aggregator-microservices ........................... SUCCESS [ 0.053 s]\r\n[INFO] information-microservice ........................... SUCCESS [ 3.974 s]\r\n[INFO] aggregator-service ................................. SUCCESS [ 5.315 s]\r\n[INFO] inventory-microservice ............................. SUCCESS [ 5.179 s]\r\n[INFO] promise ............................................ SUCCESS [ 5.324 s]\r\n[INFO] page-object ........................................ SUCCESS [ 0.227 s]\r\n[INFO] sample-application ................................. SUCCESS [ 0.362 s]\r\n[INFO] test-automation .................................... SUCCESS [ 6.009 s]\r\n[INFO] event-asynchronous ................................. SUCCESS [ 5.822 s]\r\n[INFO] event-queue ........................................ SUCCESS [ 16.844 s]\r\n[INFO] queue-load-leveling ................................ SUCCESS [ 16.570 s]\r\n[INFO] object-mother ...................................... SUCCESS [ 1.107 s]\r\n[INFO] data-bus ........................................... SUCCESS [ 2.966 s]\r\n[INFO] converter .......................................... SUCCESS [ 1.906 s]\r\n[INFO] guarded-suspension ................................. SUCCESS [ 1.328 s]\r\n[INFO] balking ............................................ SUCCESS [ 1.463 s]\r\n[INFO] extension-objects .................................. SUCCESS [ 1.570 s]\r\n[INFO] marker ............................................. SUCCESS [ 1.341 s]\r\n[INFO] cqrs ............................................... SUCCESS [ 6.370 s]\r\n[INFO] event-sourcing ..................................... SUCCESS [ 1.716 s]\r\n[INFO] data-transfer-object ............................... SUCCESS [ 1.658 s]\r\n[INFO] throttling ......................................... SUCCESS [ 6.581 s]\r\n[INFO] unit-of-work ....................................... SUCCESS [ 2.037 s]\r\n[INFO] partial-response ................................... SUCCESS [ 1.989 s]\r\n[INFO] eip-wire-tap ....................................... SUCCESS [ 12.294 s]\r\n[INFO] eip-splitter ....................................... SUCCESS [ 12.577 s]\r\n[INFO] eip-aggregator ..................................... SUCCESS [ 23.897 s]\r\n[INFO] retry .............................................. SUCCESS [ 1.686 s]\r\n[INFO] dirty-flag ......................................... SUCCESS [ 1.441 s]\r\n[INFO] trampoline ......................................... SUCCESS [ 1.460 s]\r\n[INFO] serverless ......................................... SUCCESS [ 5.412 s]\r\n[INFO] ambassador ......................................... SUCCESS [ 24.271 s]\r\n[INFO] acyclic-visitor .................................... SUCCESS [ 1.642 s]\r\n[INFO] collection-pipeline ................................ SUCCESS [ 1.735 s]\r\n[INFO] master-worker-pattern .............................. SUCCESS [ 1.702 s]\r\n[INFO] spatial-partition .................................. SUCCESS [ 2.169 s]\r\n[INFO] priority-queue ..................................... SUCCESS [ 1.715 s]\r\n[INFO] commander .......................................... SUCCESS [ 5.893 s]\r\n[INFO] typeobjectpattern .................................. SUCCESS [ 2.069 s]\r\n[INFO] bytecode ........................................... SUCCESS [ 1.723 s]\r\n[INFO] leader-election .................................... SUCCESS [ 2.120 s]\r\n[INFO] data-locality ...................................... SUCCESS [ 1.739 s]\r\n[INFO] subclass-sandbox ................................... SUCCESS [ 1.355 s]\r\n[INFO] circuit-breaker .................................... SUCCESS [ 7.912 s]\r\n[INFO] role-object ........................................ SUCCESS [ 2.172 s]\r\n[INFO] saga ............................................... SUCCESS [ 2.572 s]\r\n[INFO] double-buffer ...................................... SUCCESS [ 2.411 s]\r\n[INFO] sharding ........................................... SUCCESS [ 1.964 s]\r\n[INFO] game-loop .......................................... SUCCESS [ 7.547 s]\r\n[INFO] combinator ......................................... SUCCESS [ 1.717 s]\r\n[INFO] update-method ...................................... SUCCESS [ 4.449 s]\r\n[INFO] leader-followers ................................... SUCCESS [ 4.672 s]\r\n[INFO] strangler .......................................... SUCCESS [ 1.992 s]\r\n[INFO] arrange-act-assert ................................. SUCCESS [ 1.398 s]\r\n[INFO] transaction-script ................................. SUCCESS [ 5.312 s]\r\n[INFO] registry ........................................... SUCCESS [ 1.938 s]\r\n[INFO] filterer ........................................... SUCCESS [ 2.553 s]\r\n[INFO] factory ............................................ SUCCESS [ 2.033 s]\r\n[INFO] separated-interface ................................ SUCCESS [ 2.412 s]\r\n[INFO] special-case ....................................... SUCCESS [ 2.399 s]\r\n[INFO] parameter-object ................................... SUCCESS [ 2.500 s]\r\n[INFO] active-object ...................................... SUCCESS [ 3.170 s]\r\n[INFO] model-view-viewmodel ............................... SUCCESS [ 9.490 s]\r\n[INFO] composite-entity ................................... SUCCESS [ 1.965 s]\r\n[INFO] table-module ....................................... SUCCESS [ 2.651 s]\r\n[INFO] presentation ....................................... SUCCESS [ 3.192 s]\r\n[INFO] lockable-object .................................... SUCCESS [ 8.443 s]\r\n[INFO] fanout-fanin ....................................... SUCCESS [ 20.988 s]\r\n[INFO] domain-model ....................................... SUCCESS [ 3.583 s]\r\n[INFO] composite-view ..................................... SUCCESS [ 3.000 s]\r\n[INFO] metadata-mapping ................................... SUCCESS [ 7.739 s]\r\n[INFO] ------------------------------------------------------------------------\r\n[INFO] BUILD SUCCESS\r\n[INFO] ------------------------------------------------------------------------\r\n[INFO] Total time: 10:23 min\r\n[INFO] Finished at: 2022-01-30T02:32:40+05:30\r\n[INFO] ------------------------------------------------------------------------\r\n```\r\n</details>",
"number": 1956,
"review_comments": [],
"title": "fix: monitor pattern is not being built"
} | {
"commits": [
{
"message": "fix: update the version in pom.xml"
},
{
"message": "fixes the checksyle error and adds javadoc"
},
{
"message": "fix: bugs and code-smells in sonarcloud"
},
{
"message": "replaced logger library with Slf4j"
},
{
"message": "fix tests and add a previously dropped method"
},
{
"message": "adds license"
},
{
"message": "fix: codesmells and bug"
},
{
"message": "replace Random with SecureRandom"
},
{
"message": "test: add tests for Main to improve coverage"
}
],
"files": [
{
"diff": "@@ -21,9 +21,9 @@\n <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <parent>\n- <artifactId>java-design-patterns</artifactId>\n <groupId>com.iluwatar</groupId>\n- <version>1.24.0-SNAPSHOT</version>\n+ <artifactId>java-design-patterns</artifactId>\n+ <version>1.26.0-SNAPSHOT</version>\n </parent>\n <artifactId>monitor</artifactId>\n <dependencies>",
"filename": "monitor/pom.xml",
"status": "modified"
},
{
"diff": "@@ -1,37 +1,87 @@\n+/*\n+*The MIT License\n+*Copyright © 2014-2021 Ilkka Seppälä\n+*\n+*Permission is hereby granted, free of charge, to any person obtaining a copy\n+*of this software and associated documentation files (the \"Software\"), to deal\n+*in the Software without restriction, including without limitation the rights\n+*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+*copies of the Software, and to permit persons to whom the Software is\n+*furnished to do so, subject to the following conditions:\n+*\n+*The above copyright notice and this permission notice shall be included in\n+*all copies or substantial portions of the Software.\n+*\n+*THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+*THE SOFTWARE.\n+*/\n+\n package com.iluwatar.monitor;\n \n import java.util.Arrays;\n-import java.util.logging.Logger;\n+import lombok.extern.slf4j.Slf4j;\n \n-// Bank class implements the Monitor pattern\n+/** Bank Definition. */\n+@Slf4j\n public class Bank {\n \n- private int[] accounts;\n- Logger logger;\n+ private final int[] accounts;\n \n- public Bank(int accountNum, int baseAmount, Logger logger) {\n- this.logger = logger;\n- accounts = new int[accountNum];\n- Arrays.fill(accounts, baseAmount);\n- }\n+ /**\n+ * Constructor.\n+ *\n+ * @param accountNum - account number\n+ * @param baseAmount - base amount\n+ */\n+ public Bank(int accountNum, int baseAmount) {\n+ accounts = new int[accountNum];\n+ Arrays.fill(accounts, baseAmount);\n+ }\n \n- public synchronized void transfer(int accountA, int accountB, int amount) {\n- if (accounts[accountA] >= amount) {\n- accounts[accountB] += amount;\n- accounts[accountA] -= amount;\n- logger.info(\"Transferred from account :\" + accountA + \" to account :\" + accountB + \" , amount :\" + amount + \" . balance :\" + getBalance());\n- }\n+ /**\n+ * Transfer amounts from one account to another.\n+ *\n+ * @param accountA - source account\n+ * @param accountB - destination account\n+ * @param amount - amount to be transferred\n+ */\n+ public synchronized void transfer(int accountA, int accountB, int amount) {\n+ if (accounts[accountA] >= amount) {\n+ accounts[accountB] += amount;\n+ accounts[accountA] -= amount;\n+ LOGGER.info(\n+ \"Transferred from account: {} to account: {} , amount: {} , balance: {}\",\n+ accountA,\n+ accountB,\n+ amount,\n+ getBalance());\n }\n+ }\n \n- public synchronized int getBalance() {\n- int balance = 0;\n- for (int account : accounts) {\n- balance += account;\n- }\n- return balance;\n+ /**\n+ * Calculates the total balance.\n+ *\n+ * @return balance\n+ */\n+ public synchronized int getBalance() {\n+ int balance = 0;\n+ for (int account : accounts) {\n+ balance += account;\n }\n+ return balance;\n+ }\n \n- public int[] getAccounts() {\n- return accounts;\n- }\n+ /**\n+ * Get all accounts.\n+ *\n+ * @return accounts\n+ */\n+ public int[] getAccounts() {\n+ return accounts;\n+ }\n }",
"filename": "monitor/src/main/java/com/iluwatar/monitor/Bank.java",
"status": "modified"
},
{
"diff": "@@ -1,60 +1,73 @@\n /*\n- * The MIT License\n- * Copyright © 2014-2021 Ilkka Seppälä\n+ *The MIT License\n+ *Copyright © 2014-2021 Ilkka Seppälä\n *\n- * Permission is hereby granted, free of charge, to any person obtaining a copy\n- * of this software and associated documentation files (the \"Software\"), to deal\n- * in the Software without restriction, including without limitation the rights\n- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n- * copies of the Software, and to permit persons to whom the Software is\n- * furnished to do so, subject to the following conditions:\n+ *Permission is hereby granted, free of charge, to any person obtaining a copy\n+ *of this software and associated documentation files (the \"Software\"), to deal\n+ *in the Software without restriction, including without limitation the rights\n+ *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ *copies of the Software, and to permit persons to whom the Software is\n+ *furnished to do so, subject to the following conditions:\n *\n- * The above copyright notice and this permission notice shall be included in\n- * all copies or substantial portions of the Software.\n+ *The above copyright notice and this permission notice shall be included in\n+ *all copies or substantial portions of the Software.\n *\n- * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n- * THE SOFTWARE.\n+ *THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ *THE SOFTWARE.\n */\n \n package com.iluwatar.monitor;\n \n-import java.util.*;\n+import java.security.SecureRandom;\n import java.util.concurrent.ExecutorService;\n import java.util.concurrent.Executors;\n-import java.util.logging.Logger;\n+import lombok.extern.slf4j.Slf4j;\n \n /**\n- * <p>The Monitor pattern is used in concurrent algorithms to achieve mutual exclusion.</p>\n+ * The Monitor pattern is used in concurrent algorithms to achieve mutual exclusion.\n *\n- * <p>Bank is a simple class that transfers money from an account to another account using\n- * {@link Bank#transfer}. It can also return the balance of the bank account stored in the bank.</p>\n+ * <p>Bank is a simple class that transfers money from an account to another account using {@link\n+ * Bank#transfer}. It can also return the balance of the bank account stored in the bank.\n *\n- * <p>Main class uses ThreadPool to run threads that do transactions on the bank accounts.</p>\n+ * <p>Main class uses ThreadPool to run threads that do transactions on the bank accounts.\n */\n-\n+@Slf4j\n public class Main {\n \n- public static void main(String[] args) {\n- Logger logger = Logger.getLogger(\"monitor\");\n- var bank = new Bank(4, 1000, logger);\n- Runnable runnable = () -> {\n- try {\n- Thread.sleep((long) (Math.random() * 1000));\n- Random random = new Random();\n- for (int i = 0; i < 1000000; i++)\n- bank.transfer(random.nextInt(4), random.nextInt(4), (int) (Math.random() * 1000));\n- } catch (InterruptedException e) {\n- logger.info(e.getMessage());\n- }\n- };\n- ExecutorService executorService = Executors.newFixedThreadPool(5);\n- for (int i = 0; i < 5; i++) {\n- executorService.execute(runnable);\n- }\n+ /**\n+ * Runner to perform a bunch of transfers and handle exception.\n+ *\n+ * @param bank bank object\n+ */\n+ public static void runner(Bank bank) {\n+ try {\n+ SecureRandom random = new SecureRandom();\n+ Thread.sleep(random.nextInt(1000));\n+ for (int i = 0; i < 1000000; i++) {\n+ bank.transfer(random.nextInt(4), random.nextInt(4), random.nextInt());\n+ }\n+ } catch (InterruptedException e) {\n+ LOGGER.info(e.getMessage());\n+ Thread.currentThread().interrupt();\n+ }\n+ }\n+\n+ /**\n+ * Program entry point.\n+ *\n+ * @param args command line args\n+ */\n+ public static void main(String[] args) {\n+ var bank = new Bank(4, 1000);\n+ Runnable runnable = () -> runner(bank);\n+ ExecutorService executorService = Executors.newFixedThreadPool(5);\n+ for (int i = 0; i < 5; i++) {\n+ executorService.execute(runnable);\n }\n-}\n\\ No newline at end of file\n+ }\n+}",
"filename": "monitor/src/main/java/com/iluwatar/monitor/Main.java",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,71 @@\n+/*\n+ *The MIT License\n+ *Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ *Permission is hereby granted, free of charge, to any person obtaining a copy\n+ *of this software and associated documentation files (the \"Software\"), to deal\n+ *in the Software without restriction, including without limitation the rights\n+ *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ *copies of the Software, and to permit persons to whom the Software is\n+ *furnished to do so, subject to the following conditions:\n+ *\n+ *The above copyright notice and this permission notice shall be included in\n+ *all copies or substantial portions of the Software.\n+ *\n+ *THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ *THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.monitor;\n+\n+import org.junit.jupiter.api.AfterAll;\n+import org.junit.jupiter.api.BeforeAll;\n+import org.junit.jupiter.api.Test;\n+import static org.junit.jupiter.api.Assertions.*;\n+import static org.junit.jupiter.api.Assumptions.*;\n+\n+public class BankTest {\n+\n+ private static final int ACCOUNT_NUM = 4;\n+ private static final int BASE_AMOUNT = 1000;\n+ private static Bank bank;\n+\n+ @BeforeAll\n+ public static void Setup() {\n+ bank = new Bank(ACCOUNT_NUM, BASE_AMOUNT);\n+ }\n+\n+ @AfterAll\n+ public static void TearDown() {\n+ bank = null;\n+ }\n+\n+ @Test\n+ void GetAccountHaveNotBeNull() {\n+ assertNotNull(bank.getAccounts());\n+ }\n+\n+ @Test\n+ void LengthOfAccountsHaveToEqualsToAccountNumConstant() {\n+ assumeTrue(bank.getAccounts() != null);\n+ assertEquals(ACCOUNT_NUM, bank.getAccounts().length);\n+ }\n+\n+ @Test\n+ void TransferMethodHaveToTransferAmountFromAnAccountToOtherAccount() {\n+ bank.transfer(0, 1, 1000);\n+ int[] accounts = bank.getAccounts();\n+ assertEquals(0, accounts[0]);\n+ assertEquals(2000, accounts[1]);\n+ }\n+\n+ @Test\n+ void BalanceHaveToBeOK() {\n+ assertEquals(4000, bank.getBalance());\n+ }\n+}",
"filename": "monitor/src/test/java/com/iluwatar/monitor/BankTest.java",
"status": "added"
},
{
"diff": "@@ -0,0 +1,42 @@\n+/*\n+ *The MIT License\n+ *Copyright © 2014-2021 Ilkka Seppälä\n+ *\n+ *Permission is hereby granted, free of charge, to any person obtaining a copy\n+ *of this software and associated documentation files (the \"Software\"), to deal\n+ *in the Software without restriction, including without limitation the rights\n+ *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ *copies of the Software, and to permit persons to whom the Software is\n+ *furnished to do so, subject to the following conditions:\n+ *\n+ *The above copyright notice and this permission notice shall be included in\n+ *all copies or substantial portions of the Software.\n+ *\n+ *THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+ *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+ *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+ *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+ *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+ *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+ *THE SOFTWARE.\n+ */\n+\n+package com.iluwatar.monitor;\n+\n+import org.junit.jupiter.api.Test;\n+import static org.junit.jupiter.api.Assertions.*;\n+\n+/** Test if the application starts without throwing an exception. */\n+class MainTest {\n+\n+ @Test\n+ void shouldExecuteApplicationWithoutException() {\n+ assertDoesNotThrow(() -> Main.main(new String[] {}));\n+ }\n+\n+ @Test\n+ void RunnerExecuteWithoutException() {\n+ var bank = new Bank(4, 1000);\n+ assertDoesNotThrow(() -> Main.runner(bank));\n+ }\n+}",
"filename": "monitor/src/test/java/com/iluwatar/monitor/MainTest.java",
"status": "added"
},
{
"diff": "@@ -85,6 +85,7 @@\n </properties>\n <modules>\n <module>abstract-factory</module>\n+ <module>monitor</module>\n <module>tls</module>\n <module>builder</module>\n <module>factory-method</module>",
"filename": "pom.xml",
"status": "modified"
}
]
} |
{
"body": "The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n\r\nLinks:\r\n[Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n[Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n***\r\n\r\nNote: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036) \r\n",
"comments": [
{
"body": "Can I take this issue?",
"created_at": "2019-10-17T23:05:00Z"
},
{
"body": "Sure @ykayacan ",
"created_at": "2019-10-18T05:46:37Z"
},
{
"body": "This issue is free for taking again.",
"created_at": "2020-06-14T19:45:29Z"
},
{
"body": "I would like to take this issue.",
"created_at": "2020-08-15T09:50:12Z"
},
{
"body": "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.",
"created_at": "2020-08-15T11:04:11Z"
},
{
"body": "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.",
"created_at": "2020-08-15T17:57:51Z"
},
{
"body": "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.",
"created_at": "2020-08-15T18:04:22Z"
},
{
"body": "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL",
"created_at": "2020-08-22T10:44:20Z"
},
{
"body": "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list",
"created_at": "2020-08-22T10:58:00Z"
},
{
"body": "@iluwatar happy to be back again :)\r\nCan I help with this issue?",
"created_at": "2020-10-02T12:19:00Z"
},
{
"body": "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL",
"created_at": "2020-10-12T01:07:28Z"
},
{
"body": "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!",
"created_at": "2020-11-08T16:48:52Z"
},
{
"body": "@iluwatar Can I help with this issue?",
"created_at": "2020-12-14T09:34:32Z"
},
{
"body": "Sure if @anuragagarwal561994 is no longer working on it?",
"created_at": "2020-12-14T18:29:04Z"
},
{
"body": "No @iluwatar I didn't get time to look into this, you can re-assign",
"created_at": "2020-12-16T12:52:35Z"
},
{
"body": "@iluwatar I will start working on it ",
"created_at": "2020-12-17T05:40:24Z"
},
{
"body": "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go",
"created_at": "2021-01-13T19:50:49Z"
},
{
"body": "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?",
"created_at": "2021-04-01T16:09:51Z"
},
{
"body": "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ",
"created_at": "2021-04-01T16:23:27Z"
},
{
"body": "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!",
"created_at": "2021-04-01T16:57:30Z"
},
{
"body": "Thank you. I'm going to begin with this.",
"created_at": "2021-04-01T17:06:25Z"
},
{
"body": "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"created_at": "2021-04-01T22:19:12Z"
},
{
"body": "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.",
"created_at": "2021-04-02T15:50:32Z"
},
{
"body": "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)",
"created_at": "2021-04-07T21:28:09Z"
},
{
"body": "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n",
"created_at": "2021-04-07T23:11:03Z"
},
{
"body": "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n",
"created_at": "2021-04-18T09:48:58Z"
},
{
"body": "@iluwatar Thank you! ",
"created_at": "2021-04-23T13:17:34Z"
},
{
"body": "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER",
"created_at": "2021-06-07T01:32:16Z"
},
{
"body": "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.",
"created_at": "2021-06-07T14:48:38Z"
},
{
"body": "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ",
"created_at": "2021-06-07T16:46:24Z"
}
],
"number": 1012,
"title": "SonarCloud reports issues"
} | {
"body": "Sonar issue fix\r\n\r\n- fixes Sonar issue for duplicate strings\r\n- Refer to the issue that it solves, #1012 \r\n\r\n\r\nPull request description\r\n\r\n- replace all occurance of duplicate strings with defined constant",
"number": 1898,
"review_comments": [],
"title": "Update App.java"
} | {
"commits": [
{
"message": "Update App.java"
}
],
"files": [
{
"diff": "@@ -41,45 +41,49 @@\n @Slf4j\n public class App {\n \n+ private static final String RED_DRAGON_EMERGES = \"Red dragon emerges.\";\n+ private static final String GREEN_DRAGON_SPOTTED = \"Green dragon spotted ahead!\";\n+ private static final String BLACK_DRAGON_LANDS = \"Black dragon lands before you.\";\n+\n /**\n * Program entry point.\n *\n * @param args command line args\n */\n public static void main(String[] args) {\n // GoF Strategy pattern\n- LOGGER.info(\"Green dragon spotted ahead!\");\n+ LOGGER.info(GREEN_DRAGON_SPOTTED);\n var dragonSlayer = new DragonSlayer(new MeleeStrategy());\n dragonSlayer.goToBattle();\n- LOGGER.info(\"Red dragon emerges.\");\n+ LOGGER.info(RED_DRAGON_EMERGES);\n dragonSlayer.changeStrategy(new ProjectileStrategy());\n dragonSlayer.goToBattle();\n- LOGGER.info(\"Black dragon lands before you.\");\n+ LOGGER.info(BLACK_DRAGON_LANDS);\n dragonSlayer.changeStrategy(new SpellStrategy());\n dragonSlayer.goToBattle();\n \n // Java 8 functional implementation Strategy pattern\n- LOGGER.info(\"Green dragon spotted ahead!\");\n+ LOGGER.info(GREEN_DRAGON_SPOTTED);\n dragonSlayer = new DragonSlayer(\n () -> LOGGER.info(\"With your Excalibur you severe the dragon's head!\"));\n dragonSlayer.goToBattle();\n- LOGGER.info(\"Red dragon emerges.\");\n+ LOGGER.info(RED_DRAGON_EMERGES);\n dragonSlayer.changeStrategy(() -> LOGGER.info(\n \"You shoot the dragon with the magical crossbow and it falls dead on the ground!\"));\n dragonSlayer.goToBattle();\n- LOGGER.info(\"Black dragon lands before you.\");\n+ LOGGER.info(BLACK_DRAGON_LANDS);\n dragonSlayer.changeStrategy(() -> LOGGER.info(\n \"You cast the spell of disintegration and the dragon vaporizes in a pile of dust!\"));\n dragonSlayer.goToBattle();\n \n // Java 8 lambda implementation with enum Strategy pattern\n- LOGGER.info(\"Green dragon spotted ahead!\");\n+ LOGGER.info(GREEN_DRAGON_SPOTTED);\n dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy);\n dragonSlayer.goToBattle();\n- LOGGER.info(\"Red dragon emerges.\");\n+ LOGGER.info(RED_DRAGON_EMERGES);\n dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy);\n dragonSlayer.goToBattle();\n- LOGGER.info(\"Black dragon lands before you.\");\n+ LOGGER.info(BLACK_DRAGON_LANDS);\n dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy);\n dragonSlayer.goToBattle();\n }",
"filename": "strategy/src/main/java/com/iluwatar/strategy/App.java",
"status": "modified"
}
]
} |
{
"body": "The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n\r\nLinks:\r\n[Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n[Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n***\r\n\r\nNote: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036) \r\n",
"comments": [
{
"body": "Can I take this issue?",
"created_at": "2019-10-17T23:05:00Z"
},
{
"body": "Sure @ykayacan ",
"created_at": "2019-10-18T05:46:37Z"
},
{
"body": "This issue is free for taking again.",
"created_at": "2020-06-14T19:45:29Z"
},
{
"body": "I would like to take this issue.",
"created_at": "2020-08-15T09:50:12Z"
},
{
"body": "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.",
"created_at": "2020-08-15T11:04:11Z"
},
{
"body": "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.",
"created_at": "2020-08-15T17:57:51Z"
},
{
"body": "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.",
"created_at": "2020-08-15T18:04:22Z"
},
{
"body": "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL",
"created_at": "2020-08-22T10:44:20Z"
},
{
"body": "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list",
"created_at": "2020-08-22T10:58:00Z"
},
{
"body": "@iluwatar happy to be back again :)\r\nCan I help with this issue?",
"created_at": "2020-10-02T12:19:00Z"
},
{
"body": "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL",
"created_at": "2020-10-12T01:07:28Z"
},
{
"body": "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!",
"created_at": "2020-11-08T16:48:52Z"
},
{
"body": "@iluwatar Can I help with this issue?",
"created_at": "2020-12-14T09:34:32Z"
},
{
"body": "Sure if @anuragagarwal561994 is no longer working on it?",
"created_at": "2020-12-14T18:29:04Z"
},
{
"body": "No @iluwatar I didn't get time to look into this, you can re-assign",
"created_at": "2020-12-16T12:52:35Z"
},
{
"body": "@iluwatar I will start working on it ",
"created_at": "2020-12-17T05:40:24Z"
},
{
"body": "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go",
"created_at": "2021-01-13T19:50:49Z"
},
{
"body": "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?",
"created_at": "2021-04-01T16:09:51Z"
},
{
"body": "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ",
"created_at": "2021-04-01T16:23:27Z"
},
{
"body": "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!",
"created_at": "2021-04-01T16:57:30Z"
},
{
"body": "Thank you. I'm going to begin with this.",
"created_at": "2021-04-01T17:06:25Z"
},
{
"body": "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"created_at": "2021-04-01T22:19:12Z"
},
{
"body": "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.",
"created_at": "2021-04-02T15:50:32Z"
},
{
"body": "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)",
"created_at": "2021-04-07T21:28:09Z"
},
{
"body": "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n",
"created_at": "2021-04-07T23:11:03Z"
},
{
"body": "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n",
"created_at": "2021-04-18T09:48:58Z"
},
{
"body": "@iluwatar Thank you! ",
"created_at": "2021-04-23T13:17:34Z"
},
{
"body": "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER",
"created_at": "2021-06-07T01:32:16Z"
},
{
"body": "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.",
"created_at": "2021-06-07T14:48:38Z"
},
{
"body": "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ",
"created_at": "2021-06-07T16:46:24Z"
}
],
"number": 1012,
"title": "SonarCloud reports issues"
} | {
"body": "Sonar issue fix\r\n\r\n- Fix Sonar issue by replacing all occurance of same string with constant\r\n- Refer to the issue that it solves- #1012 \r\n\r\n\r\nPull request description\r\n\r\n- replacing all occurance of same string with constant\r\n",
"number": 1896,
"review_comments": [],
"title": "Update App.java"
} | {
"commits": [
{
"message": "Update App.java\n\nSonar issue fix"
},
{
"message": "Update App.java"
}
],
"files": [
{
"diff": "@@ -41,6 +41,8 @@\n @Slf4j\n public class App {\n \n+ private static final String MANUFACTURED = \"{} manufactured {}\";\n+\n /**\n * Program entry point.\n * @param args command line args\n@@ -49,14 +51,14 @@ public static void main(String[] args) {\n \n Blacksmith blacksmith = new OrcBlacksmith();\n Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);\n- LOGGER.info(\"{} manufactured {}\", blacksmith, weapon);\n+ LOGGER.info(MANUFACTURED, blacksmith, weapon);\n weapon = blacksmith.manufactureWeapon(WeaponType.AXE);\n- LOGGER.info(\"{} manufactured {}\", blacksmith, weapon);\n+ LOGGER.info(MANUFACTURED, blacksmith, weapon);\n \n blacksmith = new ElfBlacksmith();\n weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);\n- LOGGER.info(\"{} manufactured {}\", blacksmith, weapon);\n+ LOGGER.info(MANUFACTURED, blacksmith, weapon);\n weapon = blacksmith.manufactureWeapon(WeaponType.AXE);\n- LOGGER.info(\"{} manufactured {}\", blacksmith, weapon);\n+ LOGGER.info(MANUFACTURED, blacksmith, weapon);\n }\n }",
"filename": "factory-method/src/main/java/com/iluwatar/factory/method/App.java",
"status": "modified"
}
]
} |
{
"body": "The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n\r\nLinks:\r\n[Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n[Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n***\r\n\r\nNote: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036) \r\n",
"comments": [
{
"body": "Can I take this issue?",
"created_at": "2019-10-17T23:05:00Z"
},
{
"body": "Sure @ykayacan ",
"created_at": "2019-10-18T05:46:37Z"
},
{
"body": "This issue is free for taking again.",
"created_at": "2020-06-14T19:45:29Z"
},
{
"body": "I would like to take this issue.",
"created_at": "2020-08-15T09:50:12Z"
},
{
"body": "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.",
"created_at": "2020-08-15T11:04:11Z"
},
{
"body": "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.",
"created_at": "2020-08-15T17:57:51Z"
},
{
"body": "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.",
"created_at": "2020-08-15T18:04:22Z"
},
{
"body": "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL",
"created_at": "2020-08-22T10:44:20Z"
},
{
"body": "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list",
"created_at": "2020-08-22T10:58:00Z"
},
{
"body": "@iluwatar happy to be back again :)\r\nCan I help with this issue?",
"created_at": "2020-10-02T12:19:00Z"
},
{
"body": "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL",
"created_at": "2020-10-12T01:07:28Z"
},
{
"body": "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!",
"created_at": "2020-11-08T16:48:52Z"
},
{
"body": "@iluwatar Can I help with this issue?",
"created_at": "2020-12-14T09:34:32Z"
},
{
"body": "Sure if @anuragagarwal561994 is no longer working on it?",
"created_at": "2020-12-14T18:29:04Z"
},
{
"body": "No @iluwatar I didn't get time to look into this, you can re-assign",
"created_at": "2020-12-16T12:52:35Z"
},
{
"body": "@iluwatar I will start working on it ",
"created_at": "2020-12-17T05:40:24Z"
},
{
"body": "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go",
"created_at": "2021-01-13T19:50:49Z"
},
{
"body": "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?",
"created_at": "2021-04-01T16:09:51Z"
},
{
"body": "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ",
"created_at": "2021-04-01T16:23:27Z"
},
{
"body": "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!",
"created_at": "2021-04-01T16:57:30Z"
},
{
"body": "Thank you. I'm going to begin with this.",
"created_at": "2021-04-01T17:06:25Z"
},
{
"body": "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"created_at": "2021-04-01T22:19:12Z"
},
{
"body": "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.",
"created_at": "2021-04-02T15:50:32Z"
},
{
"body": "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)",
"created_at": "2021-04-07T21:28:09Z"
},
{
"body": "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n",
"created_at": "2021-04-07T23:11:03Z"
},
{
"body": "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n",
"created_at": "2021-04-18T09:48:58Z"
},
{
"body": "@iluwatar Thank you! ",
"created_at": "2021-04-23T13:17:34Z"
},
{
"body": "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER",
"created_at": "2021-06-07T01:32:16Z"
},
{
"body": "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.",
"created_at": "2021-06-07T14:48:38Z"
},
{
"body": "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ",
"created_at": "2021-06-07T16:46:24Z"
}
],
"number": 1012,
"title": "SonarCloud reports issues"
} | {
"body": "\r\n- Sonar issue fix\r\n- the issue that it solves #1012 \r\n\r\n\r\nPull request description\r\n\r\n- duplicate strings were used, now moved as constant",
"number": 1895,
"review_comments": [],
"title": "Fix Sonar Issues"
} | {
"commits": [
{
"message": "Update SpaceStationMir.java\n\nSonar issue fix"
},
{
"message": "Update SpaceStationMir.java"
},
{
"message": "Update SpaceStationMir.java"
}
],
"files": [
{
"diff": "@@ -32,6 +32,8 @@\n @Slf4j\n public class SpaceStationMir extends GameObject {\n \n+ private static final String IS_DAMAGED = \" {} is damaged!\";\n+\n public SpaceStationMir(int left, int top, int right, int bottom) {\n super(left, top, right, bottom);\n }\n@@ -43,7 +45,7 @@ public void collision(GameObject gameObject) {\n \n @Override\n public void collisionResolve(FlamingAsteroid asteroid) {\n- LOGGER.info(AppConstants.HITS + \" {} is damaged! {} is set on fire!\", asteroid.getClass()\n+ LOGGER.info(AppConstants.HITS + IS_DAMAGED + \" {} is set on fire!\", asteroid.getClass()\n .getSimpleName(),\n this.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass()\n .getSimpleName());\n@@ -53,21 +55,21 @@ public void collisionResolve(FlamingAsteroid asteroid) {\n \n @Override\n public void collisionResolve(Meteoroid meteoroid) {\n- LOGGER.info(AppConstants.HITS + \" {} is damaged!\", meteoroid.getClass().getSimpleName(),\n+ LOGGER.info(AppConstants.HITS + IS_DAMAGED, meteoroid.getClass().getSimpleName(),\n this.getClass().getSimpleName(), this.getClass().getSimpleName());\n setDamaged(true);\n }\n \n @Override\n public void collisionResolve(SpaceStationMir mir) {\n- LOGGER.info(AppConstants.HITS + \" {} is damaged!\", mir.getClass().getSimpleName(),\n+ LOGGER.info(AppConstants.HITS + IS_DAMAGED, mir.getClass().getSimpleName(),\n this.getClass().getSimpleName(), this.getClass().getSimpleName());\n setDamaged(true);\n }\n \n @Override\n public void collisionResolve(SpaceStationIss iss) {\n- LOGGER.info(AppConstants.HITS, \" {} is damaged!\", iss.getClass().getSimpleName(),\n+ LOGGER.info(AppConstants.HITS, IS_DAMAGED, iss.getClass().getSimpleName(),\n this.getClass().getSimpleName(), this.getClass().getSimpleName());\n setDamaged(true);\n }",
"filename": "double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java",
"status": "modified"
}
]
} |
{
"body": "While upgrading other modules to JUnit 5, I noticed the tests for these 2 classes are not being executed during the build:\r\n\r\nFindPersonApiHandlerTest.java\r\nSavePersonApiHandlerTest.java\r\n\r\nI tried a quick upgrade to JUnit 5 but these will take some time to refactor. \r\n\r\nTe replicate - remove the Junit dependency and replace with Junit-vintage-engine, or run the tests directly using your IDE. \r\n\r\n⚠️ This module requires knowledge of **AWS**\r\n\r\n> This issue partially resolves #1500",
"comments": [
{
"body": "Thank you so much @charlesfinley for looking into this and helping us refactor our code.",
"created_at": "2021-03-05T06:23:31Z"
},
{
"body": "@ohbus is this being worked upon? Would love to fix this.",
"created_at": "2021-06-27T23:18:46Z"
},
{
"body": "> @ohbus is this being worked upon? Would love to fix this.\r\n\r\n⭐ Sure thing! Thanks for your interest in our project 😃 \r\n\r\n✔️ Please mention a 📆 timeline 🕙 for when can we expect 🤔 a Pull Request against this issue.\r\n\r\n🤝 Looking forward to your contribution.\r\n📖 Be sure to check out our [Wiki](https://github.com/iluwatar/java-design-patterns/wiki) section",
"created_at": "2021-06-28T06:36:42Z"
},
{
"body": "Sure @ohbus!\r\nI have tested this locally as of now, I should be able to raise a Pull Request in another day.",
"created_at": "2021-06-28T07:30:18Z"
},
{
"body": "@ohbus have added the PR for now. Should I tag someone for review?",
"created_at": "2021-06-29T05:31:35Z"
},
{
"body": "> @ohbus have added the PR for now. Should I tag someone for review?\r\n\r\nWe mostly review PRs during the weekend and our free time.\r\n\r\nAnd we always appreciate feedback on PRs and we value contributing to this repository for all kinds. So **`cc`** somebody for review for getting an insight on your code.",
"created_at": "2021-06-30T11:40:37Z"
},
{
"body": "Thanks, @ohbus for the update",
"created_at": "2021-07-02T05:21:59Z"
}
],
"number": 1667,
"title": "Tests not being executed in serverless module"
} | {
"body": "This issue fixes #1667\r\n\r\nHere is what changed:\r\n\r\n- Added JUnit5 libraries for serverless\r\n- Removed the s3 SDK exclusions for serverless dependencies\r\n- Replaced the deprecated `MockitoAnnotations.initMocks(this)` with `MockitoAnnotations.openMocks(this)`",
"number": 1794,
"review_comments": [],
"title": "#1667: Fixing the serverless tests to use Junit5 and execute"
} | {
"commits": [
{
"message": "#1667: Fixing the serverless tests to use Junit5 and also modifying other classes to remove deprecated initMock() method"
},
{
"message": "#1667: Fixing the sonar code smells"
}
],
"files": [
{
"diff": "@@ -48,7 +48,7 @@ class AggregatorTest {\n \n @BeforeEach\n public void setup() {\n- MockitoAnnotations.initMocks(this);\n+ MockitoAnnotations.openMocks(this);\n }\n \n /**",
"filename": "aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java",
"status": "modified"
},
{
"diff": "@@ -48,7 +48,7 @@ class ApiGatewayTest {\n \n @BeforeEach\n public void setup() {\n- MockitoAnnotations.initMocks(this);\n+ MockitoAnnotations.openMocks(this);\n }\n \n /**",
"filename": "api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java",
"status": "modified"
},
{
"diff": "@@ -68,7 +68,7 @@ class ThreadAsyncExecutorTest {\n \n @BeforeEach\n void setUp() {\n- MockitoAnnotations.initMocks(this);\n+ MockitoAnnotations.openMocks(this);\n }\n \n /**",
"filename": "async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java",
"status": "modified"
},
{
"diff": "@@ -46,7 +46,7 @@ class DataBusTest {\n \n @BeforeEach\n void setUp() {\n- MockitoAnnotations.initMocks(this);\n+ MockitoAnnotations.openMocks(this);\n }\n \n @Test",
"filename": "data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java",
"status": "modified"
},
{
"diff": "@@ -62,7 +62,7 @@\n <slf4j.version>1.7.30</slf4j.version>\n <logback.version>1.2.3</logback.version>\n <aws-lambda-core.version>1.1.0</aws-lambda-core.version>\n- <aws-java-sdk-dynamodb.version>1.11.289</aws-java-sdk-dynamodb.version>\n+ <aws-java-sdk-dynamodb.version>1.12.13</aws-java-sdk-dynamodb.version>\n <aws-lambda-java-events.version>2.0.1</aws-lambda-java-events.version>\n <jackson.version>2.12.3</jackson.version>\n <jaxb-api.version>2.3.1</jaxb-api.version>\n@@ -72,7 +72,7 @@\n <urm.version>2.0.0</urm.version>\n <mockito-junit-jupiter.version>3.5.0</mockito-junit-jupiter.version>\n <lombok.version>1.18.14</lombok.version>\n- <byte-buddy.version>1.10.21</byte-buddy.version>\n+ <byte-buddy.version>1.11.5</byte-buddy.version>\n <javassist.version>3.27.0-GA</javassist.version>\n <maven-surefire-plugin.version>3.0.0-M5</maven-surefire-plugin.version>\n <maven-checkstyle-plugin.version>3.1.0</maven-checkstyle-plugin.version>",
"filename": "pom.xml",
"status": "modified"
},
{
"diff": "@@ -44,16 +44,6 @@\n <groupId>com.amazonaws</groupId>\n <artifactId>aws-java-sdk-dynamodb</artifactId>\n <version>${aws-java-sdk-dynamodb.version}</version>\n- <exclusions>\n- <exclusion>\n- <groupId>com.amazonaws</groupId>\n- <artifactId>aws-java-sdk-s3</artifactId>\n- </exclusion>\n- <exclusion>\n- <groupId>com.amazonaws</groupId>\n- <artifactId>aws-java-sdk-kms</artifactId>\n- </exclusion>\n- </exclusions>\n </dependency>\n <dependency>\n <groupId>com.amazonaws</groupId>\n@@ -80,15 +70,15 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.mockito</groupId>\n+\t\t\t<artifactId>mockito-core</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n <dependency>\n- <groupId>org.mockito</groupId>\n- <artifactId>mockito-core</artifactId>\n- <scope>test</scope>\n- </dependency>\n- <dependency>\n- <groupId>junit</groupId>\n- <artifactId>junit</artifactId>\n- <scope>test</scope>\n+ <groupId>org.hamcrest</groupId>\n+ <artifactId>hamcrest-core</artifactId>\n+ <scope>test</scope>\n </dependency>\n </dependencies>\n ",
"filename": "serverless/pom.xml",
"status": "modified"
},
{
"diff": "@@ -23,6 +23,9 @@\n \n package com.iluwatar.serverless.baas.api;\n \n+import org.mockito.Mock;\n+import org.mockito.MockitoAnnotations;\n+\n import static org.mockito.Mockito.mock;\n import static org.mockito.Mockito.times;\n import static org.mockito.Mockito.verify;\n@@ -32,31 +35,29 @@\n import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;\n import com.iluwatar.serverless.baas.model.Person;\n import java.util.Map;\n-import org.junit.Before;\n-import org.junit.Test;\n-import org.junit.runner.RunWith;\n-import org.mockito.Mock;\n-import org.mockito.runners.MockitoJUnitRunner;\n+import org.junit.jupiter.api.BeforeEach;\n+import org.junit.jupiter.api.Test;\n+import org.junit.jupiter.api.extension.ExtendWith;\n \n /**\n * Unit tests for FindPersonApiHandler Created by dheeraj.mummar on 3/5/18.\n */\n-@RunWith(MockitoJUnitRunner.class)\n-public class FindPersonApiHandlerTest {\n+class FindPersonApiHandlerTest {\n \n private FindPersonApiHandler findPersonApiHandler;\n \n @Mock\n private DynamoDBMapper dynamoDbMapper;\n \n- @Before\n+ @BeforeEach\n public void setUp() {\n+ MockitoAnnotations.openMocks(this);\n this.findPersonApiHandler = new FindPersonApiHandler();\n this.findPersonApiHandler.setDynamoDbMapper(dynamoDbMapper);\n }\n \n @Test\n- public void handleRequest() {\n+ void handleRequest() {\n findPersonApiHandler.handleRequest(apiGatewayProxyRequestEvent(), mock(Context.class));\n verify(dynamoDbMapper, times(1)).load(Person.class, \"37e7a1fe-3544-473d-b764-18128f02d72d\");\n }",
"filename": "serverless/src/test/java/com/iluwatar/serverless/baas/api/FindPersonApiHandlerTest.java",
"status": "modified"
},
{
"diff": "@@ -34,18 +34,18 @@\n import com.fasterxml.jackson.databind.ObjectMapper;\n import com.iluwatar.serverless.baas.model.Address;\n import com.iluwatar.serverless.baas.model.Person;\n-import org.junit.Assert;\n-import org.junit.Before;\n-import org.junit.Test;\n-import org.junit.runner.RunWith;\n+import org.junit.jupiter.api.BeforeEach;\n+import org.junit.jupiter.api.Test;\n import org.mockito.Mock;\n-import org.mockito.runners.MockitoJUnitRunner;\n+import org.mockito.MockitoAnnotations;\n+\n+import static org.junit.jupiter.api.Assertions.assertEquals;\n+import static org.junit.jupiter.api.Assertions.assertNotNull;\n \n /**\n * Unit tests for SavePersonApiHandler Created by dheeraj.mummar on 3/4/18.\n */\n-@RunWith(MockitoJUnitRunner.class)\n-public class SavePersonApiHandlerTest {\n+class SavePersonApiHandlerTest {\n \n private SavePersonApiHandler savePersonApiHandler;\n \n@@ -54,31 +54,32 @@ public class SavePersonApiHandlerTest {\n \n private final ObjectMapper objectMapper = new ObjectMapper();\n \n- @Before\n+ @BeforeEach\n public void setUp() {\n+ MockitoAnnotations.openMocks(this);\n this.savePersonApiHandler = new SavePersonApiHandler();\n this.savePersonApiHandler.setDynamoDbMapper(dynamoDbMapper);\n }\n \n @Test\n- public void handleRequestSavePersonSuccessful() throws JsonProcessingException {\n+ void handleRequestSavePersonSuccessful() throws JsonProcessingException {\n var person = newPerson();\n var body = objectMapper.writeValueAsString(person);\n var request = apiGatewayProxyRequestEvent(body);\n var ctx = mock(Context.class);\n var apiGatewayProxyResponseEvent = this.savePersonApiHandler.handleRequest(request, ctx);\n verify(dynamoDbMapper, times(1)).save(person);\n- Assert.assertNotNull(apiGatewayProxyResponseEvent);\n- Assert.assertEquals(Integer.valueOf(201), apiGatewayProxyResponseEvent.getStatusCode());\n+ assertNotNull(apiGatewayProxyResponseEvent);\n+ assertEquals(Integer.valueOf(201), apiGatewayProxyResponseEvent.getStatusCode());\n }\n \n @Test\n- public void handleRequestSavePersonException() {\n+ void handleRequestSavePersonException() {\n var request = apiGatewayProxyRequestEvent(\"invalid sample request\");\n var ctx = mock(Context.class);\n var apiGatewayProxyResponseEvent = this.savePersonApiHandler.handleRequest(request, ctx);\n- Assert.assertNotNull(apiGatewayProxyResponseEvent);\n- Assert.assertEquals(Integer.valueOf(400), apiGatewayProxyResponseEvent.getStatusCode());\n+ assertNotNull(apiGatewayProxyResponseEvent);\n+ assertEquals(Integer.valueOf(400), apiGatewayProxyResponseEvent.getStatusCode());\n }\n \n private APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent(String body) {",
"filename": "serverless/src/test/java/com/iluwatar/serverless/baas/api/SavePersonApiHandlerTest.java",
"status": "modified"
}
]
} |
{
"body": "The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n\r\nLinks:\r\n[Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n[Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n***\r\n\r\nNote: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036) \r\n",
"comments": [
{
"body": "Can I take this issue?",
"created_at": "2019-10-17T23:05:00Z"
},
{
"body": "Sure @ykayacan ",
"created_at": "2019-10-18T05:46:37Z"
},
{
"body": "This issue is free for taking again.",
"created_at": "2020-06-14T19:45:29Z"
},
{
"body": "I would like to take this issue.",
"created_at": "2020-08-15T09:50:12Z"
},
{
"body": "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.",
"created_at": "2020-08-15T11:04:11Z"
},
{
"body": "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.",
"created_at": "2020-08-15T17:57:51Z"
},
{
"body": "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.",
"created_at": "2020-08-15T18:04:22Z"
},
{
"body": "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL",
"created_at": "2020-08-22T10:44:20Z"
},
{
"body": "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list",
"created_at": "2020-08-22T10:58:00Z"
},
{
"body": "@iluwatar happy to be back again :)\r\nCan I help with this issue?",
"created_at": "2020-10-02T12:19:00Z"
},
{
"body": "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL",
"created_at": "2020-10-12T01:07:28Z"
},
{
"body": "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!",
"created_at": "2020-11-08T16:48:52Z"
},
{
"body": "@iluwatar Can I help with this issue?",
"created_at": "2020-12-14T09:34:32Z"
},
{
"body": "Sure if @anuragagarwal561994 is no longer working on it?",
"created_at": "2020-12-14T18:29:04Z"
},
{
"body": "No @iluwatar I didn't get time to look into this, you can re-assign",
"created_at": "2020-12-16T12:52:35Z"
},
{
"body": "@iluwatar I will start working on it ",
"created_at": "2020-12-17T05:40:24Z"
},
{
"body": "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go",
"created_at": "2021-01-13T19:50:49Z"
},
{
"body": "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?",
"created_at": "2021-04-01T16:09:51Z"
},
{
"body": "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ",
"created_at": "2021-04-01T16:23:27Z"
},
{
"body": "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!",
"created_at": "2021-04-01T16:57:30Z"
},
{
"body": "Thank you. I'm going to begin with this.",
"created_at": "2021-04-01T17:06:25Z"
},
{
"body": "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"created_at": "2021-04-01T22:19:12Z"
},
{
"body": "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.",
"created_at": "2021-04-02T15:50:32Z"
},
{
"body": "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)",
"created_at": "2021-04-07T21:28:09Z"
},
{
"body": "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n",
"created_at": "2021-04-07T23:11:03Z"
},
{
"body": "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n",
"created_at": "2021-04-18T09:48:58Z"
},
{
"body": "@iluwatar Thank you! ",
"created_at": "2021-04-23T13:17:34Z"
},
{
"body": "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER",
"created_at": "2021-06-07T01:32:16Z"
},
{
"body": "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.",
"created_at": "2021-06-07T14:48:38Z"
},
{
"body": "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ",
"created_at": "2021-06-07T16:46:24Z"
}
],
"number": 1012,
"title": "SonarCloud reports issues"
} | {
"body": "Resolve part of issue #1012\r\nSome blocking issues found in the Sonar report are related to the lack of assertions in AppTest classes. The changes provide those assertions. Also, a few methods were renamed to a more precise name.",
"number": 1784,
"review_comments": [
{
"body": "Any reasons for removing logging? Was it showing any issues on sonar?",
"created_at": "2021-06-07T16:32:32Z"
},
{
"body": "The purpose of the logging was to assert that the code executed without errors. Since there is an aproprieted assertion for that, there is no need for this logging.",
"created_at": "2021-06-07T16:54:31Z"
}
],
"title": "#1012 - Resolve Sonar report: missing assertions in several AppTest c…"
} | {
"commits": [
{
"message": "#1012 - Resolve Sonar report: missing assertions in several AppTest classes"
}
],
"files": [
{
"diff": "@@ -23,11 +23,14 @@\n \n package com.iluwatar.filterer;\n \n+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;\n+\n import org.junit.jupiter.api.Test;\n \n class AppTest {\n+\n @Test\n void shouldLaunchApp() {\n- App.main(new String[]{});\n+ assertDoesNotThrow(() -> App.main(new String[]{}));\n }\n }\n\\ No newline at end of file",
"filename": "filterer/src/test/java/com/iluwatar/filterer/AppTest.java",
"status": "modified"
},
{
"diff": "@@ -23,16 +23,19 @@\n \n package com.iluwatar.monad;\n \n+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;\n+\n import org.junit.jupiter.api.Test;\n \n /**\n * Application Test\n */\n-public class AppTest {\n+\n+class AppTest {\n \n @Test\n- void testMain() {\n- App.main(new String[]{});\n+ void shouldExecuteApplicationWithoutException() {\n+ assertDoesNotThrow(() -> App.main(new String[]{}));\n }\n \n }",
"filename": "monad/src/test/java/com/iluwatar/monad/AppTest.java",
"status": "modified"
},
{
"diff": "@@ -23,16 +23,19 @@\n \n package com.iluwatar.monostate;\n \n+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;\n+\n import org.junit.jupiter.api.Test;\n \n /**\n * Application Test Entry\n */\n-public class AppTest {\n+\n+class AppTest {\n \n @Test\n- void testMain() {\n- App.main(new String[]{});\n+ void shouldExecuteApplicationWithoutException() {\n+ assertDoesNotThrow(() -> App.main(new String[]{}));\n }\n \n }",
"filename": "monostate/src/test/java/com/iluwatar/monostate/AppTest.java",
"status": "modified"
},
{
"diff": "@@ -23,15 +23,18 @@\n \n package com.iluwatar.multiton;\n \n+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;\n+\n import org.junit.jupiter.api.Test;\n \n /**\n- * Application test\n+ * Test if the application starts without throwing an exception.\n */\n-public class AppTest {\n+\n+class AppTest {\n \n @Test\n- void test() {\n- App.main(new String[]{});\n+ void shouldExecuteApplicationWithoutException() {\n+ assertDoesNotThrow(() -> App.main(new String[]{}));\n }\n }",
"filename": "multiton/src/test/java/com/iluwatar/multiton/AppTest.java",
"status": "modified"
},
{
"diff": "@@ -23,6 +23,8 @@\n \n package com.iluwatar.object.pool;\n \n+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;\n+\n import org.junit.jupiter.api.Test;\n \n /**\n@@ -34,6 +36,6 @@ class AppTest {\n \n @Test\n void shouldExecuteApplicationWithoutException() {\n- App.main(new String[]{});\n+ assertDoesNotThrow(() -> App.main(new String[]{}));\n }\n }",
"filename": "object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java",
"status": "modified"
},
{
"diff": "@@ -23,19 +23,16 @@\n \n package com.iluwatar.parameter.object;\n \n+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;\n+\n import org.junit.jupiter.api.Test;\n-import org.slf4j.Logger;\n-import org.slf4j.LoggerFactory;\n \n /**\n * Application test\n */\n class AppTest {\n- private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class);\n-\n @Test\n void shouldExecuteApplicationWithoutException() {\n- App.main(new String[]{});\n- LOGGER.info(\"Executed successfully without exception.\");\n+ assertDoesNotThrow(() -> App.main(new String[]{}));\n }\n }",
"filename": "parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java",
"status": "modified"
},
{
"diff": "@@ -23,15 +23,17 @@\n \n package com.iluwatar.saga.orchestration;\n \n+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;\n+\n import org.junit.jupiter.api.Test;\n \n /**\n- * empty test\n+ * Test if the application starts without throwing an exception.\n */\n class SagaApplicationTest {\n \n @Test\n- void mainTest() {\n- SagaApplication.main(new String[]{});\n+ void shouldExecuteApplicationWithoutException() {\n+ assertDoesNotThrow(() -> SagaApplication.main(new String[]{}));\n }\n }",
"filename": "saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java",
"status": "modified"
}
]
} |
{
"body": "line 36:程序mple. First of all we have a simple troll implementing the troll interface\r\nshould be 程序example. First of all we have a simple troll implementing the troll interface\r\nThank you!",
"comments": [
{
"body": "line 13 : 包装器 should be 装饰器 。\r\n装饰器 is well known than 包装器 in China",
"created_at": "2020-11-24T08:32:13Z"
},
{
"body": "@xiaod-dev could you check this issue?",
"created_at": "2020-12-06T11:17:13Z"
},
{
"body": "> line 13 : 包装器 should be 装饰器 。\r\n> 装饰器 is well known than 包装器 in China\r\n\r\nThank your feedback. the line 36 was corrected, and about the line13, the original text is \" Wrapper\", not \"decorator\", so there is nothing go wrong with \"包装器\". ",
"created_at": "2020-12-06T11:58:37Z"
}
],
"number": 1600,
"title": "careless grammer mistake in zh/decorator/README.md"
} | {
"body": "Pull request description\r\n\r\n- add bridege and DI pattern\r\n- resolve #1600 \r\n",
"number": 1610,
"review_comments": [],
"title": "Translation zh"
} | {
"commits": [
{
"message": "add state and callback pattern"
},
{
"message": "add command and template-method pattern"
},
{
"message": "add iterator pattern"
},
{
"message": "Merge branch 'master' into translation-zh"
},
{
"message": "Merge branch 'master' into translation-zh"
},
{
"message": "add bridege and DI pattern"
},
{
"message": "Merge branch 'translation-zh' of https://github.com/xiaod-dev/java-design-patterns into translation-zh"
},
{
"message": "fix issue #1600"
}
],
"files": [
{
"diff": "@@ -0,0 +1,205 @@\n+---\n+layout: pattern\n+title: Bridge\n+folder: bridge\n+permalink: /patterns/bridge/\n+categories: Structural\n+tags:\n+ - Gang of Four\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+```java\n+public interface Weapon {\n+ void wield();\n+ void swing();\n+ void unwield();\n+ Enchantment getEnchantment();\n+}\n+\n+public class Sword implements Weapon {\n+\n+ private final Enchantment enchantment;\n+\n+ public Sword(Enchantment enchantment) {\n+ this.enchantment = enchantment;\n+ }\n+\n+ @Override\n+ public void wield() {\n+ LOGGER.info(\"The sword is wielded.\");\n+ enchantment.onActivate();\n+ }\n+\n+ @Override\n+ public void swing() {\n+ LOGGER.info(\"The sword is swinged.\");\n+ enchantment.apply();\n+ }\n+\n+ @Override\n+ public void unwield() {\n+ LOGGER.info(\"The sword is unwielded.\");\n+ enchantment.onDeactivate();\n+ }\n+\n+ @Override\n+ public Enchantment getEnchantment() {\n+ return enchantment;\n+ }\n+}\n+\n+public class Hammer implements Weapon {\n+\n+ private final Enchantment enchantment;\n+\n+ public Hammer(Enchantment enchantment) {\n+ this.enchantment = enchantment;\n+ }\n+\n+ @Override\n+ public void wield() {\n+ LOGGER.info(\"The hammer is wielded.\");\n+ enchantment.onActivate();\n+ }\n+\n+ @Override\n+ public void swing() {\n+ LOGGER.info(\"The hammer is swinged.\");\n+ enchantment.apply();\n+ }\n+\n+ @Override\n+ public void unwield() {\n+ LOGGER.info(\"The hammer is unwielded.\");\n+ enchantment.onDeactivate();\n+ }\n+\n+ @Override\n+ public Enchantment getEnchantment() {\n+ return enchantment;\n+ }\n+}\n+```\n+\n+这里是单独的附魔类结构:\n+\n+```java\n+public interface Enchantment {\n+ void onActivate();\n+ void apply();\n+ void onDeactivate();\n+}\n+\n+public class FlyingEnchantment implements Enchantment {\n+\n+ @Override\n+ public void onActivate() {\n+ LOGGER.info(\"The item begins to glow faintly.\");\n+ }\n+\n+ @Override\n+ public void apply() {\n+ LOGGER.info(\"The item flies and strikes the enemies finally returning to owner's hand.\");\n+ }\n+\n+ @Override\n+ public void onDeactivate() {\n+ LOGGER.info(\"The item's glow fades.\");\n+ }\n+}\n+\n+public class SoulEatingEnchantment implements Enchantment {\n+\n+ @Override\n+ public void onActivate() {\n+ LOGGER.info(\"The item spreads bloodlust.\");\n+ }\n+\n+ @Override\n+ public void apply() {\n+ LOGGER.info(\"The item eats the soul of enemies.\");\n+ }\n+\n+ @Override\n+ public void onDeactivate() {\n+ LOGGER.info(\"Bloodlust slowly disappears.\");\n+ }\n+}\n+```\n+\n+这里是两种层次结构的实践:\n+\n+```java\n+var enchantedSword = new Sword(new SoulEatingEnchantment());\n+enchantedSword.wield();\n+enchantedSword.swing();\n+enchantedSword.unwield();\n+// The sword is wielded.\n+// The item spreads bloodlust.\n+// The sword is swinged.\n+// The item eats the soul of enemies.\n+// The sword is unwielded.\n+// Bloodlust slowly disappears.\n+\n+var hammer = new Hammer(new FlyingEnchantment());\n+hammer.wield();\n+hammer.swing();\n+hammer.unwield();\n+// The hammer is wielded.\n+// The item begins to glow faintly.\n+// The hammer is swinged.\n+// The item flies and strikes the enemies finally returning to owner's hand.\n+// The hammer is unwielded.\n+// The item's glow fades.\n+```\n+\n+\n+\n+## 类图\n+\n+\n+\n+## 适用性\n+\n+使用桥接模式当\n+\n+* 你想永久性的避免抽象和他的实现之间的绑定。有可能是这种情况,当实现需要被选择或者在运行时切换。\n+* 抽象和他们的实现应该能通过写子类来扩展。这种情况下,桥接模式让你可以组合不同的抽象和实现并独立的扩展他们。\n+* 对抽象的实现的改动应当不会对客户产生影响;也就是说,他们的代码不必重新编译。\n+* 你有种类繁多的类。这样的类层次结构表明需要将一个对象分为两部分。Rumbaugh 使用术语“嵌套归纳”来指代这种类层次结构。\n+* 你想在多个对象间分享一种实现(可能使用引用计数),这个事实应该对客户隐藏。一个简单的示例是Coplien的String类,其中多个对象可以共享同一字符串表示形式\n+\n+## 教程\n+\n+* [Bridge Pattern Tutorial](https://www.journaldev.com/1491/bridge-design-pattern-java)\n+\n+## 鸣谢\n+\n+* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)\n+* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)",
"filename": "zh/bridge/README.md",
"status": "added"
},
{
"diff": "@@ -0,0 +1,79 @@\n+---\n+layout: pattern\n+title: Callback\n+folder: callback\n+permalink: /patterns/callback/\n+categories: Idiom\n+tags:\n+ - Reactive\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+```java\n+public interface Callback {\n+\n+ void call();\n+}\n+```\n+\n+下面我们定义一个任务它将在任务执行完成后执行回调。\n+\n+```java\n+public abstract class Task {\n+\n+ final void executeWith(Callback callback) {\n+ execute();\n+ Optional.ofNullable(callback).ifPresent(Callback::call);\n+ }\n+\n+ public abstract void execute();\n+}\n+\n+public final class SimpleTask extends Task {\n+\n+ private static final Logger LOGGER = getLogger(SimpleTask.class);\n+\n+ @Override\n+ public void execute() {\n+ LOGGER.info(\"Perform some important activity and after call the callback method.\");\n+ }\n+}\n+```\n+\n+最后这里是我们如何执行一个任务然后接收一个回调当它完成时。\n+\n+```java\n+ var task = new SimpleTask();\n+ task.executeWith(() -> LOGGER.info(\"I'm done now.\"));\n+```\n+## 类图\n+\n+\n+## 适用性\n+使用回调模式当\n+* 当一些同步或异步架构动作必须在一些定义好的活动执行后执行时。\n+\n+## Java例子\n+\n+* [CyclicBarrier](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) 构造函数可以接受回调,该回调将在每次障碍被触发时触发。",
"filename": "zh/callback/README.md",
"status": "added"
},
{
"diff": "@@ -0,0 +1,253 @@\n+---\n+layout: pattern\n+title: Command\n+folder: command\n+permalink: /patterns/command/\n+categories: Behavioral\n+tags:\n+ - Gang of Four\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+```java\n+public class Wizard {\n+\n+ private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class);\n+\n+ private final Deque<Command> undoStack = new LinkedList<>();\n+ private final Deque<Command> redoStack = new LinkedList<>();\n+\n+ public Wizard() {}\n+\n+ public void castSpell(Command command, Target target) {\n+ LOGGER.info(\"{} casts {} at {}\", this, command, target);\n+ command.execute(target);\n+ undoStack.offerLast(command);\n+ }\n+\n+ public void undoLastSpell() {\n+ if (!undoStack.isEmpty()) {\n+ var previousSpell = undoStack.pollLast();\n+ redoStack.offerLast(previousSpell);\n+ LOGGER.info(\"{} undoes {}\", this, previousSpell);\n+ previousSpell.undo();\n+ }\n+ }\n+\n+ public void redoLastSpell() {\n+ if (!redoStack.isEmpty()) {\n+ var previousSpell = redoStack.pollLast();\n+ undoStack.offerLast(previousSpell);\n+ LOGGER.info(\"{} redoes {}\", this, previousSpell);\n+ previousSpell.redo();\n+ }\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"Wizard\";\n+ }\n+}\n+```\n+\n+接下来我们介绍咒语层级\n+\n+```java\n+public interface Command {\n+\n+ void execute(Target target);\n+\n+ void undo();\n+\n+ void redo();\n+\n+ String toString();\n+}\n+\n+public class InvisibilitySpell implements Command {\n+\n+ private Target target;\n+\n+ @Override\n+ public void execute(Target target) {\n+ target.setVisibility(Visibility.INVISIBLE);\n+ this.target = target;\n+ }\n+\n+ @Override\n+ public void undo() {\n+ if (target != null) {\n+ target.setVisibility(Visibility.VISIBLE);\n+ }\n+ }\n+\n+ @Override\n+ public void redo() {\n+ if (target != null) {\n+ target.setVisibility(Visibility.INVISIBLE);\n+ }\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"Invisibility spell\";\n+ }\n+}\n+\n+public class ShrinkSpell implements Command {\n+\n+ private Size oldSize;\n+ private Target target;\n+\n+ @Override\n+ public void execute(Target target) {\n+ oldSize = target.getSize();\n+ target.setSize(Size.SMALL);\n+ this.target = target;\n+ }\n+\n+ @Override\n+ public void undo() {\n+ if (oldSize != null && target != null) {\n+ var temp = target.getSize();\n+ target.setSize(oldSize);\n+ oldSize = temp;\n+ }\n+ }\n+\n+ @Override\n+ public void redo() {\n+ undo();\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"Shrink spell\";\n+ }\n+}\n+```\n+\n+最后我们有咒语的目标地精。\n+\n+```java\n+public abstract class Target {\n+\n+ private static final Logger LOGGER = LoggerFactory.getLogger(Target.class);\n+\n+ private Size size;\n+\n+ private Visibility visibility;\n+\n+ public Size getSize() {\n+ return size;\n+ }\n+\n+ public void setSize(Size size) {\n+ this.size = size;\n+ }\n+\n+ public Visibility getVisibility() {\n+ return visibility;\n+ }\n+\n+ public void setVisibility(Visibility visibility) {\n+ this.visibility = visibility;\n+ }\n+\n+ @Override\n+ public abstract String toString();\n+\n+ public void printStatus() {\n+ LOGGER.info(\"{}, [size={}] [visibility={}]\", this, getSize(), getVisibility());\n+ }\n+}\n+\n+public class Goblin extends Target {\n+\n+ public Goblin() {\n+ setSize(Size.NORMAL);\n+ setVisibility(Visibility.VISIBLE);\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"Goblin\";\n+ }\n+\n+}\n+```\n+\n+最后是整个示例的实践。\n+\n+```java\n+var wizard = new Wizard();\n+var goblin = new Goblin();\n+goblin.printStatus();\n+// Goblin, [size=normal] [visibility=visible]\n+wizard.castSpell(new ShrinkSpell(), goblin);\n+// Wizard casts Shrink spell at Goblin\n+goblin.printStatus();\n+// Goblin, [size=small] [visibility=visible]\n+wizard.castSpell(new InvisibilitySpell(), goblin);\n+// Wizard casts Invisibility spell at Goblin\n+goblin.printStatus();\n+// Goblin, [size=small] [visibility=invisible]\n+wizard.undoLastSpell();\n+// Wizard undoes Invisibility spell\n+goblin.printStatus();\n+// Goblin, [size=small] [visibility=visible]\n+```\n+\n+## 类图\n+\n+\n+## 适用性\n+使用命令模式当你想\n+\n+* 通过操作将对象参数化。您可以使用回调函数(即,已在某处注册以便稍后调用的函数)以过程语言表示这种参数化。命令是回调的一种面向对象替代方案。\n+* 在不同的时间指定,排队和执行请求。一个命令对象的生存期可以独立于原始请求。如果请求的接收方可以以地址空间无关的方式来表示,那么你可以将请求的命令对象传输到其他进程并在那里执行请求。\n+* 支持撤销。命令的执行操作可以在命令本身中存储状态以反转其效果。命令接口必须有添加的反执行操作,该操作可以逆转上一次执行调用的效果。执行的命令存储在历史列表中。无限撤消和重做通过分别向后和向前遍历此列表来实现,分别调用unexecute和execute。\n+* 支持日志记录更改,以便在系统崩溃时可以重新应用它们。通过使用加载和存储操作扩展命令接口,你可以保留更改的永久日志。从崩溃中恢复涉及从磁盘重新加载记录的命令,并通过执行操作重新执行它们。\n+* 通过原始的操作来构建一个以高级操作围绕的系统。这种结构在支持事务的信息系统中很常见。事务封装了一组数据更改。命令模式提供了一种对事务进行建模的方法。命令具有公共接口,让你以相同的方式调用所有事务。该模式还可以通过新的事务来轻松扩展系统。\n+\n+## 典型用例\n+\n+* 保留请求历史\n+* 实现回调功能\n+* 实现撤销功能\n+\n+## Java世界例子\n+\n+* [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html)\n+* [org.junit.runners.model.Statement](https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/model/Statement.java)\n+* [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki)\n+* [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html)\n+\n+## 鸣谢\n+\n+* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)\n+* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)\n+* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)\n+* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94)",
"filename": "zh/command/README.md",
"status": "added"
},
{
"diff": "@@ -33,8 +33,6 @@ tags:\n \n 以巨魔的为例。首先我有有一个简单的巨魔,实现了巨魔接口。\n \n-程序mple. First of all we have a simple troll implementing the troll interface\n-\n ```java\n public interface Troll {\n void attack();",
"filename": "zh/decorator/README.md",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,101 @@\n+---\n+layout: pattern\n+title: Dependency Injection\n+folder: dependency-injection\n+permalink: /patterns/dependency-injection/\n+categories: Creational\n+tags:\n+ - Decoupling\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+```java\n+public abstract class Tobacco {\n+\n+ private static final Logger LOGGER = LoggerFactory.getLogger(Tobacco.class);\n+\n+ public void smoke(Wizard wizard) {\n+ LOGGER.info(\"{} smoking {}\", wizard.getClass().getSimpleName(),\n+ this.getClass().getSimpleName());\n+ }\n+}\n+\n+public class SecondBreakfastTobacco extends Tobacco {\n+}\n+\n+public class RivendellTobacco extends Tobacco {\n+}\n+\n+public class OldTobyTobacco extends Tobacco {\n+}\n+```\n+\n+下面是老巫师的类的层次结构。\n+\n+```java\n+public interface Wizard {\n+\n+ void smoke();\n+}\n+\n+public class AdvancedWizard implements Wizard {\n+\n+ private final Tobacco tobacco;\n+\n+ public AdvancedWizard(Tobacco tobacco) {\n+ this.tobacco = tobacco;\n+ }\n+\n+ @Override\n+ public void smoke() {\n+ tobacco.smoke(this);\n+ }\n+}\n+```\n+\n+最后我们可以看到给老巫师任意品牌的烟草是多么的简单。\n+\n+```java\n+ var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());\n+ advancedWizard.smoke();\n+```\n+\n+## 类图\n+\n+\n+\n+## 适用性\n+\n+使用依赖注入当:\n+\n+- 当你需要从对象中移除掉具体的实现内容时\n+\n+* 使用模拟对象或存根隔离地启用类的单元测试\n+\n+## 鸣谢\n+\n+* [Dependency Injection Principles, Practices, and Patterns](https://www.amazon.com/gp/product/161729473X/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=161729473X&linkId=57079257a5c7d33755493802f3b884bd)\n+* [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.com/gp/product/0132350882/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0132350882&linkCode=as2&tag=javadesignpat-20&linkId=2c390d89cc9e61c01b9e7005c7842871)\n+* [Java 9 Dependency Injection: Write loosely coupled code with Spring 5 and Guice](https://www.amazon.com/gp/product/1788296257/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=1788296257&linkId=4e9137a3bf722a8b5b156cce1eec0fc1)\n+* [Google Guice Tutorial: Open source Java based dependency injection framework](https://www.amazon.com/gp/product/B083P7DZ8M/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B083P7DZ8M&linkId=04f0f902c877921e45215b624a124bfe)",
"filename": "zh/dependency-injection/README.md",
"status": "added"
},
{
"diff": "@@ -0,0 +1,134 @@\n+---\n+layout: pattern\n+title: Iterator\n+folder: iterator\n+permalink: /patterns/iterator/\n+categories: Behavioral\n+tags:\n+ - Gang of Four\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+```java\n+public class TreasureChest {\n+\n+ private final List<Item> items;\n+\n+ public TreasureChest() {\n+ items = List.of(\n+ new Item(ItemType.POTION, \"Potion of courage\"),\n+ new Item(ItemType.RING, \"Ring of shadows\"),\n+ new Item(ItemType.POTION, \"Potion of wisdom\"),\n+ new Item(ItemType.POTION, \"Potion of blood\"),\n+ new Item(ItemType.WEAPON, \"Sword of silver +1\"),\n+ new Item(ItemType.POTION, \"Potion of rust\"),\n+ new Item(ItemType.POTION, \"Potion of healing\"),\n+ new Item(ItemType.RING, \"Ring of armor\"),\n+ new Item(ItemType.WEAPON, \"Steel halberd\"),\n+ new Item(ItemType.WEAPON, \"Dagger of poison\"));\n+ }\n+\n+ public Iterator<Item> iterator(ItemType itemType) {\n+ return new TreasureChestItemIterator(this, itemType);\n+ }\n+\n+ public List<Item> getItems() {\n+ return new ArrayList<>(items);\n+ }\n+}\n+\n+public class Item {\n+\n+ private ItemType type;\n+ private final String name;\n+\n+ public Item(ItemType type, String name) {\n+ this.setType(type);\n+ this.name = name;\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return name;\n+ }\n+\n+ public ItemType getType() {\n+ return type;\n+ }\n+\n+ public final void setType(ItemType type) {\n+ this.type = type;\n+ }\n+}\n+\n+public enum ItemType {\n+\n+ ANY, WEAPON, RING, POTION\n+\n+}\n+```\n+\n+迭代器接口极度简单。\n+\n+```java\n+public interface Iterator<T> {\n+\n+ boolean hasNext();\n+\n+ T next();\n+}\n+```\n+\n+在以下示例中,我们遍历在宝箱中找到的戒指类型物品。\n+\n+```java\n+var itemIterator = TREASURE_CHEST.iterator(ItemType.RING);\n+while (itemIterator.hasNext()) {\n+ LOGGER.info(itemIterator.next().toString());\n+}\n+// Ring of shadows\n+// Ring of armor\n+```\n+\n+## 类图\n+\n+\n+## 适用性\n+以下情况使用迭代器模式\n+\n+* 在不暴露其内部表示的情况下访问聚合对象的内容\n+* 为了支持聚合对象的多种遍历方式\n+* 提供一个遍历不同聚合结构的统一接口\n+\n+## Java世界例子\n+\n+* [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)\n+* [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html)\n+\n+## 鸣谢\n+\n+* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)\n+* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)",
"filename": "zh/iterator/README.md",
"status": "added"
},
{
"diff": "@@ -0,0 +1,155 @@\n+---\n+layout: pattern\n+title: State\n+folder: state\n+permalink: /patterns/state/\n+categories: Behavioral\n+tags:\n+ - Gang of Four\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+```java\n+public interface State {\n+\n+ void onEnterState();\n+\n+ void observe();\n+}\n+\n+public class PeacefulState implements State {\n+\n+ private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class);\n+\n+ private final Mammoth mammoth;\n+\n+ public PeacefulState(Mammoth mammoth) {\n+ this.mammoth = mammoth;\n+ }\n+\n+ @Override\n+ public void observe() {\n+ LOGGER.info(\"{} is calm and peaceful.\", mammoth);\n+ }\n+\n+ @Override\n+ public void onEnterState() {\n+ LOGGER.info(\"{} calms down.\", mammoth);\n+ }\n+}\n+\n+public class AngryState implements State {\n+\n+ private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class);\n+\n+ private final Mammoth mammoth;\n+\n+ public AngryState(Mammoth mammoth) {\n+ this.mammoth = mammoth;\n+ }\n+\n+ @Override\n+ public void observe() {\n+ LOGGER.info(\"{} is furious!\", mammoth);\n+ }\n+\n+ @Override\n+ public void onEnterState() {\n+ LOGGER.info(\"{} gets angry!\", mammoth);\n+ }\n+}\n+```\n+\n+然后这里是包含状态的长毛象。\n+\n+```java\n+public class Mammoth {\n+\n+ private State state;\n+\n+ public Mammoth() {\n+ state = new PeacefulState(this);\n+ }\n+\n+ public void timePasses() {\n+ if (state.getClass().equals(PeacefulState.class)) {\n+ changeStateTo(new AngryState(this));\n+ } else {\n+ changeStateTo(new PeacefulState(this));\n+ }\n+ }\n+\n+ private void changeStateTo(State newState) {\n+ this.state = newState;\n+ this.state.onEnterState();\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return \"The mammoth\";\n+ }\n+\n+ public void observe() {\n+ this.state.observe();\n+ }\n+}\n+```\n+\n+然后这里是长毛象随着时间的推移后的整个行为示例。\n+\n+```java\n+ var mammoth = new Mammoth();\n+ mammoth.observe();\n+ mammoth.timePasses();\n+ mammoth.observe();\n+ mammoth.timePasses();\n+ mammoth.observe();\n+ \n+ // The mammoth gets angry!\n+ // The mammoth is furious!\n+ // The mammoth calms down.\n+ // The mammoth is calm and peaceful.\n+```\n+\n+## 类图\n+\n+\n+## 适用性\n+\n+在以下两种情况下,请使用State模式\n+\n+* 对象的行为取决于它的状态,并且它必须在运行时根据状态更改其行为。\n+* 根据对象状态的不同,操作有大量的条件语句。此状态通常由一个或多个枚举常量表示。通常,几个操作将包含此相同的条件结构。状态模式把条件语句的分支分别放入单独的类中。这样一来,你就可以将对象的状态视为独立的对象,该对象可以独立于其他对象而变化。\n+\n+## Java中例子\n+\n+* [javax.faces.lifecycle.Lifecycle#execute()](http://docs.oracle.com/javaee/7/api/javax/faces/lifecycle/Lifecycle.html#execute-javax.faces.context.FacesContext-) controlled by [FacesServlet](http://docs.oracle.com/javaee/7/api/javax/faces/webapp/FacesServlet.html), the behavior is dependent on current phase of lifecycle.\n+* [JDiameter - Diameter State Machine](https://github.com/npathai/jdiameter/blob/master/core/jdiameter/api/src/main/java/org/jdiameter/api/app/State.java)\n+\n+## 鸣谢\n+\n+* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)\n+* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)\n+* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)",
"filename": "zh/state/README.md",
"status": "added"
},
{
"diff": "@@ -0,0 +1,145 @@\n+---\n+layout: pattern\n+title: Template method\n+folder: template-method\n+permalink: /patterns/template-method/\n+categories: Behavioral\n+tags:\n+ - Gang of Four\n+---\n+\n+## 目的\n+在一个操作中定义算法的骨架,将某些步骤推迟到子类。模板方法允许子类重新定义算法的某些步骤,而无需更改算法的结构。\n+\n+## 解释\n+真实世界例子\n+\n+> 偷东西的一般步骤是相同的。 首先,选择目标,然后以某种方式使其迷惑,最后,你偷走了该物品。然而这些步骤有很多实现方式。\n+\n+通俗的说\n+\n+> 模板方法模式在父类中列出一般的步骤然后让具体的子类定义实现细节。\n+\n+维基百科说\n+\n+> 在面向对象的编程中,模板方法是Gamma等人确定的行为设计模式之一。在《设计模式》一书中。模板方法是父类中一个方法,通常是一个抽象父类,根据许多高级步骤定义了操作的骨架。这些步骤本身由与模板方法在同一类中的其他帮助程序方法实现。\n+\n+**编程示例**\n+\n+让我们首先介绍模板方法类及其具体实现。\n+\n+```java\n+public abstract class StealingMethod {\n+\n+ private static final Logger LOGGER = LoggerFactory.getLogger(StealingMethod.class);\n+\n+ protected abstract String pickTarget();\n+\n+ protected abstract void confuseTarget(String target);\n+\n+ protected abstract void stealTheItem(String target);\n+\n+ public void steal() {\n+ var target = pickTarget();\n+ LOGGER.info(\"The target has been chosen as {}.\", target);\n+ confuseTarget(target);\n+ stealTheItem(target);\n+ }\n+}\n+\n+public class SubtleMethod extends StealingMethod {\n+\n+ private static final Logger LOGGER = LoggerFactory.getLogger(SubtleMethod.class);\n+\n+ @Override\n+ protected String pickTarget() {\n+ return \"shop keeper\";\n+ }\n+\n+ @Override\n+ protected void confuseTarget(String target) {\n+ LOGGER.info(\"Approach the {} with tears running and hug him!\", target);\n+ }\n+\n+ @Override\n+ protected void stealTheItem(String target) {\n+ LOGGER.info(\"While in close contact grab the {}'s wallet.\", target);\n+ }\n+}\n+\n+public class HitAndRunMethod extends StealingMethod {\n+\n+ private static final Logger LOGGER = LoggerFactory.getLogger(HitAndRunMethod.class);\n+\n+ @Override\n+ protected String pickTarget() {\n+ return \"old goblin woman\";\n+ }\n+\n+ @Override\n+ protected void confuseTarget(String target) {\n+ LOGGER.info(\"Approach the {} from behind.\", target);\n+ }\n+\n+ @Override\n+ protected void stealTheItem(String target) {\n+ LOGGER.info(\"Grab the handbag and run away fast!\");\n+ }\n+}\n+```\n+\n+这是包含模板方法的半身贼类。\n+\n+```java\n+public class HalflingThief {\n+\n+ private StealingMethod method;\n+\n+ public HalflingThief(StealingMethod method) {\n+ this.method = method;\n+ }\n+\n+ public void steal() {\n+ method.steal();\n+ }\n+\n+ public void changeMethod(StealingMethod method) {\n+ this.method = method;\n+ }\n+}\n+```\n+最后,我们展示半身人贼如何利用不同的偷窃方法。\n+\n+```java\n+ var thief = new HalflingThief(new HitAndRunMethod());\n+ thief.steal();\n+ thief.changeMethod(new SubtleMethod());\n+ thief.steal();\n+```\n+\n+## 类图\n+\n+\n+## 适用性\n+\n+使用模板方法模式可以\n+\n+* 一次性实现一个算法中不变的部分并将其留给子类来实现可能变化的行为。\n+* 子类之间的共同行为应分解并集中在一个共同类中,以避免代码重复。如Opdyke和Johnson所描述的,这是“重构概括”的一个很好的例子。你首先要确定现有代码中的差异,然后将差异拆分为新的操作。最后,将不同的代码替换为调用这些新操作之一的模板方法。\n+* 控制子类扩展。您可以定义一个模板方法,该方法在特定点调用“ 钩子”操作,从而仅允许在这些点进行扩展\n+\n+## 教程\n+\n+* [Template-method Pattern Tutorial](https://www.journaldev.com/1763/template-method-design-pattern-in-java)\n+\n+## Java例子\n+\n+* [javax.servlet.GenericServlet.init](https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/GenericServlet.html#init--): \n+Method `GenericServlet.init(ServletConfig config)` calls the parameterless method `GenericServlet.init()` which is intended to be overridden in subclasses.\n+Method `GenericServlet.init(ServletConfig config)` is the template method in this example.\n+\n+## 鸣谢\n+\n+* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)\n+* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)\n+* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)",
"filename": "zh/template-method/README.md",
"status": "added"
}
]
} |
{
"body": "\r\nLines 83-84: Could not find CarSimpleFactory. Isn't it CarsFactory?",
"comments": [
{
"body": "I am new to this. Can I take up this?",
"created_at": "2020-12-03T12:24:16Z"
},
{
"body": "@ohbus when handling issues set the correct labels and on close set the milestone",
"created_at": "2020-12-04T13:51:08Z"
},
{
"body": "> @ohbus when handling issues set the correct labels and on close set the milestone\n\nThank you for this guiding me on this.\n\nAnd Hacktoberfest is over, I guess we should remove this tag from the repository or stop using it for the time being.",
"created_at": "2020-12-04T13:59:37Z"
},
{
"body": "@ohbus before you know it, it will be the next Hactoberfest, so I would just leave it there :)",
"created_at": "2020-12-04T14:01:08Z"
}
],
"number": 1601,
"title": "Word mistake in factory/README.md"
} | {
"body": "Fix for #1601 \r\n",
"number": 1604,
"review_comments": [],
"title": "Word mistake in factory/README.md #1601"
} | {
"commits": [
{
"message": "Word mistake in factory/README.md #1601"
},
{
"message": "Merge branch 'master' into master"
}
],
"files": [
{
"diff": "@@ -81,7 +81,7 @@ public enum CarType {\n }\n ```\n Then we have the static method `getCar` to create car objects encapsulated in the factory class \n-`CarSimpleFactory`.\n+`CarsFactory`.\n \n ```java\n public class CarsFactory {",
"filename": "factory/README.md",
"status": "modified"
}
]
} |
{
"body": "At the moment the Service Layer pattern example does not produce log output at all.",
"comments": [],
"number": 1339,
"title": "Service Layer logging broken"
} | {
"body": "Pull request title\r\n\r\n- Fix broken logging in service layer\r\n- #1339\r\n\r\nPull request description\r\n\r\n- Changes in service-layer `logback.xml` to fix logging",
"number": 1342,
"review_comments": [],
"title": "Fix broken logging in service layer"
} | {
"commits": [
{
"message": "Fix broken logging in service layer"
}
],
"files": [
{
"diff": "@@ -43,6 +43,7 @@\n <logger name=\"com.iluwatar\" additivity=\"false\">\n <level value=\"DEBUG\"/>\n <appender-ref ref=\"FILE\"/>\n+ <appender-ref ref=\"STDOUT\"/>\n </logger>\n \n <logger name=\"org.hibernate\" additivity=\"false\">",
"filename": "service-layer/src/main/resources/logback.xml",
"status": "modified"
}
]
} |
{
"body": "Credits link in Aggregator Microservices is responded with a blank page. \r\nThe current link is http://blog.arungupta.me/microservice-design-patterns/",
"comments": [
{
"body": "Thanks for reporting @karthikmucheli. Would you like to create a pull request for that?",
"created_at": "2020-01-21T15:17:45Z"
}
],
"number": 1161,
"title": "Aggregator Microservices"
} | {
"body": " Page doesn't exist anymore, so changed to use web archive\r\n\r\nFixes #1161",
"number": 1214,
"review_comments": [],
"title": "Changing Aggregator Microservices pattern link"
} | {
"commits": [
{
"message": "Changing Aggregator Microservices pattern link\n\n Page doesn't exist anymore, so changed to use web archive"
}
],
"files": [
{
"diff": "@@ -27,4 +27,4 @@ Use the Aggregator Microservices pattern when you need a unified API for various\n \n ## Credits\n \n-* [Microservice Design Patterns](http://blog.arungupta.me/microservice-design-patterns/)\n+* [Microservice Design Patterns](http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/)",
"filename": "aggregator-microservices/README.md",
"status": "modified"
}
]
} |
{
"body": "",
"comments": [
{
"body": "Apparently you are talking about this https://github.com/iluwatar/java-design-patterns/blob/master/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java? Could you provide a more detailed description what is missing?",
"created_at": "2020-02-01T06:43:47Z"
},
{
"body": "Am I missing something, or is this an example of purely declarative programming?",
"created_at": "2020-02-01T13:52:49Z"
},
{
"body": "I think you are correct. The imperative style has been lost in recent refactoring. It should look more like https://github.com/iluwatar/java-design-patterns/blob/4904d7eea047b5b924dcf33092ed887300f44d10/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java",
"created_at": "2020-02-05T05:12:12Z"
}
],
"number": 1163,
"title": "ImperativeProgramming does not demonstracte Imperative-style in CollectonsPipeline Pattern"
} | {
"body": "Signed-off-by: yichen88 <tang.yichenyves@gmail.com>\r\n\r\n\r\nPull request title\r\n\r\n- Clearly and concisely describes what it does\r\n- Refer to the issue that it solves, if available\r\n\r\n\r\n\r\nPull request description\r\n\r\n- Describes the main changes that come with the pull request\r\n- Any relevant additional information is provided\r\n#1163 \r\n\r\n\r\n> For detailed contributing instructions see https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute\r\n",
"number": 1180,
"review_comments": [],
"title": "Fix imperative-style."
} | {
"commits": [
{
"message": "Fix imperative-style.\n\nSigned-off-by: yichen88 <tang.yichenyves@gmail.com>"
}
],
"files": [
{
"diff": "@@ -23,12 +23,12 @@\n \n package com.iluwatar.collectionpipeline;\n \n-import java.util.Collection;\n+import java.util.ArrayList;\n import java.util.Collections;\n import java.util.Comparator;\n+import java.util.HashMap;\n import java.util.List;\n import java.util.Map;\n-import java.util.stream.Collectors;\n \n /**\n * Imperative-style programming to iterate over the list and get the names of cars made later than\n@@ -57,11 +57,27 @@ private ImperativeProgramming() {\n * @return {@link List} of {@link String} of car models built after year 2000\n */\n public static List<String> getModelsAfter2000(List<Car> cars) {\n- return cars.stream()\n- .filter(car -> car.getYear() > 2000)\n- .sorted(Comparator.comparingInt(Car::getYear))\n- .map(Car::getModel)\n- .collect(Collectors.toList());\n+ List<Car> carsSortedByYear = new ArrayList<>();\n+\n+ for (Car car : cars) {\n+ if (car.getYear() > 2000) {\n+ carsSortedByYear.add(car);\n+ }\n+ }\n+\n+ Collections.sort(carsSortedByYear, new Comparator<Car>() {\n+ @Override\n+ public int compare(Car car1, Car car2) {\n+ return car1.getYear() - car2.getYear();\n+ }\n+ });\n+\n+ List<String> models = new ArrayList<>();\n+ for (Car car : carsSortedByYear) {\n+ models.add(car.getModel());\n+ }\n+\n+ return models;\n }\n \n /**\n@@ -71,7 +87,17 @@ public static List<String> getModelsAfter2000(List<Car> cars) {\n * @return {@link Map} with category as key and cars belonging to that category as value\n */\n public static Map<Category, List<Car>> getGroupingOfCarsByCategory(List<Car> cars) {\n- return cars.stream().collect(Collectors.groupingBy(Car::getCategory));\n+ Map<Category, List<Car>> groupingByCategory = new HashMap<>();\n+ for (Car car : cars) {\n+ if (groupingByCategory.containsKey(car.getCategory())) {\n+ groupingByCategory.get(car.getCategory()).add(car);\n+ } else {\n+ List<Car> categoryCars = new ArrayList<>();\n+ categoryCars.add(car);\n+ groupingByCategory.put(car.getCategory(), categoryCars);\n+ }\n+ }\n+ return groupingByCategory;\n }\n \n /**\n@@ -82,11 +108,25 @@ public static Map<Category, List<Car>> getGroupingOfCarsByCategory(List<Car> car\n * @return {@link List} of {@link Car} to belonging to the group\n */\n public static List<Car> getSedanCarsOwnedSortedByDate(List<Person> persons) {\n- return persons.stream()\n- .map(Person::getCars)\n- .flatMap(Collection::stream)\n- .filter(car -> car.getCategory() == Category.SEDAN)\n- .sorted(Comparator.comparingInt(Car::getYear))\n- .collect(Collectors.toList());\n+ List<Car> cars = new ArrayList<>();\n+ for (Person person : persons) {\n+ cars.addAll(person.getCars());\n+ }\n+\n+ List<Car> sedanCars = new ArrayList<>();\n+ for (Car car : cars) {\n+ if (Category.SEDAN.equals(car.getCategory())) {\n+ sedanCars.add(car);\n+ }\n+ }\n+\n+ sedanCars.sort(new Comparator<Car>() {\n+ @Override\n+ public int compare(Car o1, Car o2) {\n+ return o1.getYear() - o2.getYear();\n+ }\n+ });\n+\n+ return sedanCars;\n }\n }",
"filename": "collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java",
"status": "modified"
}
]
} |
{
"body": "In issue #518 it was proposed to change the relationship between decorator and target (in the code example between Troll und SmartTroll) from a composition to an aggregation with the argumentation that in a composition both instances cannot live without the other one. I disagree with this argumentation and I just checked the UML spec from OMG (available at https://www.omg.org/spec/UML/2.5.1/). An example in the UML spec are wheels which are part of a car (composition), but wheels can exist without a car (in particular I just exchanged my summer wheels with winter wheels).\r\n\r\n\r\nThe spec states:\r\n\r\n> Composite aggregation is a strong form of aggregation that requires a part object be included in at most one composite object at a time. If a composite object is deleted, all of its part instances that are objects are deleted with it.\r\n> NOTE. A part object may (where otherwise allowed) be removed from a composite object before the composite object is deleted, and thus not be deleted as part of the composite object.\r\n\r\nThe main properties are that\r\n1. a part may be part of at most one composite. I think that this holds for the decorator pattern, i.e. you can't decorate an instance with two different decorators, but rather the idea is that the original reference is replaced with the reference to the decorator.\r\n2. deleting an object in one part of the graph will also result in the deletion of all objects of the subgraph below that object. But this holds for the decorator as well, i.e. if you release the smart troll instance, then the troll instance is released as well.\r\n\r\nTherefore I recommend to switch back from aggregation to composition.\r\n\r\nBest wishes\r\nDominik\r\n",
"comments": [
{
"body": "Thanks for the extensive explanation. Looking at the source code, I see that `ClubbedTroll` really can't exist without `Troll`. So you are right, it is a bug and should be fixed.",
"created_at": "2019-11-18T17:04:02Z"
},
{
"body": "well, don't be bedazzled by an extensive explanation ;-)\r\n\r\nThe argument raised in issue #518 was a symmetric one, i.e. it was stated that the `Troll` could also live without the `ClubbedTroll` and that therefore the association is an aggregation instead of a composition. Stated in #518, for a composition both instances, the whole and the part, cannot live without each other. Obviously, the `ClubbedTroll` cannot live without a `Troll`, but the `Troll` can obviously live without the `ClubbedTroll`. \r\n\r\nI argue that the _cannot live without_ argument is the wrong one, even in a composition the part could live in isolation, but the difference is that in a composition the part can be part of at most one whole, and this is what counts in this case, therefore I consider this relationship as a composition.\r\n",
"created_at": "2019-11-18T17:23:36Z"
},
{
"body": "Closed with commit #1096.",
"created_at": "2019-11-18T17:27:28Z"
}
],
"number": 1095,
"title": "Decorator: Composition instead of Aggregation"
} | {
"body": "As described in issue #1095, this pull request changes the description of the association between the decorator and its inner object. The current version states that this is an aggregation, but as explained in issue #1095 this should be a composition.\r\n\r\n",
"number": 1096,
"review_comments": [],
"title": "Changes the description of the decorator pattern (as described in issue #1095)"
} | {
"commits": [
{
"message": "Changes aggregation to composition (as described in issue #1095)"
}
],
"files": [
{
"diff": "@@ -28,7 +28,7 @@\n \n /**\n * The Decorator pattern is a more flexible alternative to subclassing. The Decorator class\n- * implements the same interface as the target and uses aggregation to \"decorate\" calls to the\n+ * implements the same interface as the target and uses composition to \"decorate\" calls to the\n * target. Using the Decorator pattern it is possible to change the behavior of the class during\n * runtime.\n *",
"filename": "decorator/src/main/java/com/iluwatar/decorator/App.java",
"status": "modified"
}
]
} |
{
"body": "When running `mvn clean install` from project's submodules, the following error message is outputted\r\n\r\n```\r\nFailed to execute goal com.mycila:license-maven-plugin:3.0:format (install-format) on project adapter: Resource license-plugin-header-style.xml not found in file system, classpath or URL: no protocol: license-plugin-header-style.xml\r\n```\r\n\r\nBuilding from the submodules should work as well as building from the multimodule root.",
"comments": [],
"number": 1037,
"title": "Error when building from submodule directories"
} | {
"body": "Closes #1037 \r\n\r\nThe license-plugin-header-style.xml in the root directory was not resolved correctly when the project was built from a submodule directory, so I ended up adding a new plugin `directory-maven-plugin` which does that.\r\n\r\nOther solutions were to use the `${maven.multiModuleProjectDirectory}` property, but I was not able to make it work, or to add a relative path property to each of the submodules `<properties><projectRoot>${parent.basedir}</projectRoot></properties>`, but this configuration would be difficult to maintain, as there are 120 submodules.",
"number": 1045,
"review_comments": [],
"title": "#1037: Fix error when building from a submodule directory"
} | {
"commits": [
{
"message": "Fix error when building from a submodule directory\n\nAdd directory-maven-plugin to resolve the location of the\nlicense-plugin-header-style.xml from a submodule directory"
}
],
"files": [
{
"diff": "@@ -406,6 +406,31 @@\n </executions>\n </plugin>\n \n+ <!-- Resolves ${projectRoot} to the project root directory.\n+ Used by the license-maven-plugin to find the correct location of\n+ license-plugin-header-style.xml when built from a submodule directory. -->\n+ <plugin>\n+ <groupId>org.commonjava.maven.plugins</groupId>\n+ <artifactId>directory-maven-plugin</artifactId>\n+ <version>0.3.1</version>\n+ <executions>\n+ <execution>\n+ <id>directories</id>\n+ <goals>\n+ <goal>directory-of</goal>\n+ </goals>\n+ <phase>initialize</phase>\n+ <configuration>\n+ <property>projectRoot</property>\n+ <project>\n+ <groupId>com.iluwatar</groupId>\n+ <artifactId>java-design-patterns</artifactId>\n+ </project>\n+ </configuration>\n+ </execution>\n+ </executions>\n+ </plugin>\n+\n <plugin>\n <groupId>com.mycila</groupId>\n <artifactId>license-maven-plugin</artifactId>\n@@ -417,7 +442,7 @@\n </properties>\n <skipExistingHeaders>true</skipExistingHeaders>\n <headerDefinitions>\n- <headerDefinition>license-plugin-header-style.xml</headerDefinition>\n+ <headerDefinition>${projectRoot}${file.separator}license-plugin-header-style.xml</headerDefinition>\n </headerDefinitions>\n <mapping>\n <java>SLASHSTAR_CUSTOM_STYLE</java>",
"filename": "pom.xml",
"status": "modified"
}
]
} |
{
"body": "Steps to recreate:\r\n\r\n1. In Eclipse, select a unit test to run by right-clicking and selecting: \"Run Configurations.\" Select a JUnit execution and ensure that the JUnit5 runner is selected:\r\n\r\n\r\n1. Click the Run button. \r\n\r\n1. The following error is shown: \r\n\r\nand the following stack trace is displayed:\r\n\r\n```\r\njava.lang.NoClassDefFoundError: org/junit/platform/commons/PreconditionViolationException\r\n\tat org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createUnfilteredTest(JUnit5TestLoader.java:75)\r\n\tat org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createTest(JUnit5TestLoader.java:66)\r\n\tat org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.loadTests(JUnit5TestLoader.java:53)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:525)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)\r\nCaused by: java.lang.ClassNotFoundException: org.junit.platform.commons.PreconditionViolationException\r\n\tat java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)\r\n\tat java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)\r\n\tat java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)\r\n\t... 7 more\r\n```\r\n\r\n\r\n\r\n\r\nWorkaround: Run the mvn test on the command line and the tests will execute. \r\n\r\nAccording to the following Stackoverflow: https://stackoverflow.com/questions/57040675/java-lang-noclassdeffounderror-org-junit-platform-commons-preconditionviolation adding the following dependency to the project will fix. (I've tried with the example project and it seems to work). \r\n\r\n```\r\n <dependency>\r\n <groupId>org.junit.platform</groupId>\r\n <artifactId>junit-platform-commons</artifactId>\r\n <version>1.5.2</version>\r\n </dependency>\r\n```",
"comments": [
{
"body": "I got this at work today as well, and we solved it with the above suggested solution. I can prepare a PR for it if noone else already did it?",
"created_at": "2019-10-16T14:32:06Z"
},
{
"body": "Sure @lbroman, PR is welcome",
"created_at": "2019-10-16T15:25:30Z"
},
{
"body": "Instead of inserting `junit-platform-commons` in each of the ~120 module poms a better fix would be to just update JUnit 5 to the most current version...",
"created_at": "2019-10-17T07:47:49Z"
},
{
"body": "Does this fix the problem?\r\n\r\nI suggested in my PR (not visible here) that a better aproach might also be to upgrade the last junit 4 projects to jupiter and then pull the jupiter dependencies up to the root pom.",
"created_at": "2019-10-17T07:59:57Z"
},
{
"body": "Yes it does, because JUnit 5.5.2 transitively pulls junit-platform-commons 1.5.2:\r\n\r\n\r\n",
"created_at": "2019-10-17T08:37:01Z"
},
{
"body": "Tried updating to 5.5.2 and it broke the maven build, current version dates back to 2017...\r\njunit-platform-commons is in the current dependency tree also, but 1.0.2.\r\n\r\nAlso noticed I cannot reproduce this issue on Eclipse EE but only on Eclipse Java, so is problably eclipse edition related. Will test this by managing the junit-platforms-commons version instead and see what that might bring.",
"created_at": "2019-10-17T09:28:51Z"
},
{
"body": "Updating to 5.5.2 works for me. In addition `junit-jupiter-api` have to be added in the parent pom because `spring-boot-dependencies` imports and old version of this. \r\n\r\nNow the tests run on the command line as well as from eclipse. I'll submit a pull request.\r\n\r\n\r\n\r\n\r\n\r\n\r\nA future improvement may be to remove all `junit-jupiter-*` dependencies and replace them by the aggregator dependency [`junit-jupiter`](https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter/5.5.2) which was introduces with 5.4.0.",
"created_at": "2019-10-17T13:13:04Z"
},
{
"body": "Another option is to switch to TestNG.",
"created_at": "2019-10-17T13:36:51Z"
},
{
"body": "java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: org/junit/platform/engine/EngineDiscoveryListener\r\n\tat org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.getLauncherDiscoveryListener(LauncherDiscoveryRequestBuilder.java:241)\r\n\tat org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.build(LauncherDiscoveryRequestBuilder.java:235)\r\n\tat org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createUnfilteredTest(JUnit5TestLoader.java:75)\r\n\tat org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createTest(JUnit5TestLoader.java:66)\r\n\tat org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.loadTests(JUnit5TestLoader.java:53)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:526)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)\r\nCaused by: java.lang.NoClassDefFoundError: org/junit/platform/engine/EngineDiscoveryListener\r\n\tat java.lang.ClassLoader.defineClass1(Native Method)\r\n\tat java.lang.ClassLoader.defineClass(Unknown Source)\r\n\tat java.security.SecureClassLoader.defineClass(Unknown Source)\r\n\tat java.net.URLClassLoader.defineClass(Unknown Source)\r\n\tat java.net.URLClassLoader.access$100(Unknown Source)\r\n\tat java.net.URLClassLoader$1.run(Unknown Source)\r\n\tat java.net.URLClassLoader$1.run(Unknown Source)\r\n\tat java.security.AccessController.doPrivileged(Native Method)\r\n\tat java.net.URLClassLoader.findClass(Unknown Source)\r\n\tat java.lang.ClassLoader.loadClass(Unknown Source)\r\n\tat sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)\r\n\tat java.lang.ClassLoader.loadClass(Unknown Source)\r\n\t... 9 more\r\nCaused by: java.lang.ClassNotFoundException: org.junit.platform.engine.EngineDiscoveryListener\r\n\tat java.net.URLClassLoader.findClass(Unknown Source)\r\n\tat java.lang.ClassLoader.loadClass(Unknown Source)\r\n\tat sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)\r\n\tat java.lang.ClassLoader.loadClass(Unknown Source)\r\n\t... 21 more\r\n",
"created_at": "2021-01-13T15:03:58Z"
}
],
"number": 1007,
"title": "JUnit5 test are not able to run in Eclipse"
} | {
"body": "Added dependencies to junit-platform-commons to make jupiter modules work in eclipse.\r\nDid this with a script because of the large amount of modules to modify, pom file indenting is not consequent and those might look ugly. Maybe this should be cleaned up with a global reformat?\r\n\r\nAlso, it would be wise to move all module to jupiter and then pull up the unit test dependencies to the root pom.\r\n\r\n\r\nFixes #1007",
"number": 1013,
"review_comments": [],
"title": "Added dep to make jupiter work in eclipse #1007"
} | {
"commits": [
{
"message": "Added junit-platform-commons to all jupiter modules to make junit work in eclipse"
}
],
"files": [
{
"diff": "@@ -38,5 +38,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+ <dependency>\n+ <groupId>org.junit.platform</groupId>\n+ <artifactId>junit-platform-commons</artifactId>\n+ <scope>test</scope>\n+ </dependency>\n </dependencies>\n </project>",
"filename": "abstract-document/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,5 +38,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+ <dependency>\n+ <groupId>org.junit.platform</groupId>\n+ <artifactId>junit-platform-commons</artifactId>\n+ <scope>test</scope>\n+ </dependency>\n </dependencies>\n </project>",
"filename": "abstract-factory/pom.xml",
"status": "modified"
},
{
"diff": "@@ -61,6 +61,11 @@\n \t\t<artifactId>junit-jupiter-engine</artifactId>\n \t\t<scope>test</scope>\n \t</dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n \t\t<dependency>\n \t\t\t<groupId>org.mockito</groupId>\n \t\t\t<artifactId>mockito-all</artifactId>",
"filename": "acyclic-visitor/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,6 +38,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n <dependency>\n <groupId>org.mockito</groupId>\n <artifactId>mockito-core</artifactId>",
"filename": "adapter/pom.xml",
"status": "modified"
},
{
"diff": "@@ -48,6 +48,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n <dependency>\n <groupId>org.mockito</groupId>\n <artifactId>mockito-core</artifactId>",
"filename": "aggregator-microservices/aggregator-service/pom.xml",
"status": "modified"
},
{
"diff": "@@ -50,6 +50,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n \n <build>",
"filename": "aggregator-microservices/information-microservice/pom.xml",
"status": "modified"
},
{
"diff": "@@ -49,6 +49,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n \n <build>",
"filename": "aggregator-microservices/inventory-microservice/pom.xml",
"status": "modified"
},
{
"diff": "@@ -39,5 +39,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n </project>",
"filename": "ambassador/pom.xml",
"status": "modified"
},
{
"diff": "@@ -48,6 +48,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n <dependency>\n <groupId>org.mockito</groupId>\n <artifactId>mockito-core</artifactId>",
"filename": "api-gateway/api-gateway-service/pom.xml",
"status": "modified"
},
{
"diff": "@@ -48,6 +48,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n \n <build>",
"filename": "api-gateway/image-microservice/pom.xml",
"status": "modified"
},
{
"diff": "@@ -50,6 +50,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n \n <build>",
"filename": "api-gateway/price-microservice/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,6 +38,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n <dependency>\n <groupId>org.mockito</groupId>\n <artifactId>mockito-core</artifactId>",
"filename": "async-method-invocation/pom.xml",
"status": "modified"
},
{
"diff": "@@ -40,6 +40,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n \n ",
"filename": "balking/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,6 +38,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n <dependency>\n <groupId>org.mockito</groupId>\n <artifactId>mockito-core</artifactId>",
"filename": "bridge/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,5 +38,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n </project>",
"filename": "builder/pom.xml",
"status": "modified"
},
{
"diff": "@@ -39,6 +39,11 @@\n \t\t\t<artifactId>junit-jupiter-engine</artifactId>\n \t\t\t<scope>test</scope>\n \t\t</dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n \t\t<dependency>\n \t\t\t<groupId>org.mockito</groupId>\n \t\t\t<artifactId>mockito-core</artifactId>",
"filename": "business-delegate/pom.xml",
"status": "modified"
},
{
"diff": "@@ -40,6 +40,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n \n </project>\n\\ No newline at end of file",
"filename": "bytecode/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,6 +38,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n <dependency>\n <groupId>org.mongodb</groupId>\n <artifactId>mongodb-driver</artifactId>",
"filename": "caching/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,5 +38,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n </project>",
"filename": "callback/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,5 +38,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n </project>",
"filename": "chain/pom.xml",
"status": "modified"
},
{
"diff": "@@ -36,5 +36,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n </project>",
"filename": "circuit-breaker/pom.xml",
"status": "modified"
},
{
"diff": "@@ -36,5 +36,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n </project>",
"filename": "collection-pipeline/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,5 +38,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n </project>",
"filename": "command/pom.xml",
"status": "modified"
},
{
"diff": "@@ -36,5 +36,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n </project>",
"filename": "commander/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,5 +38,10 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n </project>",
"filename": "composite/pom.xml",
"status": "modified"
},
{
"diff": "@@ -38,6 +38,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n <dependency>\n <groupId>com.google.guava</groupId>\n <artifactId>guava</artifactId>",
"filename": "converter/pom.xml",
"status": "modified"
},
{
"diff": "@@ -39,6 +39,11 @@\n \t\t\t<artifactId>junit-jupiter-engine</artifactId>\n \t\t\t<scope>test</scope>\n \t\t</dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n \t\t<dependency>\n \t\t\t<groupId>com.h2database</groupId>\n \t\t\t<artifactId>h2</artifactId>",
"filename": "cqrs/pom.xml",
"status": "modified"
},
{
"diff": "@@ -40,6 +40,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n <dependency>\n <groupId>com.h2database</groupId>\n <artifactId>h2</artifactId>",
"filename": "dao/pom.xml",
"status": "modified"
},
{
"diff": "@@ -42,6 +42,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n <dependency>\n <groupId>org.mockito</groupId>\n <artifactId>mockito-core</artifactId>",
"filename": "data-bus/pom.xml",
"status": "modified"
},
{
"diff": "@@ -40,6 +40,11 @@\n <artifactId>junit-jupiter-engine</artifactId>\n <scope>test</scope>\n </dependency>\n+\t\t<dependency>\n+\t\t\t<groupId>org.junit.platform</groupId>\n+\t\t\t<artifactId>junit-platform-commons</artifactId>\n+\t\t\t<scope>test</scope>\n+\t\t</dependency>\n </dependencies>\n \n </project>\n\\ No newline at end of file",
"filename": "data-locality/pom.xml",
"status": "modified"
}
]
} |
{
"body": "\r\n",
"comments": [
{
"body": "Fixed intermittent issue #1001",
"created_at": "2019-10-14T19:34:39Z"
},
{
"body": "Didn't see @afflato already took this, sorry!",
"created_at": "2019-10-14T20:46:07Z"
}
],
"number": 1001,
"title": "Intermittent test failure in Spatial Partition pattern"
} | {
"body": "#1001 QuadTreeTest was showing intermittent failures. \r\n\r\nThe problem was due to the Rect data structure using int to store values (x, y, height, width). \r\n\r\nSince the QuadTree divides its space in four, we need to either to change the Rect data structure or the divide algorithm. \r\n\r\nI find the former more readable and clear.\r\n",
"number": 1008,
"review_comments": [],
"title": "#1001 fix intermittent test failure - changing Rect coordinates to double."
} | {
"commits": [
{
"message": "#1001 fix intermittent test failure"
}
],
"files": [
{
"diff": "@@ -28,14 +28,14 @@\n */\n \n public class Rect {\n- int x; \n- int y; \n- int width;\n- int height;\n+ double x;\n+ double y;\n+ double width;\n+ double height;\n \n //(x,y) - centre of rectangle\n \n- Rect(int x, int y, int width, int height) {\n+ Rect(double x, double y, double width, double height) {\n this.x = x;\n this.y = y;\n this.width = width;",
"filename": "spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java",
"status": "modified"
}
]
} |
{
"body": "\r\n",
"comments": [
{
"body": "Fixed intermittent issue #1001",
"created_at": "2019-10-14T19:34:39Z"
},
{
"body": "Didn't see @afflato already took this, sorry!",
"created_at": "2019-10-14T20:46:07Z"
}
],
"number": 1001,
"title": "Intermittent test failure in Spatial Partition pattern"
} | {
"body": "\r\nIntermittent test failure in Spatial Partition pattern #1001\r\n\r\n\r\nTested with repeated test for a sample of 10000 repeatitions to ensure intermittent issue doesn't come again.\r\n\r\n- field should exist within the queryrange not other way.\r\n\r\n\r\n\r\n> For detailed contributing instructions see https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute\r\n",
"number": 1006,
"review_comments": [],
"title": "Intermittent test failure in Spatial Partition pattern #1001"
} | {
"commits": [
{
"message": "Intermittent test failure in Spatial Partition pattern #1001"
},
{
"message": "Intermittent test failure in Spatial Partition pattern #1001"
}
],
"files": [
{
"diff": "@@ -26,6 +26,8 @@\n import java.util.ArrayList;\n import java.util.Hashtable;\n import java.util.Random;\n+\n+\n import org.junit.jupiter.api.Test;\n \n /**\n@@ -50,12 +52,12 @@ void queryTest() {\n \n static Hashtable<Integer, Point> quadTreeTest(ArrayList<Point> points, Rect field, Rect queryRange) {\n //creating quadtree and inserting all points\n- QuadTree qTree = new QuadTree(field, 4);\n+ QuadTree qTree = new QuadTree(queryRange, 4);\n for (int i = 0; i < points.size(); i++) {\n qTree.insert(points.get(i));\n }\n \n- ArrayList<Point> queryResult = qTree.query(queryRange, new ArrayList<Point>());\n+ ArrayList<Point> queryResult = qTree.query(field, new ArrayList<Point>());\n Hashtable<Integer, Point> result = new Hashtable<Integer, Point>();\n for (int i = 0; i < queryResult.size(); i++) {\n Point p = queryResult.get(i);",
"filename": "spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java",
"status": "modified"
}
]
} |
{
"body": "\r\n",
"comments": [
{
"body": "\r\n",
"created_at": "2019-10-13T13:32:09Z"
}
],
"number": 996,
"title": "Sonar analysis in master branch is failing"
} | {
"body": "Fix #996 SonarCloud analysis failure in master branch by updating Travis configuration",
"number": 997,
"review_comments": [],
"title": "#996 Fix SonarCloud analysis failure"
} | {
"commits": [
{
"message": "#996 Update Travis config"
},
{
"message": "#996 Remove old secret"
},
{
"message": "#996 add coverage profile"
},
{
"message": "#996 move jacoco out of profile"
}
],
"files": [
{
"diff": "@@ -1,23 +1,27 @@\n language: java\n-dist: xenial\n+dist: bionic\n jdk:\n - openjdk11\n+sudo: required\n \n env:\n global:\n - GH_REF: github.com/iluwatar/java-design-patterns.git\n - secure: LxTDuNS/rBWIvKkaEqr79ImZAe48mCdoYCF41coxNXgNoippo4GIBArknqtv+XvdkiuRZ1yGyj6pn8GU33c/yn+krddTUkVCwTbVatbalW5jhQjDbHYym/JcxaK9ZS/3JTeGcWrBgiPqHEEDhCf26vPZsXoMSeVCEORVKTp1BSg=\n- - secure: \"eoWlW9GyTJY04P8K3pxayXwU9/hmptQg/LfirispQkV9YvmziCfSzXnatnBhNfud98sCzY8BScXnb+OWLTnjLKpId4rtEqb0aJ40Jc32cUKzgzFAUn7cNcDAbUIfyPAGVqyQqfj/11wYSADwWMMOPlW97ExUtoyiH2WenXuRHso=\"\n \n services:\n - xvfb\n \n-# default install command is just \"mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V\"\n-install:\n-- mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -e\n+addons:\n+ sonarcloud:\n+ organization: \"iluwatar\"\n+ token:\n+ secure: \"FpHwMYPMkdWU6CeIB7+O3qIeIM4vJMp47UjkKK53f0w0s6tPZofZZkab+gcL2TqKSil7sFVB/AQXU1cUubflRszwcLbNsc8H2yFehD79o0o0Mqd1Dd5ip/q0KQbHkkln+InFlVLfvrLB4Xd4mlQVxbGhqpULBhXjKzFzQlRFcuU=\"\n+script:\n+ # the following command line builds the project, runs the tests with coverage and then execute the SonarCloud analysis\n+ - mvn clean verify sonar:sonar -Dsonar.projectKey=iluwatar_java-design-patterns\n \n after_success:\n-- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=$SONAR_TOKEN\n - bash update-ghpages.sh\n \n notifications:\n@@ -29,5 +33,3 @@ notifications:\n on_success: change # options: [always|never|change] default: always\n on_failure: always # options: [always|never|change] default: always\n on_start: never # options: [always|never|change] default: always\n-\n-sudo: required",
"filename": ".travis.yml",
"status": "modified"
},
{
"diff": "@@ -353,37 +353,6 @@\n <build>\n <pluginManagement>\n <plugins>\n- <!-- This plugin's configuration is used to store Eclipse m2e settings\n- only. It has no influence on the Maven build itself. TODO: Remove when the\n- m2e plugin can correctly bind to Maven lifecycle -->\n- <plugin>\n- <groupId>org.eclipse.m2e</groupId>\n- <artifactId>lifecycle-mapping</artifactId>\n- <version>1.0.0</version>\n- <configuration>\n- <lifecycleMappingMetadata>\n- <pluginExecutions>\n- <pluginExecution>\n- <pluginExecutionFilter>\n- <groupId>org.jacoco</groupId>\n- <artifactId>\n- jacoco-maven-plugin\n- </artifactId>\n- <versionRange>\n- [0.6.2,)\n- </versionRange>\n- <goals>\n- <goal>prepare-agent</goal>\n- </goals>\n- </pluginExecutionFilter>\n- <action>\n- <ignore/>\n- </action>\n- </pluginExecution>\n- </pluginExecutions>\n- </lifecycleMappingMetadata>\n- </configuration>\n- </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n@@ -410,20 +379,6 @@\n </pluginManagement>\n \n <plugins>\n- <plugin>\n- <groupId>org.jacoco</groupId>\n- <artifactId>jacoco-maven-plugin</artifactId>\n- <version>${jacoco.version}</version>\n- <executions>\n- <execution>\n- <id>prepare-agent</id>\n- <goals>\n- <goal>prepare-agent</goal>\n- </goals>\n- </execution>\n- </executions>\n- </plugin>\n-\n <!--checkstyle plug-in. checking against googles styles\n see config at checkstyle.xml\n -->\n@@ -471,6 +426,27 @@\n </execution>\n </executions>\n </plugin>\n+\n+ <plugin>\n+ <groupId>org.jacoco</groupId>\n+ <artifactId>jacoco-maven-plugin</artifactId>\n+ <version>${jacoco.version}</version>\n+ <executions>\n+ <execution>\n+ <id>prepare-agent</id>\n+ <goals>\n+ <goal>prepare-agent</goal>\n+ </goals>\n+ </execution>\n+ <execution>\n+ <id>report</id>\n+ <goals>\n+ <goal>report</goal>\n+ </goals>\n+ </execution>\n+ </executions>\n+ </plugin>\n+\n </plugins>\n </build>\n ",
"filename": "pom.xml",
"status": "modified"
}
]
} |
{
"body": "After cloning the repo and opening the pipeline project Eclipse shows red errors indicating the project cannot compile:\r\n\r\nThe error is because of the layout of the project: after the src/main/java and\r\nsrc/test/java. The directory was: src/main/java/com.iluwatar.pipeline. It should be src/main/java/com/iluwatar/pipeline\r\n",
"comments": [],
"number": 993,
"title": "The pipeline project is not compiling in Eclipse"
} | {
"body": "#993 The source directory was not working in the 2019.09 version of Eclipse. The\r\nproblem was in the layout of the project: after the src/main/java and\r\nsrc/test/java, the directory was naed com.iluwatar.pipeline. It should've\r\nbeen com/iluwatar/pipeline. This follows the hierarchy of all of the other\r\npatterns.\r\n\r\nOnce these files were moved, the Pipeline project compiled without errors.",
"number": 994,
"review_comments": [],
"title": "993: Fixed the pipeines project layout so that it will load in Eclipse"
} | {
"commits": [
{
"message": "993: Fixed the pipeines project layout so that it will load in Eclipse\n\nThe source direcory was not working in the 2019.09 version of Eclipse. The\nproblem was in the layout of the project: after the src/main/java and\nsrc/test/java, the directory was naed com.iluwatar.pipeline. It should've\nbeen com/iluwatar/pipeline. This follows the hierachy of all of the other\npatterns.\n\nOnce these files were moved, the Pipeline project compiled without errors."
}
],
"files": []
} |
{
"body": "When building project with mvn install you get below warning. You need to setup the JXR plugin to get ride of this for multi-module projects.\r\n\r\n[INFO] --- maven-pmd-plugin:3.6:pmd (pmd) @ abstract-factory ---\r\n[WARNING] Unable to locate Source XRef to link to - DISABLED\r\nUnable to locate Source XRef to link to - DISABLED",
"comments": [
{
"body": "I can fix it!",
"created_at": "2019-10-03T18:59:29Z"
},
{
"body": "Nice @perwramdemark, go ahead!",
"created_at": "2019-10-03T19:15:35Z"
},
{
"body": "Related to https://github.com/iluwatar/java-design-patterns/issues/944",
"created_at": "2019-10-05T15:04:36Z"
}
],
"number": 939,
"title": "WARNING when building project"
} | {
"body": "This fixes build warnings in #939 \r\n\r\n- By adding the JXR plugin the PMD report can pickup links in site and warning disappears.\r\n \r\nNo more \"[WARNING] Unable to locate Source XRef to link to - DISABLED\" in output when building project.",
"number": 952,
"review_comments": [],
"title": "Add JXR plugin to get rid of WARNING Unable to locate Source XRef to …"
} | {
"commits": [
{
"message": "Add JXR plugin to get rid of WARNING Unable to locate Source XRef to link to"
}
],
"files": [
{
"diff": "@@ -465,6 +465,11 @@\n <artifactId>maven-pmd-plugin</artifactId>\n <version>${pmd.version}</version>\n </plugin>\n+ <plugin>\n+ <groupId>org.apache.maven.plugins</groupId>\n+ <artifactId>maven-jxr-plugin</artifactId>\n+ <version>3.0.0</version>\n+ </plugin>\n </plugins>\n </reporting>\n ",
"filename": "pom.xml",
"status": "modified"
}
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.