access to $route in vue3 / quasar2 - quasar-framework

I am using Quasar with API composition and I have an issue.
I just want to get parameters from the current route so within onMounted, I try to use this.$route.params, but I always get "this is undefined" in console.
// src/pages/Level.vue
import { ref, onMounted, computed } from "vue";
import { useStore } from 'vuex'
import { useQuasar } from 'quasar';
export default {
name: "LevelPage",
setup () {
const $q = useQuasar();
const $store = useStore();
const level = ref(null);
onMounted(()=> {
console.log(this.$route.params)
});
return {
level,
}
},
};
I get the same error every time I use this in the setup.
So there must be something I'm not getting. Can you please help me?

I think you are looking for https://v3.vuejs.org/guide/composition-api-provide-inject.html#mutating-reactive-properties In your Level.vue:
import { provide } from 'vue';
export default {
setup() {
provide('appName', 'vue3')
}
}
And then in any child component where you want to access this variable, inject it:
import { inject } from 'vue'
export default {
setup() {
const appName = inject('appName');
}
}
OR
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
onMounted(() => {
const id = route.params.id
})
}
}

Related

How do you import from an MJS file with multiple exports?

I'm using Ruby on Rails with Stimulus without Webpack and I'm trying to import Uppy in a Controller from "#uppy/core" which has this structure:
'use strict';
const Uppy = require('./Uppy');
const UIPlugin = require('./UIPlugin');
const BasePlugin = require('./BasePlugin');
const {
debugLogger
} = require('./loggers');
module.exports = Uppy;
module.exports.Uppy = Uppy;
module.exports.UIPlugin = UIPlugin;
module.exports.BasePlugin = BasePlugin;
module.exports.debugLogger = debugLogger;
I've tried with:
import { Uppy } from "#uppy/core";
import Uppy from "#uppy/core";
import * as Uppy from "#uppy/core";
And nothing works. There is also an mjs file available with this structure:
// Core
export { default as Core } from '#uppy/core'
// Utilities
export { default as server } from '#uppy/companion-client'
/* eslint-disable */
import ProviderView from '#uppy/provider-views'
export var views = { ProviderView }
/* eslint-enable */
// Stores
export { default as DefaultStore } from '#uppy/store-default'
export { default as ReduxStore } from '#uppy/store-redux'
// UI plugins
export { default as Dashboard } from '#uppy/dashboard'
export { default as DragDrop } from '#uppy/drag-drop'
export { default as DropTarget } from '#uppy/drop-target'
export { default as FileInput } from '#uppy/file-input'
export { default as Informer } from '#uppy/informer'
export { default as ProgressBar } from '#uppy/progress-bar'
export { default as StatusBar } from '#uppy/status-bar'
export { default as ImageEditor } from '#uppy/image-editor'
// Acquirers
export { default as Dropbox } from '#uppy/dropbox'
export { default as GoogleDrive } from '#uppy/google-drive'
export { default as Instagram } from '#uppy/instagram'
export { default as OneDrive } from '#uppy/onedrive'
export { default as Box } from '#uppy/box'
export { default as Facebook } from '#uppy/facebook'
export { default as Unsplash } from '#uppy/unsplash'
export { default as Url } from '#uppy/url'
export { default as Webcam } from '#uppy/webcam'
export { default as ScreenCapture } from '#uppy/screen-capture'
export { default as Audio } from '#uppy/audio'
// Uploaders
export { default as AwsS3 } from '#uppy/aws-s3'
export { default as AwsS3Multipart } from '#uppy/aws-s3-multipart'
export { default as Transloadit } from '#uppy/transloadit'
export { default as Tus } from '#uppy/tus'
export { default as XHRUpload } from '#uppy/xhr-upload'
// Miscellaneous
export { default as Form } from '#uppy/form'
export { default as GoldenRetriever } from '#uppy/golden-retriever'
export { default as ReduxDevTools } from '#uppy/redux-dev-tools'
export { default as ThumbnailGenerator } from '#uppy/thumbnail-generator'
I have also tried to import Core from here in order to achieve the same thing. But I can't get the import to work. Any ideas?
Can you run ./bin/importmap json?
If Uppy is not there, it means that it's not installed.
Run
./bin/importmap pin uppy --from jsdelivr
Pinning "#uppy/core" to https://cdn.jsdelivr.net/npm/#uppy/core#2.1.8/lib/index.js
Pinning "#uppy/dashboard" to https://cdn.jsdelivr.net/npm/#uppy/dashboard#2.1.4/lib/index.js
Pinning "#uppy/tus" to https://cdn.jsdelivr.net/npm/#uppy/tus#2.2.2/lib/index.js
...
Now you run again ./bin/importmap json and see that Uppy is installed
./bin/importmap json
{
"imports": {
...
"#uppy/core": "https://cdn.jsdelivr.net/npm/#uppy/core#2.1.8/lib/index.js",
"#uppy/dashboard": "https://cdn.jsdelivr.net/npm/#uppy/dashboard#2.1.4/lib/index.js",
"#uppy/tus": "https://cdn.jsdelivr.net/npm/#uppy/tus#2.2.2/lib/index.js"
}
}

