load style file using bundleName in angular - html

I have light and dark theme files and mentioned in angular.json file as below:
"styles": [
"src/styles.scss",
{
"input": "src/styles/themes/light.theme.scss",
"bundleName": "light-theme",
"inject": false
},
{
"input": "src/styles/themes/dark.theme.scss",
"bundleName": "dark-theme",
"inject": false
}
],
and I want to inject each of the file dynamically via this code
loadStyle(styleName: string = 'light-theme' | 'dark-theme') {
const head = this.document.getElementsByTagName('head')[0];
let themeLink = this.document.getElementById('client-theme') as HTMLLinkElement;
if (themeLink) {
themeLink.href = styleName;
} else {
const style = this.document.createElement('link');
style.id = 'client-theme';
style.rel = 'stylesheet';
style.href = `${styleName}`;
head.appendChild(style);
}
}
The above code creates link as
<link id="client-theme" rel="stylesheet" href="dark-theme"> // href="light-theme"
but nothing happens because the actual theme file is not being injected in the head-tag.
Update
Accoring to Angular Material docs
You can define multiple themes in separate files by creating multiple theme files per Defining a theme, adding each of the files to the styles of your angular.json. However, you must additionally set the inject option for each of these files to false in order to prevent all the theme files from being loaded at the same time. When setting this property to false, your application becomes responsible for manually loading the desired file. The approach for this loading depends on your application.
https://material.angular.io/guide/theming#multiple-themes-across-separate-files
but the process of loading styles files in not there in the docs :(
Any suggestion/solution would be highly appreciable!!! :)

I don't think you can directly use the bundleName as href. Maybe try something like this:
style.href = `styles/themes/${styleName}.css`;

Set a default theme using inject attribute:
{
"input": "src/styles/themes/light.theme.scss",
"bundleName": "light-theme",
"inject": true
},
or update your ngOnInit in AppComponent:
ngOnInit(): void {
this.loadStyle('light-theme');
}

Related

Gatsby mdx pages not rendering fully when placed in subfolder of src/pages

