Cannot get aurelia-interactjs plugin to work using Aurelia CLI - aurelia

I'm trying out the aurelia-interactjs plugin to see if it meets my needs. I installed it into a new aurelia cli project by following all of the installation steps. I then added code for the Dragging section of the interactjs demo. The browser console displays the following error stating that interact is not a function:
Unhandled rejection TypeError: interact is not a function. (In 'interact(this.element)', 'interact' is undefined)
attached#http://localhost:9005/node_modules/aurelia-interactjs/dist/amd/interact-draggable.js:18:21
Here's my code:
app.html
<template>
<div id="drag-1" interact-draggable.bind="interactjsOptions">
<p> You can drag one element </p>
</div>
<div id="drag-2" interact-draggable.bind="interactjsOptions">
<p> with each pointer </p>
</div>
</template>
app.js
export class App {
constructor() {
this.interactjsOptions = {
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
restrict: {
restriction: "parent",
endOnly: true,
elementRect: {
top: 0,
left: 0,
bottom: 1,
right: 1
}
},
// enable autoScroll
autoScroll: true,
// call this function on every dragmove event
onmove: dragMoveListener,
// call this function on every dragend event
onend: function(event) {
var textEl = event.target.querySelector('p');
textEl && (textEl.textContent =
'moved a distance of ' +
(Math.sqrt(event.dx * event.dx +
event.dy * event.dy) | 0) + 'px');
}
};
}
}
function dragMoveListener(event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}

