New sample - CSS in JS with TypeStyle.

This commit is contained in:
Sergei Sergeev 2020-04-24 00:07:25 +03:00
parent 426b91707d
commit 26a208a1ab
28 changed files with 17792 additions and 0 deletions

View File

@ -0,0 +1,25 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# change these settings to your own preference
indent_style = space
indent_size = 2
# we recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[{package,bower}.json]
indent_style = space
indent_size = 2

View File

@ -0,0 +1,32 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
solution
temp
*.sppkg
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,12 @@
{
"@microsoft/generator-sharepoint": {
"isCreatingSolution": false,
"environment": "spo",
"version": "1.10.0",
"libraryName": "spfx-css-in-js",
"libraryId": "d07a3ba7-a2e7-41df-b2e6-acaf2ed00a33",
"packageManager": "npm",
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,57 @@
# "CSS in JS" with SharePoint Framework and TypeStyle
## Summary
The web part demonstrates the usage of "CSS in JS" pattern with SharePoint Framework. "CSS in JS" is implemented using [TypeStyle](https://typestyle.github.io/) library. Read more in [the blog post here](https://spblog.net/post/2020/04/22/styling-sharepoint-framework-components-with-css-in-js-approach).
![picture of the web part in action](assets/dynamic-styles.gif)
## Used SharePoint Framework Version
![1.10.0](https://img.shields.io/badge/version-1.10.0-green.svg)
## Applies to
* [SharePoint Framework](https:/dev.office.com/sharepoint)
* [Office 365 tenant](https://dev.office.com/sharepoint/docs/spfx/set-up-your-development-environment)
## Solution
Solution|Author(s)
--------|---------
react-css-in-js-typestyle|[@Sergei Sergeev](https://twitter.com/sergeev_srg) - [Mastaq](https://mastaq.com/)
## Version history
Version|Date|Comments
-------|----|--------
1.0|April 24, 2020|Initial release
## Disclaimer
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
---
## Minimal Path to Awesome
* Clone this repository
* in the command line run:
* `npm install`
* `gulp build`
* `gulp bundle --ship`
* `gulp package-solution --ship`
* add the webpart to your tenant app store
* add the app to a SharePoint site and then add the webpart to the page
## Features
This Web Part illustrates the following concepts on top of the SharePoint Framework:
* "CSS in JS" pattern adopted to SharePoint Framework
* Theme support using SharePoint Framework's `ThemeProvider`
* Dynamically reacting to theme changes without affecting performance
* React hooks
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-css-in-js-typestyle" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

View File

@ -0,0 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"dynamic-type-style-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/dynamicTypeStyle/DynamicTypeStyleWebPart.js",
"manifest": "./src/webparts/dynamicTypeStyle/DynamicTypeStyleWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"DynamicTypeStyleWebPartStrings": "lib/webparts/dynamicTypeStyle/loc/{locale}.js"
}
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/copy-assets.schema.json",
"deployCdnPath": "temp/deploy"
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./temp/deploy/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "spfx-css-in-js",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,13 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "spfx-css-in-js-client-side-solution",
"id": "d07a3ba7-a2e7-41df-b2e6-acaf2ed00a33",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"isDomainIsolated": false
},
"paths": {
"zippedPackage": "solution/spfx-css-in-js.sppkg"
}
}

View File

@ -0,0 +1,10 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://localhost:5432/workbench",
"api": {
"port": 5432,
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
}
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,7 @@
'use strict';
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
build.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,43 @@
{
"name": "spfx-css-in-js",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.10.0",
"@microsoft/sp-lodash-subset": "1.10.0",
"@microsoft/sp-office-ui-fabric-core": "1.10.0",
"@microsoft/sp-property-pane": "1.10.0",
"@microsoft/sp-webpart-base": "1.10.0",
"@types/es6-promise": "0.0.33",
"@types/react": "16.8.8",
"@types/react-dom": "16.8.3",
"@types/webpack-env": "1.13.1",
"office-ui-fabric-react": "6.189.2",
"react": "16.8.5",
"react-dom": "16.8.5",
"typestyle": "^2.0.4"
},
"resolutions": {
"@types/react": "16.8.8"
},
"devDependencies": {
"@microsoft/sp-build-web": "1.10.0",
"@microsoft/sp-tslint-rules": "1.10.0",
"@microsoft/sp-module-interfaces": "1.10.0",
"@microsoft/sp-webpart-workbench": "1.10.0",
"@microsoft/rush-stack-compiler-3.3": "0.3.5",
"gulp": "~3.9.1",
"@types/chai": "3.4.34",
"@types/mocha": "2.2.38",
"ajv": "~5.2.2"
}
}

View File

@ -0,0 +1,6 @@
import { createContext } from 'react';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
const AppContext = createContext<{ theme: IReadonlyTheme }>(undefined);
export default AppContext;

View File

@ -0,0 +1,12 @@
import { IReadonlyTheme } from "@microsoft/sp-component-base";
import { useEffect, useState } from "react";
export const useThemedStyles = <T>(theme: IReadonlyTheme, createStyles: (theme: IReadonlyTheme) => T) => {
const [styles, setStyles] = useState<T>(createStyles.bind(null, theme));
useEffect(() => {
setStyles(createStyles(theme));
}, [theme]);
return styles;
};

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,28 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "0055998e-a48a-4453-bc2e-ecedebed480d",
"alias": "DynamicTypeStyleWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "DynamicTypeStyle" },
"description": { "default": "DynamicTypeStyle description" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "DynamicTypeStyle"
}
}]
}