How reset persistent react-redux store for testing on iOS device?

Background: I've tried reading up on this issue, but can't come up with an explanation of what actually happens on iOS devices w.r.t. a react-redux and redux-persist store setup.
References:
How to reset the state of a Redux store?
https://blog.bam.tech/developer-news/redux-persist-how-it-works-and-how-to-change-the-structure-of-your-persisted-store
https://discussions.apple.com/thread/250190465
Problem:
Our QA team was unable to test out the onboarding experience.
Onboarding experience: 3 intro screens (controlled by isNew flag -> login -> onboarding tutorial (triggered by is_first_time_login: true, hasLoggedIn || hasPinCodeLoggedIn: true, and hasFinishedOnboardTutorial:false
We've tried on both Android and iOS devices, Android works as intended, but for iOS, it doesn't.
So for iOS devices, we've deleted the app, restarted the phone, then installed the test app. The test app is distributed via firebase distribution.
The problem persists, and I'm at a loss on what to do now.
Code setup:
store/index.js
import { applyMiddleware, compose, createStore } from 'redux';
import { persistReducer, persistStore, createTransform } from 'redux-persist';
import createSagaMiddleware from 'redux-saga';
import logger from 'redux-logger';
import createSensitiveStorage from 'redux-persist-sensitive-storage';
import { NODE_ENV } from '#env';
import isEmpty from 'lodash/isEmpty';
import RootSaga from 'Sagas';
import RootReducer from 'Reducers';
import { UserDetail } from 'Models';
import ApiUtils from 'Services';
import { Configs, reactotron } from 'Configs';
const secureStorage = createSensitiveStorage({
keychainService: 'xxxx',
sharedPreferencesName: 'xxx'
});
const PersistStateTransformer = createTransform(
(inboundState) => {
return { ...inboundState };
},
(outboundState) => {
if (!isEmpty(outboundState?.token)) {
ApiUtils.injectToken(outboundState?.token);
}
return { ...outboundState, userDetails: new UserDetail(outboundState.userDetails), backgroundTimestamp: 0, hasPinCodeLoggedIn: false };
},
{
whitelist: ['auth'],
}
);
const persistConfig = {
key: 'root',
storage: secureStorage,
transforms: [PersistStateTransformer],
whitelist: ['auth', 'ui'],
};
// Use to remove all the existing state including auth/ui
// if (NODE_ENV === 'development') {
// AsyncStorage.removeItem('persist:root');
// }
export const buildStore = (initialState = {}) => {
const middlewares = [];
const enhancers = [];
// Connect the sagas to the redux store
const sagaMiddleware = createSagaMiddleware();
middlewares.push(sagaMiddleware);
if (NODE_ENV === 'development') {
middlewares.push(logger);
}
// do not remove spread operator
enhancers.push(applyMiddleware(...middlewares));
// Redux persist
const persistedReducer = persistReducer(persistConfig, RootReducer);
// Reactotron is only needed during dev, in test env it's not necessary
const store =
NODE_ENV === 'development'
? createStore(persistedReducer, initialState, compose(...enhancers, reactotron.createEnhancer()))
: createStore(persistedReducer, initialState, compose(...enhancers));
const persistor = persistStore(store);
// Kick off the root saga
sagaMiddleware.run(RootSaga);
return { store, persistor };
};
App.js
import React, { useEffect } from 'react';
import { Platform, UIManager } from 'react-native';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import SplashScreen from 'react-native-splash-screen';
import Navigation from 'Navigations';
import { buildStore } from 'Stores';
import { Loading } from 'Screens';
import { Toast } from 'Components';
import GlobalUiProvider from 'Contexts';
import ApiUtils from 'Services';
const { store, persistor } = buildStore();
ApiUtils.injectStore(store);
const App = () => {
if (Platform.OS === 'android') {
UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);
}
useEffect(() => {
SplashScreen.hide();
}, []);
return (
<SafeAreaProvider>
<Provider store={store}>
<PersistGate loading={<Loading />} persistor={persistor}>
<GlobalUiProvider>
<Navigation />
</GlobalUiProvider>
<Toast />
</PersistGate>
</Provider>
</SafeAreaProvider>
);
};
export default App;
export { store, persistor };
publicNavigation.js (snippet)
<PublicStack.Navigator screenOptions={Configs.PUBLIC_SCREEN_OPTIONS}>
{isNew ? (
<PublicStack.Screen name="Onboard" component={Onboard} />
) : (
<PublicStack.Screen name="Login" component={Login} />
)}
</PublicStack.Navigator>
);
Let me know if I need to add more details.