I am sorry, wrote the above in the bus on my commute to work on my phone didn't read all the code :-)
If you want to have the basic draggable sample (first one from http://interactjs.io/), which allows you to just drag elements around:
app.css
.draggable {
width: 25%;
height: 100%;
min-height: 6.5em;
margin: 10%;
background-color: #29e;
color: white;
border-radius: 0.75em;
padding: 4%;
-webkit-transform: translate(0px, 0px);
transform: translate(0px, 0px);
}
app.html
<template>
<require from="app.css"></require>
<div
interact-draggable.bind="interactOptions"
interact-dragend.delegate="dragEnd($event)"
interact-dragmove.delegate="dragMoveListener($event)"
class="draggable">
<p> You can drag one element </p>
</div>
<div
interact-draggable.bind="interactOptions"
interact-dragend.delegate="dragEnd($event)"
interact-dragmove.delegate="dragMoveListener($event)"
class="draggable">
<p> with each pointer </p>
</div>
</template>
app.ts (if you remove the public keyword in the function it will be valid js I think)
export class App {
public dragMoveListener(event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.detail.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.detail.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
public dragEnd(event) {
var textEl = event.target.querySelector('p');
textEl && (textEl.textContent =
'moved a distance of '
+ (Math.sqrt(event.detail.dx * event.detail.dx +
event.detail.dy * event.detail.dy)|0) + 'px');
}
public interactOptions = {
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
restrict: {
restriction: "parent",
endOnly: true,
elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
},
// enable autoScroll
autoScroll: true,
};
}

Related

Why is the Vuex action type unknown?

Why is the action type unknown, and what is the fix?
I know this is a common problem. I searched SO and there are ~20 answers, many of which are related to mapActions. After reading thru most all of those answers, and trying countless variations of mapActions syntax, I still can't figure out what's wrong with my code.
I understand, we are supposed to call dispatch in the component (or module), which then commits a mutation in the Vuex store (which is where the actual value gets changed).
Also, not sure if it's helpful to point out, but I expected to see the actions and mutations in the state pic below, but do not.
Update:
After editeding the code as a couple others suggested, the result is still the same; unknown action type: toggleIsCategoryWheelSpinning,{}
Not sure if it's relevant, but the line where dispatch is called myStore.dispatch("toggleIsCategoryWheelSpinning,{}"); in Wheel.vue is inside a nested function.
Here is my code:
//Wheel.vue
<template>
<div >
<div id="chart"></div>
</div>
</template>
<script type="text/javascript" charset="utf-8">
import store from 'vuex'
import { mapActions} from 'vuex'
export default {
name: "wheel",
props: {
wheelCategories: {
type: Array,
required: true,
},
expressions: {
type: Array,
required: true,
},
},
data() {
return {
};
},
mounted() {
let myscript = document.createElement("script");
myscript.setAttribute("src", "https://d3js.org/d3.v3.min.js");
document.head.appendChild(myscript);
myscript.onload = this.createWheel(this.wheelCategories,this.expressions, this.$store);
},
methods: {
...mapActions(['toggleIsCategoryWheelSpinning']),
created(){
this.toggleIsCategoryWheelSpinning
},
createWheel: function (wheelCategories,expressions, myStore) {
var padding = { top: 20, right: 40, bottom: 20, left: 20 },
w = 500 - padding.left - padding.right,
h = 500 - padding.top - padding.bottom,
r = Math.min(w, h) / 2,
rotation = 0,
oldrotation = 0,
picked = 100000,
oldpick = [],
color = d3.scale.category20();
var svg = d3
.select("#chart")
.append("svg")
.data([wheelCategories])
.attr("width", w + padding.left + padding.right)
.attr("height", h + padding.top + padding.bottom);
var container = svg
.append("g")
.attr("class", "chartholder")
.attr(
"transform",
"translate(" +
(w / 2 + padding.left) +
"," +
(h / 2 + padding.top) +
")"
)
.style({ cursor: "grab" });
var vis = container.append("g");
var pie = d3.layout
.pie()
.sort(null)
.value(function (d) {
return 1;
});
var arc = d3.svg.arc().outerRadius(r);
var arcs = vis
.selectAll("g.slice")
.data(pie)
.enter()
.append("g")
.attr("class", "slice");
arcs.append("path")
.attr("fill", function (d, i) {
return color(i);
})
.attr("d", function (d) {
return arc(d);
});
// add the text
arcs.append("text").attr("transform", function (d) {
d.innerRadius = 0;
d.outerRadius = r;
d.angle = (d.startAngle + d.endAngle) / 2;
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")translate(" + (d.outerRadius -10) +")";
})
.attr("text-anchor", "end")
.text(function (d, i) {
return wheelCategories[i].label;
});
container.on("click", spin);
function spin(d) {
container.on("click", null);
//the following line gives the "unknown action"
myStore.dispatch("toggleIsCategoryWheelSpinning,{}");
console.log('dispatch finished');
//all slices have been seen, all done
if (oldpick.length == wheelCategories.length) {
document.getElementById("spinResponse"
).innerHTML = `out of spins`;
container.on("click", null);
return;
}
var ps = 360 / wheelCategories.length,
pieslice = Math.round(1440 / wheelCategories.length),
rng = Math.floor(Math.random() * 1440 + 360);
rotation = Math.round(rng / ps) * ps;
picked = Math.round(
wheelCategories.length - (rotation % 360) / ps
);
picked =
picked >= wheelCategories.length
? picked % wheelCategories.length
: picked;
if (oldpick.indexOf(picked) !== -1) {
d3.select(this).call(spin);
return;
} else {
oldpick.push(picked);
}
rotation += 90 - Math.round(ps / 2);
let index = Math.floor(Math.random() * expressions.length); // 10 returns a random integer from 0 to 9
vis.transition()
.duration(3000)
.attrTween("transform", rotTween)
.each("end", function () {
oldrotation = rotation;
container.on("click", spin);
});
}
//make arrow
svg.append("g")
.attr(
"transform",
"translate(" +
(w + padding.left + padding.right) +
"," +
(h / 2 + padding.top) +
")"
)
.append("path")
.attr(
"d",
"M-" +
r * 0.15 +
",0L0," +
r * 0.05 +
"L0,-" +
r * 0.05 +
"Z"
)
.style({ fill: "black" });
//draw spin circle
container
.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", 60)
.style({ fill: "white", cursor: "grab" });
//spin text
container
.append("text")
.attr("x", 0)
.attr("y", 15)
.attr("text-anchor", "middle")
.text("SPIN ME!")
.style({
"font-weight": "bold",
"font-size": "25px",
cursor: "grab",
});
function rotTween(to) {
var i = d3.interpolate(oldrotation % 360, rotation);
return function (t) {
return "rotate(" + i(t) + ")";
};
}
function getRandomNumbers() {
var array = new Uint16Array(1000);
var scale = d3.scale
.linear()
.range([360, 1440])
.domain([0, 100000]);
if (
window.hasOwnProperty("crypto") &&
typeof window.crypto.getRandomValues === "function"
) {
window.crypto.getRandomValues(array);
console.log("works");
} else {
//no support for crypto, get crappy random numbers
for (var i = 0; i < 1000; i++) {
array[i] = Math.floor(Math.random() * 100000) + 1;
}
}
return array;
}
}
}
};
//end code for wheel
</script>
<style type="text/css" scoped>
text {
font-size: 15px;
pointer-events: grab;
}
#chart {
/* cursor: grab; */
margin: 0 auto;
border: 10px;
}
#question {
text-align: center;
}
#question h1 {
font-size: 50px;
font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
/* position: absolute; */
padding: 0;
margin: 0;
top: 50%;
-webkit-transform: translate(0, -50%);
transform: translate(0, -50%);
}
#spinResponse {
font-size: 30px;
text-align: center;
width: 500px;
padding-bottom: 30px;
background-color: rgb(129, 19, 19);
font-weight: bold;
}
</style>
the vuex store
// store/index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const foodCategories = [
//...
];
const expressions = [
//...
];
const isCategoryWheelSpinning = false;
export default new Vuex.Store({
state: {
foodCategories,
expressions,
isCategoryWheelSpinning,
},
getters: {
},
actions: {
toggleIsCategoryWheelSpinning(context,payload){
context.commit("toggleIsCategoryWheelSpinning",payload);
}
},
mutations: {
toggleIsCategoryWheelSpinning(state, payload) {
state.isCategoryWheelSpinning = !isCategoryWheelSpinning;
},
},
});
and the main.js
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store';
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App),
}).$mount('#app')
your action name mismatches. It should be same for your code.
Try to use :...mapActions(["toggleIsCategoryWheelSpinning"] for importing the action
In your actions in the store, there is no action called action_toggleIsCategoryWheelSpinning, but there is one called toggleIsCategoryWheelSpinning, so in your mapActions you should import that:
methods: {
mapActions(['toggleIsCategoryWheelSpinning'])
}
The comment from #Tao (see below) lead to (is) the answer; specifically the bold text.
The following code edits fixed the problem.
In Wheel.vue, edit the methods section
...mapActions(['toggleIsCategoryWheelSpinning']),
created(){
this.toggleIsCategoryWheelSpinning
},
When dispatch is called, changed from the first line to the second.
myStore.dispatch("toggleIsCategoryWheelSpinning,{}");
myStore.dispatch("toggleIsCategoryWheelSpinning",{});
An action is called with two parameters: name, which is a string in
the form of {module/}{action} (with module names when you're using
modules) and payload, which can be an object (or array, which is still
an object) or any primitive (string, boolean, number, etc...). So call
it as dispatch("toggleIsCategoryWheelSpinning", {}) if you want to
call it with an empty object as payload. You've placed the payload
inside the name parameter and it results into a string which doesn't
map onto a known action. – tao 30 mins ago

How to break the line with vue-typer without breaking word

I'm working with vue-typer and it adjusts on screen according to the space. But, depending the size of the screen, the vue-typer breaks the word. I want to break just when we have backspace. The code is:
<vue-typer
class="text-h4 font-weight-bold"
text="Nós acreditamos que o futuro pode ser incrível. Quer criar
ele com a gente?" :repeat='0'
></vue-typer><br>
Here is the image of how is working now
I dont know if anyone is still dealing with this issue, I have written a quick fix to the issue. Its not perfect but does the job.
You will run the text through a Method that will auto add in the line breaks automatically.
<div
style="
font-size: 30pt;
margin: auto;
color: white;
max-width: 600px;
"
ref="theRef"
>
<vue-typer
v-if="startTypers"
:text="[
formatText(
'TextHere',
'theRef',
22
),
]"
:repeat="0"
:shuffle="false"
initial-action="typing"
:pre-type-delay="70"
:type-delay="70"
:pre-erase-delay="2000"
:erase-delay="100"
erase-style="backspace"
:erase-on-complete="false"
caret-animation="blink"
></vue-typer>
</div>
mounted() {
setTimeout(() => {
this.startTypers = true;
}, 150);
}
The reason for the startTypers is because they will run the formatText method before the div has been rendered. Meaning you won't be able to get the clientWidth of the parent div.
formatText(text, ref, textSize = 22) {
let maxChars = Math.floor(this.$refs[ref].clientWidth / textSize);
let words = text.split(" ");
let breaked = "";
let currentCount = 0;
words.forEach((word) => {
currentCount += word.length;
currentCount += 1;
if (currentCount >= maxChars) {
currentCount = word.length;
breaked = `${breaked}\n${word} `;
} else {
breaked = `${breaked}${word} `;
}
});
return breaked;
},
The Parameters for formatText are the Text that you want to have the line breaks added in, The name of the ref, and the size of the span(Chars) that is rendered (22 was the default for the font and font-size I used in my use case, yours will vary)
Hopefully this helps
In order to break the text into chunks, consider the following
data() {
text : 'Hello World! I`m clarification masterjam!',
},
computed : {
textComputed() {
let n = "\n"
let breaked = this.text.match(/.{1,25}/g);
breaked[0];
var pos = breaked[0].lastIndexOf(' ');
breaked[0] = breaked[0].substring(0,pos)+n+breaked[0].substring(pos+1);
return breaked.join('')
},
}