View File

@ -0,0 +1,80 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { ThemeProvider, IReadonlyTheme, ThemeChangedEventArgs } from '@microsoft/sp-component-base';
import * as strings from 'DynamicTypeStyleWebPartStrings';
import { StylesDemo } from './components/StylesDemo';
import AppContext from '../../common/AppContext';
export interface IDynamicTypeStyleWebPartProps {
description: string;
}
export default class DynamicTypeStyleWebPart extends BaseClientSideWebPart<IDynamicTypeStyleWebPartProps> {
private themeProvider: ThemeProvider;
private theme: IReadonlyTheme;
protected onInit(): Promise<void> {
this.themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey);
this.theme = this.themeProvider.tryGetTheme();
this.themeProvider.themeChangedEvent.add(this, this.onThemeChanged);
return super.onInit();
}
public render(): void {
const element: React.ReactElement = React.createElement(
AppContext.Provider,
{
value: {
theme: { ...this.theme }
}
},
React.createElement(StylesDemo)
);
ReactDom.render(element, this.domElement);
}
private onThemeChanged(args: ThemeChangedEventArgs) {
this.theme = args.theme;
this.render();
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,8 @@
import * as React from 'react';
import { TypeStyleButton } from './TypeStyleButton/TypeStyleButton';
export const StylesDemo: React.FC = () => (
<div>
<div><TypeStyleButton /></div>
</div>
);

View File

@ -0,0 +1,29 @@
import { stylesheet } from "typestyle";
import { IReadonlyTheme } from "@microsoft/sp-component-base";
export const createStyles = (theme: IReadonlyTheme) => {
return stylesheet({
root: {
margin: "10px",
},
myButton: {
backgroundColor: theme.palette.themePrimary,
color: theme.palette.white,
height: "60px",
lineHeight: "60px",
textAlign: "center",
fontSize: "16px",
padding: "0 15px",
cursor: "pointer",
borderWidth: "0 0 6px 0",
fontWeight: "bold",
borderColor: "#4e84c3",
borderStyle: "solid",
$nest: {
"&:hover": {
backgroundColor: "#328bf9",
}
}
}
});
};

View File

@ -0,0 +1,22 @@
import * as React from 'react';
import { createStyles } from "./TypeStyleButton.styles";
import { useThemedStyles } from '../../../../hooks/useThemedStyles';
import AppContext from '../../../../common/AppContext';
export const TypeStyleButton: React.FC = () => {
const { theme } = React.useContext(AppContext);
const styles = useThemedStyles(theme, createStyles);
const [enabled, setEnabled] = React.useState(true);
const toggleEnable = () => {
setEnabled(!enabled);
};
return (
<div className={styles.root}>
<button onClick={toggleEnable} className={styles.myButton}>Hello from a TypeStyle button! The state is {enabled ? "enabled" : "disabled"}</button>
</div>
);
};

View File

@ -0,0 +1,7 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field"
}
});

View File

@ -0,0 +1,10 @@
declare interface IDynamicTypeStyleWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'DynamicTypeStyleWebPartStrings' {
const strings: IDynamicTypeStyleWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1,38 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.3/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
]
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"lib"
]
}

View File

@ -0,0 +1,30 @@
{
"extends": "@microsoft/sp-tslint-rules/base-tslint.json",
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": true,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
}