frida - defpackage class not list in android

I found some classes in defpackage directory but it not list out with below code:
log("load script")
Java.perform(function() {
log("load java")
var clzlst = []
Java.enumerateLoadedClasses({
onMatch: function(clzname) {
clzlst.push(clzname)
},
onComplete: function(e) {
console.log("<<<<onComplete");
}
});
log(clzlst.length)
clzlst.forEach(function (clzname) {
if (clzname.includes("abcd")) {
log("found clz:" + clzname) // this line not been hitted.
}
});
var hook = Java.use("abcd");
var methods = hook.class.getDeclaredMethods();
hook.$dispose();
methods.forEach(function (method) {
var name = method.toString();
log(name) // this line hitted
});
});
function log(msg) {
console.log(msg)
}
The loaded list classes not include target class (e.g. abcd), but if I call Java.use("abcd"), I can access that class successfully.
I guess that class maybe still not being loaded! how can I list all classes even if it's not been loaded?

Is there a way to get Golden Layout pop-outs working in conjunction with Electron windows?

I'm working on a JHipster application that I'm trying to get functioning in Electron. I have Golden Layout for window/pane management and cross-pane communication. I am having several problems with the combination of technologies, including:
I can't pop out more than one pane at the same time into their own Electron windows. I instead get an Uncaught Error: Can't create config, layout not yet initialised error in the console.
Two thirds of the panes don't display anything when popped out into Electron windows, and I'm not sure what the reason is. Any ideas or suggestions for this? One example of content is a leaflet map, another is a "PowerPoint preview" that is really just divs that mock the appearance of slides.
I haven't made it this far yet, but I assume that I will have trouble communicating between popped-out Electron windows when I get more than one open. Right now, the panes communicate between each other using Golden Layout's glEventHub emissions. I have an avenue to explore when I cross that bridge, namely Electron ipcRenderer.
Some borrowed code is here (most of it I can't share because it's company confidential):
electron.js:
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const isDev = require('electron-is-dev');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({width: 900, height: 680});
mainWindow.loadURL(isDev ? 'http://localhost:9000' : `file://${path.join(__dirname, '../build/index.html')}`);
if (isDev) {
// Open the DevTools.
//BrowserWindow.addDevToolsExtension('<location to your react chrome extension>');
mainWindow.webContents.openDevTools();
}
mainWindow.on('closed', () => mainWindow = null);
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
goldenLayoutComponent.tsx, a patch for Golden Layout:
import React from "react";
import ReactDOM from "react-dom";
// import "./goldenLayout-dependencies";
import GoldenLayout from "golden-layout";
import "golden-layout/src/css/goldenlayout-base.css";
import "golden-layout/src/css/goldenlayout-dark-theme.css";
import $ from "jquery";
interface IGoldenLayoutProps {
htmlAttrs: {},
config: any,
registerComponents: Function
}
interface IGoldenLayoutState {
renderPanels: Set<any>
}
interface IContainerRef {
current: any
}
export class GoldenLayoutComponent extends React.Component <IGoldenLayoutProps, IGoldenLayoutState> {
goldenLayoutInstance = undefined;
state = {
renderPanels: new Set<any>()
};
containerRef: IContainerRef = React.createRef();
render() {
const panels = Array.from(this.state.renderPanels || []);
return (
<div ref={this.containerRef as any} {...this.props.htmlAttrs}>
{panels.map((panel, index) => {
return ReactDOM.createPortal(
panel._getReactComponent(),
panel._container.getElement()[0]
);
})}
</div>
);
}
componentRender(reactComponentHandler) {
this.setState(state => {
const newRenderPanels = new Set(state.renderPanels);
newRenderPanels.add(reactComponentHandler);
return { renderPanels: newRenderPanels };
});
}
componentDestroy(reactComponentHandler) {
this.setState(state => {
const newRenderPanels = new Set(state.renderPanels);
newRenderPanels.delete(reactComponentHandler);
return { renderPanels: newRenderPanels };
});
}
componentDidMount() {
this.goldenLayoutInstance = new GoldenLayout(
this.props.config || {},
this.containerRef.current
);
if (this.props.registerComponents instanceof Function)
this.props.registerComponents(this.goldenLayoutInstance);
this.goldenLayoutInstance.reactContainer = this;
this.goldenLayoutInstance.init();
}
}
// Patching internal GoldenLayout.__lm.utils.ReactComponentHandler:
const ReactComponentHandler = GoldenLayout["__lm"].utils.ReactComponentHandler;
class ReactComponentHandlerPatched extends ReactComponentHandler {
_container: any;
_reactClass: any;
_render() {
const reactContainer = this._container.layoutManager.reactContainer; // Instance of GoldenLayoutComponent class
if (reactContainer && reactContainer.componentRender)
reactContainer.componentRender(this);
}
_destroy() {
// ReactDOM.unmountComponentAtNode( this._container.getElement()[ 0 ] );
this._container.off("open", this._render, this);
this._container.off("destroy", this._destroy, this);
}
_getReactComponent() {
// the following method is absolute copy of the original, provided to prevent depenency on window.React
const defaultProps = {
glEventHub: this._container.layoutManager.eventHub,
glContainer: this._container
};
const props = $.extend(defaultProps, this._container._config.props);
return React.createElement(this._reactClass, props);
}
}
GoldenLayout["__lm"].utils.ReactComponentHandler = ReactComponentHandlerPatched;
Any help or insight into these issues would be appreciated. Thanks in advance!
If you are still looking for a solutions, 1 and 2 I have solved, if you want to see my solution you could see in this repository.
But it was basically this:
1: The window that popups has a different path than the main window, so I just had to put a try catch in my requires, and you have to set
nativeWindowOpen = true
when creating the Browser window.
2: Solves it's self after 1 I think