I have been converting a WordPress site to Gatsby, and everything works nicely with gatsby develop, however after building with gatsby build some pages seem to render with only the page body and no wrapper layout or styling. I am using markdown pages with mdx, and I have all my markdown files under subfolders of the src/pages directory, like this:
src/pages/
--project/
--contact.md
--outputs.md
--project.md
--sources.md
--software/
--apps.md
--frontend.md
--system.md
The above structure is more for organizational reasons than anything else (there are many more mdx files in reality). It does also correspond to the overall path structure of the site, however. In my built site, when I go to http://localhost:9000/contact the page renders perfectly, but when I visit http://localhost:9000/project or any other pages relating to that folder I only see the page body (the text content), with no layout component wrapper or styling. Everything under the software folder renders fine.
Each markdown file has a slug defined in the usual way in the frontmatter. The slug defined in src/project/project.md is just '/project'. The slug for src/project/contact.md is '/project/contact'.
Clearly the presence of src/pages/project/project.md is causing problems, but I can't figure out exactly why. I tried renaming that to src/pages/project/index.md, but that did nothing. Interestingly, when I look at public/project I see an index.html at the top level, with subfolders for each subpage, each containing its index.html. For public/software there is no index.html at the top level.
My gatsby-config.js (relevant parts):
{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/pages`,
},
},
{
resolve: `gatsby-plugin-mdx`,
options: {
extensions: [`.md`, `.mdx`, `.markdown`],
gatsbyRemarkPlugins: [
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 1024,
},
},
],
},
},
My template (under templates/page.js - I use some MUI components):
export default function SitePageTemplate({ data: { mdx } }) {
const { frontmatter, body } = mdx;
const { title } = frontmatter;
return (
<Layout>
<Seo title={title} />
<Container fixed>
<Stack direction="row" justifyContent="space-between">
<SideBar/>
<div style={ { padding: "0 0 0 3.5%", width: "75%" } }>
<MDXRenderer>{body}</MDXRenderer>
</div>
</Stack>
</Container>
</Layout>
);
}
export const pageQuery = graphql`
query ($id: String!) {
mdx(id: { eq: $id }) {
body
frontmatter {
date(formatString: "MMMM DD, YYYY")
slug
title
}
}
}`
My gatsby-node.js:
const path = require("path");
exports.createPages = async ({ graphql, actions, reporter }) => {
const { createPage } = actions
createPage({
path: "/using-dsg",
component: require.resolve("./src/templates/using-dsg.js"),
context: {},
defer: true,
})
const result = await graphql(`
query MARKDOWN {
allMdx {
edges {
node {
id
frontmatter {
date(formatString: "MMMM DD, YYYY")
slug
title
}
}
}
}
}
`);
if (result.errors) {
reporter.panicOnBuild("🚨 ERROR: Loading \"createPages\" query");
}
const md = result.data.allMdx.edges;
md.forEach(({ node }, index) => {
createPage({
// This component will wrap our MDX content
component: path.resolve("./src/templates/page.js"),
// Pass any value you want to access inside the template. They'll be available via `props`.
context: {
id: node.id
},
// Slug defined with frontmatter in each MDX file.
path: node.frontmatter.slug
});
});
}
If I place all the markdown files flat under the src/pages directory the problem goes away. But I would like to retain the above folder layout so that the markdown is organized properly. How can I do this whilst at the same time avoiding this problem?
OK, returning to this issue after a few months, I think I finally solved it. A warning I was also getting turned out to be the real clue - initially I had thought it unrelated to this issue. At develop and at build time I was getting a warning in the following format:
warn Non-deterministic routing danger: Attempting to create page: "/project/contact/", but page
"/project/contact" already exists
Others have reported this warning, but none of the reasons or propsed fixes seemed to relate to my problem. Looking at my gatsby-config.js, however, I noticed that I had at some time included the gatsby-plugin-page-creator plugin. I suspected that somehow this might be generating pages in addition to the mdx plugin. And it seemed as if this was right - removing the plugin removed both the warnings about duplicate page creation and also fixed my rendering problems. Everything looks fine now, for both development and production versions of my site.
I can't remember why I originally included this plugin - I was originally using the mdx extension for my markdown files, and I think I needed gatsby-plugin-page-creator so that files with that extension would be correctly interpreted as markdown. I now use the standard md extension, and removing gatsby-plugin-page-creator doesn't cause any problems.

NUXTJS | Error on loading css / layout the first call

I am playing as a newbie with Nuxtjs. I bought an html template to transform it as Nuxtjs project. The template, there are several css to display out a good layout.
There are issues on loading a page.vue as first call but if I reload it, the layout/css are displayed correctly.
My tries were:
- Adding css: [ ... ] at nuxt.config.js as global.
- Added css as script injected into the page.vue as follow:
export default {
head () {
return {
link: [
{ rel: 'stylesheet', type: 'text/css', href: './css/animate.css' },
{ rel: 'stylesheet', type: 'text/css', href: './css/et-line.css' },
],
}
}
}
I appreciate your clues & tricks.
Put your css files to assets or static folder. More info about the difference you could find in the doc: https://nuxtjs.org/guide/assets#static
Plug it in nuxt.config.js as so:
css: ["~assets/main.css"] or css: ["~/static/static.css"]
Rebuild the project

Modify MediaWiki Search Form

Is there a way to modify the MediaWiki search form in the page header other than by editing Vector.php?
Basically, I would like to change/extend the markup of the the HTML form and add a JavaScript listener for Ajax calls.
Unfortunately, I can't seem to be able to find an appropriate hook.
That's not easily possible, if you want to change the HTML. But to add a JavaScript listener you usually don't need to add something directly to the input where you want to listen for events.
You could, e.g., use jQuery to add a listener to the search input. For this you could create a new extension (read this manual for a quick start). In your extension, you create a new resource module:
{
"#comment": "Other configuration options may follow here"
"ResourceFileModulePaths": {
"localBasePath": "",
"remoteSkinPath": "ExampleExt"
},
"ResourceModules": {
"ext.ExampleExt.js": {
"scripts": [
"resources/ext.ExampleExt.js/script.js"
]
}
},
"#comment": "Other configuration options may follow here"
}
Now, you can add the script file, which you defined in the module:
( function ( $ ) {
$( '#searchInput' ).on( 'change', function () {
// do whatever you want when the input
// value changed
}
}( jQuery ) );
The code in the function (in the second parameter of the on() function) will run whenever the value of the search input changes.
Now, you only need to load your module when MediaWiki output's the page. The easiest way is to use the BeforePageDisplay hook:
Register the hook handler:
{
"#comment": "Other configuration options may follow here"
"Hooks": {
"BeforePageDisplay": [
"ExampleExtHooks::onBeforePageDisplay"
],
},
"#comment": "Other configuration options may follow here"
}
Handle the hook (in ExampleExtHooks class, which needs to be created and added to the Autoload classes):
public static function onBeforePageDisplay( OutputPage &$output, Skin &$skin ) {
$output->addModules( array(
'ext.ExampleExt.js',
) );
return true;
}
First, I added a hook:
$wgHooks['BeforePageDisplay'][] = 'MyNamespace\Hooks::onBeforePageDisplay';
The hook is pretty simple:
public static function onBeforePageDisplay( \OutputPage &$out, \Skin &$skin ) {
$skin->template = '\MyNamespace\Template';
}
Finally, the Template class overrides the renderNavigation() method, which renders the search form:
<?php
namespace XtxSearch;
class Template extends \VectorTemplate {
protected function renderNavigation( $elements ) {
...
}
}

Creating Chrome extensions to hide DIV display:none; on a specific page

I'm trying to create my first Chrome extension.
It's basically an adblocker for specific elements, in this case - the Facebook comments section.
It works with the all_urls but not with that specific domain.
Manifest file:
{
"name": "My extension",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [
{
"matches": ["http://visir.is/*"], //where your script should be injected
"css": ["style.css"] //the name of the file to be injected
}
]
}
style.css file:
.fbcomment {
display: none;
}
Any ideas how to correct "matches"?
I have tried *://visir.is/* as specified in https://developer.chrome.com/extensions/match_patterns but it only works with all_urls
Viktor,
You are on the wrong way. Your extension should work on Facebook site, and so the matches statement in the manifest must be exactly as the following:
"matches": ["https://www.facebook.com/*"]
Than you need to find all the comments in the timeline (most probably by css class), detect the presence of the target site address (//visir.is/) and then hide these comments.
Because the timeline dynamically load more posts you will also need to observe the new nodes and apply your function on them too (see the example from my Chrome extension below):
var obs = new MutationObserver(function (mutations, observer) {
for (var i = 0; i < mutations[0].addedNodes.length; i++) {
if (mutations[0].addedNodes[i].nodeType == 1) {
$(mutations[0].addedNodes[i]).find(".userContentWrapper").each(function () {
injectFBMButton($(this));
});
}
}
injectMainButton();
});
obs.observe(document.body, { childList: true, subtree: true, attributes: false, characterData: false });

Use local files with Browser extensions (kango framework)

I'm working on a "browser extension" using "Kango Framework" (http://kangoextensions.com/)
When i want to link a css file i have to use external source (href='http://mysite.com/folder/mysite.css), how should i change the href to make is source from the plugin folder ? (ex: href='mylocalpluginfolder/localfile.css')
i've tried 'localfile.css' and putting the file in the same folder as the JS file.
$("head").append("");
How should i change the json file to make it work ? Should i declare the files as "extended_scripts" or "content_scripts" ?
I've a hard time finding support for this framework, even though the admins are awesome !
Thanks for your help. (please do not suggest to use other solutions, because i won't be able to code plugins for IE and Kango is my only option for this). I didn't find any samples matching my need as the only example available on their site is linking to outside content (christmas tree).
If you want to add CSS in page from content script you should:
Get CSS file contents
Inject CSS code in page
function addStyle(cssCode, id) {
if (id && document.getElementById(id))
return;
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (id)
styleElement.id = id;
if (styleElement.styleSheet){
styleElement.styleSheet.cssText = cssCode;
}else{
styleElement.appendChild(document.createTextNode(cssCode));
}
var father = null;
var heads = document.getElementsByTagName("head");
if (heads.length>0){
father = heads[0];
}else{
if (typeof document.documentElement!='undefined'){
father = document.documentElement
}else{
var bodies = document.getElementsByTagName("body");
if (bodies.length>0){
father = bodies[0];
}
}
}
if (father!=null)
father.appendChild(styleElement);
}
var details = {
url: 'styles.css',
method: 'GET',
async: true,
contentType: 'text'
};
kango.xhr.send(details, function(data) {
var content = data.response;
kango.console.log(content);
addStyle(content);
});
I do it another way.
I have a JSON containing the styling for specified web sites, when i should change the css.
Using jQuery's CSS gives an advantage on applying CSS, as you may know css() applying in-line css and inline css have a priority over classes and IDs defined in default web pages files and in case of inline CSS it will override them. I find it fine for my needs, you should try.
Using jQuery:
// i keep info in window so making it globally accessible
function SetCSS(){
$.each(window.skinInfo.css, function(tagName, cssProps){
$(tagName).css(cssProps);
});
return;
}
// json format
{
"css":{
"body":{"backgroundColor":"#f0f0f0"},
"#main_feed .post":{"borderBottom":"1px solid #000000"}
}
}
As per kango framework structure, resources must be placed in common/res directory.
Create 'res' folder under src/common folder
Add your css file into it and then access that file using
kango.io.getResourceUrl("res/style.css");
You must add this file into head element of the DOM.
This is done by following way.
// Common function to load local css into head element.
function addToHead (element) {
'use strict';
var head = document.getElementsByTagName('head')[0];
if (head === undefined) {
head = document.createElement('head');
document.getElementsByTagName('html')[0].appendChild(head);
}
head.appendChild(element);
}
// Common function to create css link element dynamically.
function addCss(url) {
var css_tag = document.createElement('link');
css_tag.setAttribute('type', 'text/css');
css_tag.setAttribute('rel', 'stylesheet');
css_tag.setAttribute('href', url);
addToHead(css_tag);
}
And then you can call common function to add your local css file with kango api
// Add css.
addCss(kango.io.getResourceUrl('res/style.css'));