Vscode Ext display extension only when project have some file - javascript

I've created a vscode extension which handle some Rakefile tasks.
Now I want to limit that the extension will be displayed in the explorer only when user
open a Rakefile
for that I use the following entry in the package.json
"contributes": {
"views": {
"explorer": [
{
"id": "rakeView",
"name": "Rakee",
"when": "resourceFilename ='Rakefile'"
}
]
},
"commands": [
{
"command": "rakeView.executeTask",
"title": "Execute",
"icon": "images/icon.png"
}
],
when adding the following line
"when": "resourceFilename ='Rakefile'"
the extension removed from the explorer view, when I remove it I was able to see the extension.
I want it to display only when a project have a Rakefile how could I do it ?
https://github.com/microsoft/vscode-extension-samples/tree/1aae138e311fb87cc3ed2782be287f5d2f78e327/task-provider-sample
update
After trying the answer below it's still not working, this is the all code:
import * as vscode from "vscode";
import { rakeTaskProvider } from "./rakeCmd";
import { TaskTreeDataProvider } from "./rakeView";
let rakeTaskProvider: vscode.Disposable | undefined;
export function activate(_context: vscode.ExtensionContext): void {
const workspaceRoot = vscode.workspace.rootPath;
const onChangeActiveTextEditor = () => {
let editor = vscode.window.activeTextEditor;
vscode.commands.executeCommand('setContext', 'rakeView:fileIsRake', editor && editor.document.languageId === 'rakefile');
};
vscode.window.onDidChangeActiveTextEditor(onChangeActiveTextEditor, null, _context.subscriptions);
onChangeActiveTextEditor();
rakeTaskProvider = vscode.tasks.registerTaskProvider(
rakeTaskProvider.rakeType,
new rakeTaskProvider(workspaceRoot)
);
vscode.window.registerTreeDataProvider(
"rakeView",
new TaskTreeDataProvider(_context)
);
vscode.commands.registerCommand("rakeView.executeTask", function (task) {
console.log(task);
vscode.tasks.executeTask(task).then(
function (value) {
return value;
},
function (e) {
console.error(
"error",
e
);
}
);
});
}
export function deactivate(): void {
if (rakeTaskProvider) {
rakeTaskProvider.dispose();
}
}
package.json
"contributes": {
"views": {
"explorer": [
{
"id": "rakeView",
"name": "Rakke",
"when": "rakeView:fileIsRake"
}
]
},

You need to use the context, when the editor changes set a context variable to signal the current file is a Rakefile
In your activate function
const onChangeActiveTextEditor = () => {
let editor = vscode.window.activeTextEditor;
vscode.commands.executeCommand('setContext', 'myExtenstion:fileIsRake', editor && editor.document.languageId === 'rake');
};
vscode.window.onDidChangeActiveTextEditor(onChangeActiveTextEditor, null, context.subscriptions);
onChangeActiveTextEditor();
In package.json add this context variable
"views": {
"explorer": [
{
"id": "rakeView",
"name": "Rakee",
"when": "myExtenstion:fileIsRake"
}
]
},

Related

Set value of a js file properties from outside of it

I`m new to JS and apologize for asking a primary question!
We have this first.js file as a js class example with:
const {MakeRequest} = require("./Request");
let api;
let token;
let unique_token;
function chat(data, unique_token = null) {
try {
if (api != null && token != null) {
return MakeRequest(token, api, data, unique_token)
} else {
return {
"provider": {
"website": "https://example.com",
"source": "Example"
},
"status": true,
"response": [],
"options": {},
"error": {
"code": 207,
"message": "Token or Api token did not valueted!"
}
}
}
} catch (e) {
return {
"provider": {
"website": "https://example.com",
"source": "Example"
},
"status": true,
"response": [],
"options": {},
"error": {
"code": e.code,
"message": e.message
}
}
}
}
module.exports = {
token,api,unique_token,chat
}
also, I have this second.js file as a executable js file:
const object = require("./first.js")
object.token ="123456"
object.api ="123456"
object.token ="123456"
console.log(object.chat("hello"))
If I run the second.js file, the api variable is undefined and didn`t get the value from second.js, how can I resolve this problem without change the second.js codes!
You can't edit a variable from a scope outside where it was declared.
Consider passing the values as arguments to chat function when you call it.

Dialogflow fulfillment not responding to keywords

I am trying to make sense of how the fulfillment works, and I cannot get the responses from the if statements to work. Whenever I write the keyword, the default response I get is Not available.
The webhook for the intent is enabled, the entity is 'hooked' in the intent as well.
What am I missing here?
const functions = require('firebase-functions');
const { dialogflow } = require('actions-on-google');
const app = dialogflow();
const WELCOME_INTENT = 'Default Welcome Intent';
const USER_MESSAGE_ENTITY = 'UserMessage';
app.intent(WELCOME_INTENT, (conv) => {
const userMessage = conv.parameters(USER_MESSAGE_ENTITY).toLowerCase();
if (userMessage == 'hey') {
conv.ask('Hey there');
} else if (userMessage == 'greetings') {
conv.ask('Greetings, how are you');
} else if (userMessage == 'evening') {
conv.ask('Good evening');
}
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
{
"responseId": "8499a8f2-b570-4fb2-9f3c-262bd03db01e-c4f60134",
"queryResult": {
"queryText": "hey",
"action": "input.welcome",
"parameters": {
"UserMessage": "hey"
},
"allRequiredParamsPresent": true,
"intent": {
"name": "projects/wandlee-zad-rekrutacyjne--euol/agent/intents/d76ffc6c-c724-4fa4-8c9b-7178a2d7f9b7",
"displayName": "Default Welcome Intent"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 76
},
"languageCode": "pl",
"sentimentAnalysisResult": {
"queryTextSentiment": {
"score": 0.2,
"magnitude": 0.2
}
}
},
"webhookStatus": {
"code": 14,
"message": "Webhook call failed. Error: UNAVAILABLE."
}
}
I don't know where you got conv.parameters(USER_MESSAGE_ENTITY).
The parameters of the intent are accessible as a second function argument. It is going to be a map:
app.intent(WELCOME_INTENT, (conv, params) => {
const userMessage = params[USER_MESSAGE_ENTITY].toLowerCase();
// ...
})
``

Stop Gatsby blog post slug from including individual post folders

I have encountered a problem while making a personal Gatsby site whereby blog post files are having thier unique folders included in the slug.
For example a file structure of:
data
|
|– blog
|
|– blog-1
| |
| |-blog-1.mdx
| |-img.jpg
|
|– blog-2
| |
| |-blog-2.mdx
| |-img.jpg
|
|– blog-3
| |
| |-blog-3.mdx
| |-img.jpg
Will, for example, produce slugs like this
{
"data": {
"allMdx": {
"edges": [
{
"node": {
"fields": {
"slug": "/blog-1/blog-1/"
},
"frontmatter": {
"title": "Blog 1",
"posttype": "blog"
}
}
},
{
"node": {
"fields": {
"slug": "/blog-2/blog-2/"
},
"frontmatter": {
"title": "Blog 2",
"posttype": "blog"
}
}
},
{
"node": {
"fields": {
"slug": "/blog-3/blog-3/"
},
"frontmatter": {
"title": "Blog 3",
"posttype": "blog"
}
}
},
I expect them to produce a slug like this:
{
"node": {
"fields": {
"slug": "/blog-1/"
},
"frontmatter": {
"title": "Blog 1",
"posttype": "blog"
}
}
},
The path to the parent blog folder is included in my gatsby-config like this:
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/data/blog`,
name: `blog`,
},
},
And then my gatsby-node folder is set up like this:
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
const blogPost = path.resolve(`./src/templates/blog-post.js`)
const portfolioPost = path.resolve(`./src/templates/portfolio-post.js`)
const journeyPost = path.resolve(`./src/templates/journey-post.js`)
return graphql(
`
{
allMdx(
sort: { fields: [frontmatter___date], order: DESC }
limit: 1000
) {
edges {
node {
fields {
slug
}
frontmatter {
title
posttype
}
}
}
}
}
`
).then(result => {
if (result.errors) {
throw result.errors
}
const posts = result.data.allMdx.edges
posts.forEach((post, index) => {
const previous = index === posts.length - 1 ? null : posts[index + 1].node
const next = index === 0 ? null : posts[index - 1].node
if (post.node.frontmatter.posttype == "portfolio") {
createPage({
path: `/portfolio${post.node.fields.slug}`,
component: portfolioPost,
context: {
slug: post.node.fields.slug,
previous,
next,
},
})
} else if (post.node.frontmatter.posttype == "journey") {
createPage({
path: `/journey${post.node.fields.slug}`,
component: journeyPost,
context: {
slug: post.node.fields.slug,
previous,
next,
},
})
} else {
createPage({
path: `/blog${post.node.fields.slug}`,
component: blogPost,
context: {
slug: post.node.fields.slug,
previous,
next,
},
})
}
})
return null
})
}
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `Mdx`) {
const value = createFilePath({ node, getNode })
createNodeField({
name: `slug`,
node,
value,
})
}
}
Note that the journey and portfolio paths in this file are at this point in time doing exactly the same thing as the blog path. They are set up in exactly the same way and are just split out depending on posttype. Pages are created fine but they are all using the unwanted folder/file.mdx slug.
Fixed by looking at other blog examples.
Post filename needs to be index.md or index.mdx
I am sure there is a better way but I was able to solve it by making changes in gatsby-node.js to only take the substring after the last slash (/) in from the file path. If someone knows a better way I will be glad to know that.
Old:
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode })
createNodeField({
name: `slug`,
node,
value,
})
}
}
New:
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode, trailingSlash:false })
createNodeField({
name: `slug`,
node,
value: `${value.indexOf("/") > -1 ? value.substring(value.lastIndexOf("/")) : value}`,
})
}
}

Jest encountered an unexpected token: implementing try/catch

I'm getting the following error:
Jest encountered an unexpected token ....
} catch {
^
I'm assuming that I need babel to transform the files that i'm importing but I don't understand how jest/babel are wired up together. How do I get it to transform my imported file so I can have try/catch.
I have the following code:
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
package.json
{
"name": "tests",
"scripts": {
"test": "jest"
},
"author": "jonny-b",
"dependencies": {
"jest": "^24.8.0",
"ruby-script": "^1.0.3"
}
}
index.js
class Collection extends Array {
constructor(array) {
super(array.length);
Object.assign(this, array);
}
//....
drill(...indices) {
if (this[indices] === null) return null;
if (indices.length === 1) return this[indices];
let indexes = indices.splice(indices[0]);
try {
let collection = new Collection(this[indices[0]]);
return collection.drill(...indexes);
} catch {
throw `${typeof (this[indices[0]])}`
}
}
}
script.test.js
let Collection = require('<path to file>/index.js');
describe('ruby-script', () => {
it('should error if called on a non collection return value', () => {
let collection = new Collection([1, [2, [3, [4, [5, [6, [7]]]]]]]);
expect(collection.dig(1)).toEqual(true)
})
}

Is it possible to pass arguments to functions in a main.js file for an atom plugin?

I would like to have one method that I can call and pass in an argument based on the context menu item selected.
Can an argument be passed in from the cson file, or is it possible to just pass the value of the item clicked (like item.label or something similar)?
I have this in my lib\main.js file:
const MyAtomPlugin = {
subscriptions: null,
activate (state) {
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(
atom.commands.add('atom-text-editor', {
'menu-item-label:toggle': this.method1
})
);
},
method1() {
console.log(0);
}
where the menu-item-label is in the menu.cson file for my package. The goal is to be able to have:
const MyAtomPlugin = {
subscriptions: null,
activate (state) {
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(
atom.commands.add('atom-text-editor', {
'menu-item-label:toggle': this.method1
})
);
},
method1(variableName) {
console.log(variableName);
}
My menu file follows as:
{
"context-menu": {
"atom-text-editor": [
{
"label": "Button1",
"submenu": [
{
"label": "SubMenuLabel",
"command": "menu-item-label:toggle"
}
]
}
]
}
}
So I would like to select the SubMenuLabel button from the context menu, and pass its label as the argument: variableName

Categories