Tests in angular dart, scope is empty

I'm trying test custom angular components. I want check the components class state. For this a have two options:
Get the component in the scope
Use web components xtag
The problems:
My scope is always empty - I debug in the console I'm using karma to run the tests in the browser.
xtag returns an HtmlElement class so I can't access my properties(cast in dart?)
The codes:
library vader.panel_spec;
import '../_specs.dart';
import "package:vader/components/vader_component.dart";
main(){
describe('Tests for Panel UI',(){
TestBed _;
Scope _scope;
Element ngAppElement;
beforeEach(async(inject((TestBed tb, Scope scope, VmTurnZone zone, TemplateCache cache) {
_ = tb;
_scope = scope;
addToTemplateCache(cache, 'packages/vader/components/panel.html');
addToTemplateCache(cache, 'packages/vader/components/window/window.html');
})));
beforeEachModule((Module module) {
ngAppElement = new DivElement()..attributes['ng-app'] = '';
module
..install(new VaderComponentModule());
module..bind(Node, toValue: ngAppElement);
document.body.append(ngAppElement);
});
afterEach(() {
ngAppElement.remove();
ngAppElement = null;
});
compile(html) {
ngAppElement.setInnerHtml(html, treeSanitizer: new NullTreeSanitizer());
_.compile(ngAppElement);
return ngAppElement.firstChild;
}
it("should collapse when clicked", async((){
Element panel = compile("<v-panel>CollapsedItem</v-panel>");
microLeap();
_.rootScope.apply();
Element contentPanel = panel.querySelector('.content-panel');
expect(contentPanel.classes.contains('collapse'), isFalse);
_.triggerEvent(panel.querySelector('#collapse-icon'), 'click');
_.rootScope.apply();
window.console.debug(_.rootScope.context);
var comp = panel.xtag;
expect(comp.doCollapse, isTrue);
}));
});
}
library ng_specs;
import 'dart:html' hide Animation;
import 'package:angular/angular.dart';
import 'package:angular/mock/module.dart';
import 'package:guinness/guinness_html.dart' as gns;
export 'dart:html' hide Animation;
export 'package:unittest/unittest.dart' hide expect;
export 'package:guinness/guinness_html.dart';
export 'package:mock/mock.dart';
export 'package:di/di.dart';
export 'package:di/dynamic_injector.dart';
export 'package:angular/angular.dart';
export 'package:angular/application.dart';
export 'package:angular/introspection.dart';
export 'package:angular/core/annotation.dart';
export 'package:angular/core/registry.dart';
export 'package:angular/core/module_internal.dart';
export 'package:angular/core_dom/module_internal.dart';
export 'package:angular/core/parser/parser.dart';
export 'package:angular/core/parser/lexer.dart';
export 'package:angular/directive/module.dart';
export 'package:angular/formatter/module.dart';
export 'package:angular/routing/module.dart';
export 'package:angular/animate/module.dart';
export 'package:angular/mock/module.dart';
export 'package:perf_api/perf_api.dart';
es(String html) {
var div = new DivElement();
div.setInnerHtml(html, treeSanitizer: new NullTreeSanitizer());
return new List.from(div.nodes);
}
e(String html) => es(html).first;
Expect expect(actual, [matcher]) {
final expect = new Expect(actual);
if (matcher != null) {
expect.to(matcher);
}
return expect;
}
class Expect extends gns.Expect {
Expect(actual) : super(actual);
NotExpect get not => new NotExpect(actual);
toBeValid() => _expect(actual.valid && !actual.invalid, true,
reason: 'Form is not valid');
toBePristine() => _expect(actual.pristine && !actual.dirty, true,
reason: 'Form is dirty');
get _expect => gns.guinness.matchers.expect;
}
class NotExpect extends gns.NotExpect {
NotExpect(actual) : super(actual);
toBeValid() => _expect(actual.valid && !actual.invalid, false,
reason: 'Form is valid');
toBePristine() => _expect(actual.pristine && !actual.dirty, false,
reason: 'Form is pristine');
get _expect => gns.guinness.matchers.expect;
}
_injectify(fn) {
// The function does two things:
// First: if the it() passed a function, we wrap it in
// the "sync" FunctionComposition.
// Second: when we are calling the FunctionComposition,
// we inject "inject" into the middle of the
// composition.
if (fn is! FunctionComposition) fn = sync(fn);
return fn.outer(inject(fn.inner));
}
// Replace guinness syntax elements to inject dependencies.
beforeEachModule(fn) => gns.beforeEach(module(fn), priority:1);
beforeEach(fn) => gns.beforeEach(_injectify(fn));
afterEach(fn) => gns.afterEach(_injectify(fn));
it(name, fn) => gns.it(name, _injectify(fn));
iit(name, fn) => gns.iit(name, _injectify(fn));
_removeNgBinding(node) {
if (node is Element) {
node = node.clone(true) as Element;
node.classes.remove('ng-binding');
node.querySelectorAll(".ng-binding").forEach((Element e) {
e.classes.remove('ng-binding');
});
return node;
}
return node;
}
/**
* It adds an html template into the TemplateCache.
*/
void addToTemplateCache(TemplateCache cache, String path) {
HttpRequest request = new HttpRequest();
request.open("GET", path, async : false);
request.send();
cache.put(path, new HttpResponse(200, request.responseText));
}
main() {
gns.beforeEach(setUpInjector, priority:3);
gns.afterEach(tearDownInjector);
gns.guinnessEnableHtmlMatchers();
gns.guinness.matchers.config.preprocessHtml = _removeNgBinding;
}
Use ngInjector(panel).get(PanelComponent) or ngDirectives(panel)[0]. See the documentation here.

Resources