"accept" drop option does not work in aurelia-interactjs

I'm testing out the aurelia-interactjs plugin with the Drag and Drop section of the interactjs demo code. Everything is working fine except the "accept" drop option on the target areas. The targets accept both draggable sources instead of just the one with an id of "yes-drop". In other words, the "inner-dropzone" and "outer-dropzone" targets accept a drop of the "no-drop" source even though the drop options specify accept: '#yes-drop'.
Here's the code:
drag-and-drop.html
<template>
<require from="./dragging-only.css"></require>
<require from="./drag-and-drop.css"></require>
<div interact-draggable.bind="dragOptions" interact-dragend.delegate="dragEnd($event)" interact-dragmove.delegate="dragMoveListener($event)" id="no-drop" class="draggable drag-drop"> #no-drop </div>
<div interact-draggable.bind="dragOptions" interact-dragend.delegate="dragEnd($event)" interact-dragmove.delegate="dragMoveListener($event)" id="yes-drop" class="draggable drag-drop"> #yes-drop </div>
<div interact-dropzone.bind="dropOptions" interact-dropactivate.delegate="dropActivate($event)" interact-dragenter.delegate="dragEnter($event)" interact-dragleave.delegate="dragLeave($event)" interact-drop.delegate="drop($event)" interact-dropdeactivate.delegate="dropDeactivate($event)" id="outer-dropzone" class="dropzone">
#outer-dropzone
<div interact-dropzone.bind="dropOptions" interact-dropactivate.delegate="dropActivate($event)" interact-dragenter.delegate="dragEnter($event)" interact-dragleave.delegate="dragLeave($event)" interact-drop.delegate="drop($event)" interact-dropdeactivate.delegate="dropDeactivate($event)" id="inner-dropzone" class="dropzone">#inner-dropzone</div>
</div>
</template>
drag-and-drop.js (dropOptions is defined at the end)
export class DragAndDrop {
dragMoveListener(event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.detail.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.detail.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the position attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
dragEnd(event) {
var textEl = event.target.querySelector('p');
textEl && (textEl.textContent =
'moved a distance of ' +
(Math.sqrt(event.detail.dx * event.detail.dx +
event.detail.dy * event.detail.dy) | 0) + 'px');
}
dropActivate(customEvent) {
let event = customEvent.detail;
// add active dropzone feedback
event.target.classList.add('drop-active');
}
dragEnter(customEvent) {
let event = customEvent.detail;
var draggableElement = event.relatedTarget,
dropzoneElement = event.target;
// feedback the possibility of a drop
dropzoneElement.classList.add('drop-target');
draggableElement.classList.add('can-drop');
draggableElement.textContent = 'Dragged in';
}
dragLeave(customEvent) {
let event = customEvent.detail;
// remove the drop feedback style
event.target.classList.remove('drop-target');
event.relatedTarget.classList.remove('can-drop');
event.relatedTarget.textContent = 'Dragged out';
}
drop(customEvent) {
let event = customEvent.detail;
event.relatedTarget.textContent = 'Dropped';
}
dropDeactivate(customEvent) {
let event = customEvent.detail;
// remove active dropzone feedback
event.target.classList.remove('drop-active');
event.target.classList.remove('drop-target');
}
dragOptions = {
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
restrict: {
restriction: "parent",
endOnly: true,
elementRect: {
top: 0,
left: 0,
bottom: 1,
right: 1
}
},
// enable autoScroll
autoScroll: true,
};
dropOptions = {
// only accept elements matching this CSS selector
accept: '#yes-drop',
// Require a 75% element overlap for a drop to be possible
overlap: '0.75'
};
}
I added a debugger statement in the InteractDraggableCustomAttribute.prototype.attached function within the aurelia-interactjs code and inspected this.options. It is undefined even though the options are clearly set with interact-draggable.bind.
Version 1.0.10 of aurelia-interactjs fixes this issue.

jQuery - Animation content inside a div when it becomes the current container on a horizontal slider

The Setup I have a full screen horizontal slider with 5+ divs that moves to the left when you click on an anchor link. I have some basic knowledge of jquery, and did attempted to use (scrollLeft). But the div is the wrapper div is hiding over flow and doesn't really go anywhere.
The goal is to animate the content inside the container div when it becomes the current container, and undo animation when it does to a different div.
The Issue: I got the animation to play, but have no control over when it starts.
The HTML
<div class="contentItem" id="content2">
<div id="top-box"></div>
<div id="bottom-box"></div>
</div>
<div class="contentItem" id="content3"></div>
<div class="contentItem" id="content4"></div>
<div class="contentItem" id="content5"></div>
The javascript
var theWidth;
var theHeight;
var currentContent = 0;
$(window).resize(function () {
sizeContent();
});
$(window).ready(function () {
sizeContent();
});
function sizeContent() {
theWidth = $(window).width();
theHeight = $(window).height();
sizeContentItems();
setLeftOnContentItems();
sizeContentWrapper(theWidth, theHeight);
moveContent(currentContent, theWidth);
changeSelected(currentContent);
}
function sizeContentItems() {
$(".contentItem").css('width', theWidth);
$(".contentItem").css('height', theHeight);
}
function setLeftOnContentItems() {
var contentCount = 0;
$(".contentItem").each(function (i) {
contentCount += i;
$(this).css('left', i * 990); //slider contern hight
});
}
function sizeContentWrapper(width, height) {
$("#contentWrapper").css('width', width);
$("#contentWrapper").css('height', height);
}
function moveContent(i, width) {
$("#contentWrapper").scrollLeft(i * width);
}
function changeSelected(i) {
$(".selected").removeClass("selected");
$("li:eq(" + i + ") a").addClass("selected");
}
function scrollContentNext() {
scrollContent(currentContent + 1);
}
function scrollContent(i) {
i = checkMax(i);
scrollLogo(i);
scrollTriangle(i);
changeSelected(i)
currentContent = i;
$("#contentWrapper").animate({ scrollLeft: i * 990 }, 400); // how far to go
}
function scrollLogo(i) {
var left = (i * +200);
$("#logo").animate({ left: left }, 1000);
}
function scrollTriangle(i) {
var left = (i * -300);
$("#triangle").animate({ left: left }, 700);
}
// **my edit**
function scrollbox(i) {
var i = currentContent;
if ( currentContent = 2) {
$("#bottom-box").stop().animate({'margin-top': '200px'}, 1500);
}
}
function checkMax(i) {
var maxItems = $("li").length;
if (i >= maxItems) {
return 0;
}
return i;
}

How to add a function to another jQuery function?

I'm trying to add this short function - which swaps images according to the active tab in jQuery UI Tabs - below to the larger function below, which is the jQuery Address plugin that adds forward/back and #URL functions to UI Tabs: http://www.asual.com/jquery/address/
I need to add the shorter function so it fires when the tab changes - so it changes the image in #headerwrapper - but I can't quite tell exactly where the tab change is fired in the main address function. Any ideas on how to add this shorter function to jQuery Address?
Image change function I need to add to the main function below to run when the tab change fires:
var img = $(ui.panel).data("image");
$("#headerwrapper")
.animate({ opacity: 'toggle' }, function() {
$(this).css("background-image", "url(" + img + ")")
.animate({ opacity: 'toggle' });
});
}
Main jQuery Tabs Address function:
<script type="text/javascript">
var tabs,
tabulation = false,
initialTab = 'home',
navSelector = '#tabs .ui-tabs-nav',
navFilter = function(el) {
return $(el).attr('href').replace(/^#/, '');
},
panelSelector = '#tabs .ui-tabs-panel',
panelFilter = function() {
$(panelSelector + ' a').filter(function() {
return $(navSelector + ' a[title=' + $(this).attr('title') + ']').size() != 0;
}).each(function(event) {
$(this).attr('href', '#' + $(this).attr('title').replace(/ /g, '_'));
});
};
if ($.address.value() == '') {
$.address.value(initialTab);
}
$.address.init(function(event) {
$(panelSelector).attr('id', initialTab);
$(panelSelector + ' a').address(function() {
return navFilter(this);
});
panelFilter();
tabs = $('#tabs')
.tabs({
load: function(event, ui) {
$(ui.panel).html($(panelSelector, ui.panel).html());
panelFilter();
},
fx: {
opacity: 'toggle',
duration: 'fast'}
})
.css('display', 'block');
$(navSelector + ' a').click(function(event) {
tabulation = true;
$.address.value(navFilter(event.target));
tabulation = false;
return false;
});
}).change(function(event) {
var current = $('a[href=#' + event.value + ']:first');
$.address.title($.address.title().split(' - ')[0] + ' - ' + current.text());
if (!tabulation) {
tabs.tabs('select', current.attr('href'));
}
}).history(true);
document.write('<style type="text/css"> #tabs { display: none; } </style>');
</script>