new sample reacxt-restaurant-menu

This commit is contained in:
João Mendes 2020-09-06 21:31:15 +01:00
parent 7e8964db17
commit 2b6ecdfca5
47 changed files with 22524 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,34 @@
{
"@pnp/generator-spfx": {
"framework": "react",
"pnpFramework": "reactjs.plus",
"pnp-libraries": [
"jquery@3",
"msgraph",
"@pnp/pnpjs",
"@pnp/spfx-property-controls",
"spfx-uifabric-themes",
"lodash",
"@pnp/spfx-controls-react",
"ouifr@7",
"rush@3.7"
],
"pnp-ci": "azure-preview",
"pnp-vetting": [],
"spfxenv": "spo",
"pnp-testing": [
"jest"
]
},
"@microsoft/generator-sharepoint": {
"environment": "spo",
"framework": "react",
"isCreatingSolution": true,
"version": "1.11.0",
"libraryName": "react-menu",
"libraryId": "e1632e6a-caf2-4dba-9d88-32783876aa2b",
"packageManager": "npm",
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,80 @@
---
page_type: sample
products:
- office-sp
languages:
- javascript
- typescript
extensions:
contentType: samples
technologies:
- SharePoint Framework
- PnPjs
- Fluent UI React Controls
platforms:
- React
createdDate: 4/9/2020 12:00:00 AM
---
# React Restaurant Menu
## Summary
This web part shows a Restaurant Menu , the user can select the options to show in Menu.
  
![MySites](./assets/restaurantmenu.gif)
![MySites](./assets/restaurantmenu.png)
![MySites](./assets/restaurantmenu2.png)
![MySites](./assets/restaurantmenu3.png)
## Used SharePoint Framework Version
![1.11.0](https://img.shields.io/badge/version-1.11.0-green.svg)
## Applies to
* [SharePoint Framework](https://docs.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
* [Office 365 tenant](https://docs.microsoft.com/sharepoint/dev/spfx/set-up-your-development-environment)
## Solution
Solution|Author(s)
--------|---------
react-restaurant-menu|João Mendes
## Version history
Version|Date|Comments
-------|----|--------
1.0.0|Setember 5, 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
Please follow all the steps:
- Clone this repository
- in the command line run:
- `npm install`
- `gulp build`
- `gulp bundle --ship`
- `gulp package-solution --ship`
- Add and deploy package to your tenant's App Catalog
- Go to **API Access** - from **SharePoint Admin Center** new experience, and **Approve** the permission to use Microsoft Graph scope **Group.Read.All** and **Directory.Read.All**
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-my-sites" />

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

View File

@ -0,0 +1,67 @@
parameters:
name: ''
jobs:
- job: ${{ parameters.name }}
pool:
vmImage: 'ubuntu-latest'
demands:
- npm
- node.js
- java
variables:
npm_config_cache: $(Pipeline.Workspace)/.npm
steps:
- checkout: self
- task: NodeTool@0
displayName: 'Use Node 10.x'
inputs:
versionSpec: 10.x
checkLatest: true
- task: CacheBeta@1
inputs:
key: npm | $(Agent.OS) | package-lock.json
path: $(npm_config_cache)
cacheHitVar: CACHE_RESTORED
- script: npm ci
displayName: 'npm ci'
- task: Gulp@0
displayName: 'Bundle project'
inputs:
targets: bundle
arguments: '--ship'
- script: npm test
displayName: 'npm test'
- task: PublishTestResults@2
displayName: Publish test results
inputs:
testResultsFormat: JUnit
testResultsFiles: '**/junit.xml'
#failTaskOnFailedTests: true #if we want to fail the build on failed unit tests
- task: PublishCodeCoverageResults@1
displayName: 'Publish code coverage results'
inputs:
codeCoverageTool: Cobertura
summaryFileLocation: '$(System.DefaultWorkingDirectory)/**/*coverage.xml'
- task: Gulp@0
displayName: 'Package Solution'
inputs:
targets: 'package-solution'
arguments: '--ship'
- task: CopyFiles@2
displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)'
inputs:
Contents: |
sharepoint/**/*.sppkg
TargetFolder: '$(Build.ArtifactStagingDirectory)'
- task: PublishBuildArtifacts@1
displayName: 'Publish Artifact: drop'

View File

@ -0,0 +1,39 @@
parameters:
# unique name of the job
job_name: deploy_sppkg
# friendly name of the job
display_name: Upload & deploy *.sppkg to SharePoint app catalog
# name of target enviroment deploying to
target_environment: ''
# app catalog scope (tenant|sitecollection)
o365cli_app_catalog_scope: 'tenant'
variable_group_name: ''
jobs:
- deployment: ${{ parameters.job_name }}
displayName: ${{ parameters.display_name }}
pool:
vmImage: 'ubuntu-latest'
environment: ${{ parameters.target_environment }}
variables:
- group: ${{parameters.variable_group_name}} #o365_user_login, o365_user_password, o365_app_catalog_site_url
strategy:
runOnce:
deploy:
steps:
- checkout: none
- download: current
artifact: drop
patterns: '**/*.sppkg'
- script: sudo npm install --global @pnp/office365-cli
displayName: Install Office365 CLI
- script: o365 login $(o365_app_catalog_site_url) --authType password --userName $(o365_user_login) --password $(o365_user_password)
displayName: Login to Office365
- script: |
CMD_GET_SPPKG_NAME=$(find $(Pipeline.Workspace)/drop -name '*.sppkg' -exec basename {} \;)
echo "##vso[task.setvariable variable=SpPkgFileName;isOutput=true]${CMD_GET_SPPKG_NAME}"
displayName: Get generated *.sppkg filename
name: GetSharePointPackage
- script: o365 spo app add --filePath "$(Pipeline.Workspace)/drop/sharepoint/solution/$(GetSharePointPackage.SpPkgFileName)" --appCatalogUrl $(o365_app_catalog_site_url) --scope ${{ parameters.o365cli_app_catalog_scope }} --overwrite
displayName: Upload SharePoint package to Site Collection App Catalog
- script: o365 spo app deploy --name $(GetSharePointPackage.SpPkgFileName) --appCatalogUrl $(o365_app_catalog_site_url) --scope ${{ parameters.o365cli_app_catalog_scope }}
displayName: Deploy SharePoint package

View File

@ -0,0 +1,26 @@
name: $(TeamProject)_$(BuildDefinitionName)_$(SourceBranchName)_$(Date:yyyyMMdd)$(Rev:.r)
resources:
- repo: self
trigger:
branches:
include:
- master
- develop
stages:
- stage: build
displayName: build
jobs:
- template: ./azure-pipelines-build-template.yml
parameters:
name: 'buildsolution'
- stage: 'deployqa'
# uncomment if you want deployments to occur only for a specific branch
#condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/develop'))
jobs:
- template: ./azure-pipelines-deploy-template.yml
parameters:
job_name: deploy_solution
target_environment: 'qa'
variable_group_name: qa_configuration

View File

@ -0,0 +1,20 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"restaurant-menu-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/restaurantMenu/RestaurantMenuWebPart.js",
"manifest": "./src/webparts/restaurantMenu/RestaurantMenuWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"RestaurantMenuWebPartStrings": "lib/webparts/restaurantMenu/loc/{locale}.js",
"ControlStrings": "node_modules/@pnp/spfx-controls-react/lib/loc/{locale}.js",
"PropertyControlStrings": "node_modules/@pnp/spfx-property-controls/lib/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,6 @@
{
"includeExtensions": [
"svg",
"png"
]
}

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": "react-menu",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1 @@
{"preset":"@voitanos/jest-preset-spfx-react16","rootDir":"../src","collectCoverageFrom":["<rootDir>/**/*.{ts,tsx}","!<rootDir>/**/*.scss.*","!<rootDir>/loc/**/*.*"],"coverageReporters":["text","json","lcov","text-summary","cobertura"],"reporters":["default",["jest-junit",{"suiteName":"jest tests","outputDirectory":"temp/test/junit","outputName":"junit.xml"}]]}

View File

@ -0,0 +1,21 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-restaurante-menu-app",
"id": "e1632e6a-caf2-4dba-9d88-32783876aa2b",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "João Mendes",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": ""
}
},
"paths": {
"zippedPackage": "solution/react-restaurant-menu.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,29 @@
'use strict';
// check if gulp dist was called
if (process.argv.indexOf('dist') !== -1) {
// add ship options to command call
process.argv.push('--ship');
}
const path = require('path');
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
const gulpSequence = require('gulp-sequence');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
// Create clean distrubution package
gulp.task('dist', gulpSequence('clean', 'bundle', 'package-solution'));
// Create clean development package
gulp.task('dev', gulpSequence('clean', 'bundle', 'package-solution'));
/**
* Custom Framework Specific gulp tasks
*/
build.initialize(gulp);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,60 @@
{
"name": "react-restaurant-menu",
"version": "1.0.0",
"private": true,
"main": "lib/index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"preversion": "node ./tools/pre-version.js",
"postversion": "gulp dist",
"test": "./node_modules/.bin/jest --config ./config/jest.config.json",
"test:watch": "./node_modules/.bin/jest --config ./config/jest.config.json --watchAll"
},
"dependencies": {
"@microsoft/sp-core-library": "1.11.0",
"@microsoft/sp-lodash-subset": "1.11.0",
"@microsoft/sp-office-ui-fabric-core": "1.11.0",
"@microsoft/sp-property-pane": "1.11.0",
"@microsoft/sp-webpart-base": "1.11.0",
"@pnp/pnpjs": "^2.0.6",
"@pnp/spfx-controls-react": "1.19.0",
"@pnp/spfx-property-controls": "1.19.0",
"@types/jquery": "^3.5.0",
"jquery": "^3.5.1",
"moment": "^2.27.0",
"office-ui-fabric-react": "^7.123.1",
"react": "16.8.5",
"react-dom": "16.8.5"
},
"devDependencies": {
"@microsoft/microsoft-graph-types": "^1.12.0",
"@microsoft/rush-stack-compiler-3.7": "^0.6.x",
"@microsoft/sp-build-web": "1.11.0",
"@microsoft/sp-module-interfaces": "1.11.0",
"@microsoft/sp-tslint-rules": "1.11.0",
"@microsoft/sp-webpart-workbench": "1.11.0",
"@types/chai": "3.4.34",
"@types/es6-promise": "0.0.33",
"@types/mocha": "2.2.38",
"@types/react": "^16.9.43",
"@types/react-dom": "16.8.3",
"@types/webpack-env": "1.13.1",
"@voitanos/jest-preset-spfx-react16": "^1.3.2",
"ajv": "~5.2.2",
"gulp": "~3.9.1",
"gulp-sequence": "1.0.0",
"jest": "^23.6.0",
"jest-junit": "^10.0.0",
"lodash": "^4.17.15",
"spfx-uifabric-themes": "^0.8.0",
"typescript": "~3.7.x"
},
"jest-junit": {
"output": "temp/test/junit/junit.xml",
"usePathForSuiteName": "true"
}
}

View File

@ -0,0 +1,23 @@
key;Locale en-us;RestaurantMenuWebPartStrings
DESSERTLABEL;DESSERT;x
PropertyPaneDescription;Description;x
BasicGroupName;Group Name;x
DescriptionFieldLabel;Description Field;x
VeganLabel; VEGAN;x
DietLabel; DIET;x
FishLabel; FISH;x
MeatLabel; MEAT;x
SoupLabel; SOUP;x
NoInformationLabel;No information found;x
DessertLabel;DESSERT;x
DessertFieldPropertyLabel;Dessert field;x
VeganFieldPropertyLabel;Vegan field;x
DietFieldPropertyLabel;Diet field;x
FishFieldPropertyLabel;Fish field;x
MeatFieldPropertyLabel;Meat field;x
SoupFieldPropertyLabel;Soup field;x
DateInformationMessage;" \""Date field is required to filter menu information\""";x
DateFieldPropertyLabel;Date Field;x
PlaceHolderIconTextLabel;Configure Restaurant Menu web part;x
PlaceholderDescription;Please configure the web part with information required;x
PlaceholderButtonLabel;Configure;x
1 key Locale en-us RestaurantMenuWebPartStrings
2 DESSERTLABEL DESSERT x
3 PropertyPaneDescription Description x
4 BasicGroupName Group Name x
5 DescriptionFieldLabel Description Field x
6 VeganLabel VEGAN x
7 DietLabel DIET x
8 FishLabel FISH x
9 MeatLabel MEAT x
10 SoupLabel SOUP x
11 NoInformationLabel No information found x
12 DessertLabel DESSERT x
13 DessertFieldPropertyLabel Dessert field x
14 VeganFieldPropertyLabel Vegan field x
15 DietFieldPropertyLabel Diet field x
16 FishFieldPropertyLabel Fish field x
17 MeatFieldPropertyLabel Meat field x
18 SoupFieldPropertyLabel Soup field x
19 DateInformationMessage \"Date field is required to filter menu information\" x
20 DateFieldPropertyLabel Date Field x
21 PlaceHolderIconTextLabel Configure Restaurant Menu web part x
22 PlaceholderDescription Please configure the web part with information required x
23 PlaceholderButtonLabel Configure x

View File

@ -0,0 +1,24 @@
{
"themePrimary": "#6264a7",
"themeLighterAlt": "#f7f7fb",
"themeLighter": "#e1e1f1",
"themeLight": "#c8c9e4",
"themeTertiary": "#989ac9",
"themeSecondary": "#7173b0",
"themeDarkAlt": "#585a95",
"themeDark": "#4a4c7e",
"themeDarker": "#37385d",
"neutralLighterAlt": "#0b0b0b",
"neutralLighter": "#151515",
"neutralLight": "#252525",
"neutralQuaternaryAlt": "#2f2f2f",
"neutralQuaternary": "#373737",
"neutralTertiaryAlt": "#595959",
"neutralTertiary": "#c8c8c8",
"neutralSecondary": "#d0d0d0",
"neutralPrimaryAlt": "#dadada",
"neutralPrimary": "#ffffff",
"neutralDark": "#f4f4f4",
"black": "#f8f8f8",
"white": "#000000"
}

View File

@ -0,0 +1,24 @@
{
"themePrimary": "#6264a7",
"themeLighterAlt": "#f7f7fb",
"themeLighter": "#e1e1f1",
"themeLight": "#c8c9e4",
"themeTertiary": "#989ac9",
"themeSecondary": "#7173b0",
"themeDarkAlt": "#585a95",
"themeDark": "#4a4c7e",
"themeDarker": "#37385d",
"neutralLighterAlt": "#2d2c2c",
"neutralLighter": "#2c2b2b",
"neutralLight": "#2a2929",
"neutralQuaternaryAlt": "#272626",
"neutralQuaternary": "#252525",
"neutralTertiaryAlt": "#242323",
"neutralTertiary": "#c8c8c8",
"neutralSecondary": "#d0d0d0",
"neutralPrimaryAlt": "#dadada",
"neutralPrimary": "#ffffff",
"neutralDark": "#f4f4f4",
"black": "#f8f8f8",
"white": "#2d2c2c"
}

View File

@ -0,0 +1,24 @@
{
"themePrimary": "#6264a7",
"themeLighterAlt": "#f7f7fb",
"themeLighter": "#e1e1f1",
"themeLight": "#c8c9e4",
"themeTertiary": "#989ac9",
"themeSecondary": "#7173b0",
"themeDarkAlt": "#585a95",
"themeDark": "#4a4c7e",
"themeDarker": "#37385d",
"neutralLighterAlt": "#ecebe9",
"neutralLighter": "#e8e7e6",
"neutralLight": "#dedddc",
"neutralQuaternaryAlt": "#cfcecd",
"neutralQuaternary": "#c6c5c4",
"neutralTertiaryAlt": "#bebdbc",
"neutralTertiary": "#b5b4b2",
"neutralSecondary": "#9d9c9a",
"neutralPrimaryAlt": "#868482",
"neutralPrimary": "#252423",
"neutralDark": "#565453",
"black": "#3e3d3b",
"white": "#f3f2f1"
}

View File

@ -0,0 +1,16 @@
$default-background: #f3f2f1;
$default-color: #252423;
$default-button-background: #6264a7;
$default-Button-color: #f3f2f1;
// dark theme
$dark-background: #2d2c2c;
$dark-color: #ffffff;
$dark-button-background: #6264a7;
$dark-button-color: #2d2c2c;
// contrast theme
$contrast-background: #000000;
$contrast-color: #ffffff;
$contrast-button-background: #b5c01c;
$contrast-Button-color: #000000;

View File

@ -0,0 +1,9 @@
export interface IMenuFields {
dateFieldName: string;
soupFieldName: string;
meatFieldName: string;
fishFieldName: string;
dietFieldName :string;
veganFieldName: string;
dessertFieldName: string;
}

View File

@ -0,0 +1,14 @@
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/fields/list";
import { IFieldInfo } from "@pnp/sp/fields/types";
import { Web, IWeb } from "@pnp/sp/webs";
export const useGetListFields = async (webUrl:string,listId:string): Promise<IFieldInfo[]> => {
const list = Web(webUrl).lists.getById(listId);
const _fields:IFieldInfo[] = await list.fields();
console.log('fields',_fields);
return _fields;
};

View File

@ -0,0 +1,58 @@
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/fields/list";
import { IFieldInfo, IField } from "@pnp/sp/fields/types";
import { Web } from "@pnp/sp/webs";
import "@pnp/sp/items";
import moment from "moment";
import { IMenuFields } from "../entities.ts/IMenuFields";
export const useGetListFields = async (
webUrl: string,
listId: string
): Promise<IFieldInfo[]> => {
const list = Web(webUrl).lists.getById(listId);
const _fields: IFieldInfo[] = await list.fields();
return _fields;
};
export const useGetFieldProperties = async (
webUrl: string,
listId: string,
fieldInternalName: string
): Promise<IField> => {
const list = Web(webUrl).lists.getById(listId);
const _field: IField = await list.fields.getByInternalNameOrTitle(
fieldInternalName
);
return _field;
};
export const useGetListItems = async (
webUrl: string,
listId: string,
fields: IMenuFields
): Promise<any[]> => {
const dataIni = moment().isoWeekday(1).utc(); // monday
const dataEnd = moment().isoWeekday(7).utc(); // friday
try {
const listItemsReturn: any[] = await Web(webUrl)
.lists.getById(listId)
.usingCaching()
.getItemsByCAMLQuery({
ViewXml: `<View><Query><Where><And><Geq><FieldRef Name="${
fields.dateFieldName
}" /><Value IncludeTimeValue="false" Type="DateTime">${dataIni.toISOString()}</Value></Geq><Leq><FieldRef Name="Date" /><Value IncludeTimeValue="false" Type="DateTime">${dataEnd.toISOString()}</Value></Leq></And></Where></Query></View>`,
});
return listItemsReturn;
} catch (error) {
console.log(error);
return [];
}
};

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,39 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "3974c454-c043-4705-8fce-7c784426fce0",
"alias": "RestaurantMenuWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
"supportsThemeVariants": true,
// 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", "TeamsPersonalApp", "TeamsTab"],
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "SPFx Custom Web Parts" },
"title": { "default": "Restaurant Menu" },
"description": { "default": "Restaurant Menu" },
"officeFabricIconFontName": "ContextMenu",
"properties": {
"title": "Restaurant Menu",
"site": [],
"listId": "",
"dateFieldName": "",
"soupFieldName": "",
"meatFieldName": "",
"fishFieldName": "",
"dietFieldName": "",
"veganFieldName": "",
"dessertFieldName": ""
}
}]
}

View File

@ -0,0 +1,420 @@
import * as React from "react";
import * as ReactDom from "react-dom";
import { Version, DisplayMode } from "@microsoft/sp-core-library";
import {
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneDropdown,
IPropertyPaneDropdownOption,
IPropertyPaneField,
IPropertyPaneGroup,
PropertyPaneLabel,
} from "@microsoft/sp-property-pane";
import { BaseClientSideWebPart, IPropertyPaneAccessor, PropertyPaneToggle } from "@microsoft/sp-webpart-base";
import { IFieldInfo, FieldTypes } from "@pnp/sp/fields/types";
import * as strings from "RestaurantMenuWebPartStrings";
import { RestaurantMenu } from "./components/RestaurantMenu";
import { IRestaurantMenuProps } from "./components/IRestaurantMenuProps";
import {
PropertyFieldListPicker,
PropertyFieldListPickerOrderBy,
} from "@pnp/spfx-property-controls/lib/PropertyFieldListPicker";
import {
PropertyFieldSitePicker,
IPropertyFieldSite,
} from "@pnp/spfx-property-controls/lib/PropertyFieldSitePicker";
import { PropertyFieldMessage} from '@pnp/spfx-property-controls/lib/PropertyFieldMessage';
import { sp } from "@pnp/sp";
import {
ThemeProvider,
ThemeChangedEventArgs,
IReadonlyTheme,
} from "@microsoft/sp-component-base";
import { loadTheme, IDropdownOption, MessageBarType } from "office-ui-fabric-react";
import { useGetListFields } from "../../hooks/useSPList";
import { filter, Dictionary } from "lodash";
const teamsDefaultTheme = require('../../Common/TeamsDefaultTheme.json');
const teamsDarkTheme = require('../../Common/TeamsDarkTheme.json');
const teamsContrastTheme = require('../../Common/TeamsContrastTheme.json');
export interface IRestaurantMenuWebPartProps {
title: string;
site: IPropertyFieldSite[];
listId: string;
dateFieldName: string;
dietFieldName: string;
soupFieldName: string;
meatFieldName: string;
fishFieldName: string;
veganFieldName: string;
dessertFieldName: string;
displayMode: DisplayMode;
updateProperty: (value: string) => void;
propertyPanel: IPropertyPaneAccessor;
showBox: boolean;
}
export default class RestaurantMenuWebPart extends BaseClientSideWebPart<
IRestaurantMenuWebPartProps
> {
private fieldDateOptions: IPropertyPaneDropdownOption[] = [];
private fieldSoupOptions: IPropertyPaneDropdownOption[] = [];
private fieldMeatOptions: IPropertyPaneDropdownOption[] = [];
private fieldFishOptions: IPropertyPaneDropdownOption[] = [];
private fieldDietOptions: IPropertyPaneDropdownOption[] = [];
private fieldVeganOptions: IPropertyPaneDropdownOption[] = [];
private fieldDessertOptions: IPropertyPaneDropdownOption[] = [];
private _themeProvider: ThemeProvider;
private _themeVariant: IReadonlyTheme | undefined;
private _listProperty: IPropertyPaneField<any> = {} as IPropertyPaneField<
any
>;
private listFieldProperties: IPropertyPaneField<any>[] = [];
protected async onInit(): Promise<void> {
sp.setup({
spfxContext: this.context,
});
this._themeProvider = this.context.serviceScope.consume(
ThemeProvider.serviceKey
);
// If it exists, get the theme variant
this._themeVariant = this._themeProvider.tryGetTheme();
// Register a handler to be notified if the theme variant changes
this._themeProvider.themeChangedEvent.add(
this,
this._handleThemeChangedEvent
);
if (this.context.sdks.microsoftTeams) {
// in teams ?
const context = this.context.sdks.microsoftTeams!.context;
console.log("theme", this._themeVariant);
this._applyTheme(context.theme || "default");
this.context.sdks.microsoftTeams.teamsJs.registerOnThemeChangeHandler(
this._applyTheme
);
}
return Promise.resolve();
}
/**
* Update the current theme variant reference and re-render.
*
* @param args The new theme
*/
private _handleThemeChangedEvent(args: ThemeChangedEventArgs): void {
this._themeVariant = args.theme;
console.log("theme", this._themeVariant);
this.render();
}
// Apply btheme id in Teams
private _applyTheme = (theme: string): void => {
this.context.domElement.setAttribute("data-theme", theme);
document.body.setAttribute("data-theme", theme);
if (theme == "dark") {
loadTheme({
palette: teamsDarkTheme,
});
}
if (theme == "default") {
loadTheme({
palette: teamsDefaultTheme,
});
}
if (theme == "contrast") {
loadTheme({
palette: teamsContrastTheme,
});
}
}
protected get disableReactivePropertyChanges() {
return true;
}
public render(): void {
const element: React.ReactElement<IRestaurantMenuProps> = React.createElement(
RestaurantMenu,
{
title: this.properties.title,
site: this.properties.site,
listId: this.properties.listId,
propertyPanel: this.context.propertyPane,
dateFieldName: this.properties.dateFieldName,
dietFieldName: this.properties.dietFieldName,
soupFieldName: this.properties.soupFieldName,
meatFieldName: this.properties.meatFieldName,
fishFieldName: this.properties.fishFieldName,
veganFieldName: this.properties.veganFieldName,
dessertFieldName: this.properties.dessertFieldName,
showBox: this.properties.showBox,
themeVariant: this._themeVariant,
displayMode: this.displayMode,
updateProperty: (value: string) => {
this.properties.title = value;
},
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse("1.0");
}
protected async onPropertyPaneFieldChanged(
propertyPath: string,
oldValue: any,
newValue: any
): Promise<void> {
let _fieldsOptions: IPropertyPaneDropdownOption[] = [];
if (propertyPath === "site" && newValue) {
this.properties.listId = undefined;
this.properties.fishFieldName= '';
this.properties.dateFieldName= '';
this.properties.dessertFieldName= '';
this.properties.soupFieldName= '';
this.properties.meatFieldName= '';
this.properties.veganFieldName= '';
this.context.propertyPane.refresh;
}
if (propertyPath === "listId" && newValue) {
this.properties.listId = newValue;
super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue);
this.properties.fishFieldName= '';
this.properties.dateFieldName= '';
this.properties.dessertFieldName= '';
this.properties.soupFieldName= '';
this.properties.meatFieldName= '';
this.properties.veganFieldName= '';
this.fieldSoupOptions = [];
this.fieldDessertOptions = [];
this.fieldDietOptions = [];
this.fieldFishOptions = [];
this.fieldMeatOptions = [];
this.fieldVeganOptions = [];
this.fieldDateOptions = [];
this.context.propertyPane.refresh();
const fields: IFieldInfo[] = await useGetListFields(
this.properties.site[0].url,
newValue
);
for (const field of fields) {
if (field.FieldTypeKind == FieldTypes.DateTime) {
this.fieldDateOptions.push({
key: field.InternalName,
text: field.Title,
});
}
if (
field.FieldTypeKind == FieldTypes.Text ||
field.FieldTypeKind == FieldTypes.Note
) {
_fieldsOptions.push({ key: field.InternalName, text: field.Title });
}
}
this.fieldDessertOptions = _fieldsOptions;
this.fieldDietOptions = _fieldsOptions;
this.fieldFishOptions = _fieldsOptions;
this.fieldMeatOptions = _fieldsOptions;
this.fieldSoupOptions = _fieldsOptions;
this.fieldVeganOptions = _fieldsOptions;
this.context.propertyPane.refresh();
}
}
protected async onPropertyPaneConfigurationStart(): Promise<void> {
if (this.properties.listId) {
if (this.fieldDateOptions.length > 0) {
return;
}
const fields: IFieldInfo[] = await useGetListFields(
this.properties.site[0].url,
this.properties.listId
);
const _fieldsOptions: IPropertyPaneDropdownOption[] = [];
for (const field of fields) {
if (field.FieldTypeKind == FieldTypes.DateTime) {
this.fieldDateOptions.push({
key: field.InternalName,
text: field.Title,
});
}
if (
field.FieldTypeKind == FieldTypes.Text ||
field.FieldTypeKind == FieldTypes.Note
) {
_fieldsOptions.push({ key: field.InternalName, text: field.Title });
}
}
this.fieldDessertOptions = _fieldsOptions;
this.fieldDietOptions = _fieldsOptions;
this.fieldFishOptions = _fieldsOptions;
this.fieldMeatOptions = _fieldsOptions;
this.fieldSoupOptions = _fieldsOptions;
this.fieldVeganOptions = _fieldsOptions;
this.context.propertyPane.refresh();
}
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
if (this.properties.site.length > 0) {
this._listProperty = PropertyFieldListPicker("listId", {
context: this.context,
label: "Select List",
onPropertyChange: this.onPropertyPaneFieldChanged,
properties: this.properties,
baseTemplate: 100,
deferredValidationTime: 300,
key: "listfilter",
selectedList: this.properties.listId,
multiSelect: false,
webAbsoluteUrl: this.properties.site[0].url,
orderBy: PropertyFieldListPickerOrderBy.Title,
});
} else {
this._listProperty = {} as IPropertyPaneField<any>;
}
// new List
if (this.properties.listId) {
this.listFieldProperties = [];
this.listFieldProperties = [
PropertyPaneLabel('',{
text: ""
}),
PropertyPaneLabel('',{
text: "Field Mapping"
}),
PropertyPaneLabel('',{
text: ""
}),
PropertyPaneDropdown("dateFieldName", {
options: [{ key: "N/A", text: "Not available" },...this.fieldDateOptions],
label: strings.DateFieldPropertyLabel,
selectedKey: this.properties.dateFieldName || "N/A",
}),
PropertyFieldMessage("", {
key: "MessageKey",
text:strings.DateInformationMessage,
messageType: MessageBarType.info,
isVisible: this.properties.dateFieldName === "N/A" ,
}),
PropertyPaneDropdown("soupFieldName", {
options: [{ key: "N/A", text: "Not available" }, ...this.fieldSoupOptions],
label: strings.SoupFieldPropertyLabel,
selectedKey: this.properties.soupFieldName || "N/A",
}),
PropertyPaneDropdown("meatFieldName", {
options:[{ key: "N/A", text: "Not available" },...this.fieldMeatOptions],
label: strings.MeatFieldPropertyLabel,
selectedKey: this.properties.meatFieldName || "N/A",
}),
PropertyPaneDropdown("fishFieldName", {
options: [ { key: "N/A", text: "Not available" }, ...this.fieldFishOptions] ,
label: strings.FishFieldPropertyLabel,
selectedKey: this.properties.fishFieldName || "N/A",
}),
PropertyPaneDropdown("dietFieldName", {
options: [ { key: "N/A", text: "Not available" }, ...this.fieldDietOptions] ,
label: strings.DietFieldPropertyLabel,
selectedKey: this.properties.dietFieldName || "N/A",
}),
PropertyPaneDropdown("veganFieldName", {
options: [
{ key: "N/A", text: "Not available" },
...this.fieldVeganOptions,
],
label: strings.VeganFieldPropertyLabel,
selectedKey: this.properties.veganFieldName || "N/A",
}),
PropertyPaneDropdown("dessertFieldName", {
options: [{ key: "N/A", text: "Not available" },...this.fieldDessertOptions],
label: strings.DessertFieldPropertyLabel,
selectedKey: this.properties.dessertFieldName || "N/A",
}),
];
} else {
this.listFieldProperties = [];
}
// configuration panel default options
const configuration: IPropertyPaneConfiguration = {
pages: [
{
header: {
description: strings.PropertyPaneDescription,
},
displayGroupsAsAccordion: true,
groups: [
{
groupName: strings.BasicGroupName,
isCollapsed: true,
groupFields: [
PropertyPaneTextField("title", {
label: strings.DescriptionFieldLabel,
}),
PropertyPaneToggle("showBox", {
label: "Show background box ?",
checked: this.properties.showBox
}),
],
},
],
},
],
};
// get groups first page
const { groups } = configuration.pages[0];
// SourceDataGroup
const sourceDataGroup: IPropertyPaneGroup = {
groupName: "Source of data",
isCollapsed: true,
groupFields: [
PropertyFieldSitePicker("site", {
label: "Select site",
initialSites: this.properties.site || [],
context: this.context,
deferredValidationTime: 500,
multiSelect: false,
onPropertyChange: this.onPropertyPaneFieldChanged,
properties: this.properties,
key: "sitesFieldId",
}),
this._listProperty,
...this.listFieldProperties,
],
};
// Add aditional groups
groups.push(sourceDataGroup);
// return configuration
return configuration;
}
}

View File

@ -0,0 +1,9 @@
export enum EWeekdays {
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}

View File

@ -0,0 +1,19 @@
import { IPropertyFieldSite } from "@pnp/spfx-property-controls/lib/PropertyFieldSitePicker";
import {
IReadonlyTheme,
} from "@microsoft/sp-component-base";
import { EWeekdays } from "./EWeekDays";
import { IPropertyPaneAccessor } from "@microsoft/sp-webpart-base";
export interface IMenuDetailProps {
dayOfWeek: EWeekdays;
themeVariant: IReadonlyTheme ;
listId:string;
site:any[];
dateFieldName: string;
soupFieldName: string;
meatFieldName: string;
fishFieldName: string;
dietFieldName :string;
veganFieldName: string;
dessertFieldName: string;
}

View File

@ -0,0 +1,6 @@
export interface IMenuDetailState {
isLoading:boolean;
hasHerror:boolean;
errorMessage:string;
menuDetails: any ;
}

View File

@ -0,0 +1,23 @@
import { IPropertyFieldSite } from "@pnp/spfx-property-controls/lib/PropertyFieldSitePicker";
import {
IReadonlyTheme,
} from "@microsoft/sp-component-base";
import { DisplayMode } from "@microsoft/sp-core-library";
import { IPropertyPaneAccessor } from "@microsoft/sp-webpart-base";
export interface IRestaurantMenuProps {
title: string;
site: IPropertyFieldSite[];
listId: string;
dateFieldName: string;
soupFieldName: string;
meatFieldName: string;
fishFieldName: string;
veganFieldName: string;
dietFieldName: string;
dessertFieldName: string;
themeVariant: IReadonlyTheme | undefined;
showBox:boolean;
displayMode: DisplayMode;
propertyPanel: IPropertyPaneAccessor;
updateProperty: (value: string) => void;
}

View File

@ -0,0 +1,267 @@
import * as React from "react";
import { IMenuDetailProps } from "./IMenuDetailProps";
import * as strings from "RestaurantMenuWebPartStrings";
import {
Stack,
IStackTokens,
Label,
Text,
Spinner,
SpinnerSize,
MessageBar,
mergeStyleSets,
ILabelStyles,
FontIcon,
ImageIcon,
Image,
ImageFit,
Customizer,
MessageBarType,
} from "office-ui-fabric-react";
import { IMenuDetailState } from "./IMenuDetailState";
import { useGetListItems } from "../../../hooks/useSPList";
import { EWeekdays } from "./EWeekDays";
import { filter } from "lodash";
import moment from "moment";
import { IMenuFields } from "../../../entities.ts/IMenuFields";
// global const and vars
const stackTokens: IStackTokens = {
childrenGap: 10,
};
// Component Styles
const stackStyles = {
root: {
width: "100%",
},
};
let listItems: any[] = [];
const imageNoData:string = require('../../../../assets/Eating.svg');
/// Component
export const MenuDetail: React.FunctionComponent<IMenuDetailProps> = (
props: IMenuDetailProps
) => {
const styleClasses = mergeStyleSets({
separator: {
borderBottomStyle: "solid",
borderWidth: 1,
borderBottomColor: props.themeVariant.palette.themeLighter,
},
fieldLabelStyle: {
paddingTop: 0,
marginTop: "3px !important",
overflow: "hidden",
marginBottom: 10,
},
menuIcon: {
fontSize: 18,
},
labelStyles: {
textTransform: "uppercase",
fontWeight: 600,
fontSize: props.themeVariant.fonts.medium.fontSize,
color: props.themeVariant.palette.themePrimary,
marginBottom: 0,
paddingBottom: 0,
},
});
const labelStyles: Partial<ILabelStyles> = {
root: {
textTransform: "uppercase",
fontWeight: 600,
paddingTop: 5,
fontSize: props.themeVariant.fonts.medium.fontSize,
color: props.themeVariant.palette.themePrimary,
marginBottom: 0,
paddingBottom: 0,
},
};
const [state, setState] = React.useState<IMenuDetailState>({
isLoading: true,
hasHerror: false,
errorMessage: "",
menuDetails: undefined,
});
React.useEffect(() => {
(async () => {
try {
const _menuFields: IMenuFields = {
dateFieldName: props.dateFieldName,
soupFieldName: props.soupFieldName,
fishFieldName: props.fishFieldName,
meatFieldName: props.meatFieldName,
dietFieldName: props.dietFieldName,
veganFieldName: props.veganFieldName,
dessertFieldName: props.dessertFieldName,
};
setState({ ...state, isLoading: true });
listItems = await useGetListItems(
props.site[0].url,
props.listId,
_menuFields
);
const _menuDetails = await selectDay();
setState({ ...state, isLoading: false, menuDetails: _menuDetails });
} catch (error) {
setState({
...state,
hasHerror: true,
errorMessage: JSON.stringify(error),
});
console.log(error);
}
})();
}, [props.site, props.listId, props.dateFieldName]); // key fields properties runs on change and get items
// run when day of week change Navigation tab
React.useEffect(() => {
(async () => {
if (listItems.length === 0) return; // to ensure that runs only the listitem are filled
try {
setState({ ...state, isLoading: true });
const _menuDetails = await selectDay();
setState({ ...state, isLoading: false, menuDetails: _menuDetails });
} catch (error) {
setState({
...state,
hasHerror: true,
errorMessage: JSON.stringify(error),
});
console.log(error);
}
})();
}, [props.dayOfWeek]);
// Select day of week
const selectDay = async (): Promise<any> => {
const { dayOfWeek } = props;
let _item: any[] = [];
switch (dayOfWeek) {
case EWeekdays.Monday:
_item = _item = selectItem(EWeekdays.Monday );
break;
case EWeekdays.Tuesday:
_item = _item = selectItem(EWeekdays.Tuesday );
break;
case EWeekdays.Wednesday:
_item = _item = selectItem(EWeekdays.Wednesday );
break;
case EWeekdays.Thursday:
_item = selectItem(EWeekdays.Thursday );
break;
case EWeekdays.Friday:
_item = _item = selectItem(EWeekdays.Friday );
break;
default:
break;
}
return _item;
};
// Get Item from the Array os listItems
const selectItem = (day: number): any => {
const _dt2 = moment().isoWeekday(day).format("YYYY-MM-DD");
const _selectedItems = listItems.filter((_item) => {
const _dt1 = moment(_item[props.dateFieldName]).format("YYYY-MM-DD");
return _dt1 == _dt2;
});
return _selectedItems[0];
};
if (state.isLoading) {
return <Spinner size={SpinnerSize.medium} ></Spinner>;
}
if (state.hasHerror) {
return (
<MessageBar messageBarType={MessageBarType.error}>
{state.errorMessage}
</MessageBar>
);
}
if (!state.menuDetails) {
return (
<>
<Stack horizontalAlign="center" verticalAlign="center" style={{marginTop: 20}}>
<Image src={imageNoData} width={120} height={120} imageFit={ImageFit.cover}></Image>
<Text variant="large">{strings.NoInformationLabel}</Text>
</Stack>
</>
);
}
return (
<>
<Stack tokens={stackTokens} >
{state.menuDetails[props.soupFieldName] && (
<>
<Label styles={labelStyles}>{strings.SoupLabel}</Label>
<div className={styleClasses.fieldLabelStyle}>
{state.menuDetails[props.soupFieldName]}
</div>
</>
)}
{state.menuDetails[props.meatFieldName] && (
<>
<div className={styleClasses.separator}></div>
<Label styles={labelStyles}>{strings.MeatLabel}</Label>
<div className={styleClasses.fieldLabelStyle}>
{state.menuDetails[props.meatFieldName]}
</div>
</>
)}
{state.menuDetails[props.fishFieldName] && (
<>
<div className={styleClasses.separator}></div>
<Label styles={labelStyles}>{strings.FishLabel}</Label>
<div className={styleClasses.fieldLabelStyle}>
{state.menuDetails[props.fishFieldName]}
</div>
</>
)}
{state.menuDetails[props.dietFieldName] && (
<>
<div className={styleClasses.separator}></div>
<Label styles={labelStyles}>{strings.DietLabel}</Label>
<div className={styleClasses.fieldLabelStyle}>
{state.menuDetails[props.dietFieldName]}
</div>
</>
)}
{state.menuDetails[props.veganFieldName] && (
<>
<div className={styleClasses.separator}></div>
<Label styles={labelStyles}>{strings.VeganLabel}</Label>
<div className={styleClasses.fieldLabelStyle}>
{state.menuDetails[props.veganFieldName]}
</div>
</>
)}
{state.menuDetails[props.dessertFieldName] && (
<>
<div className={styleClasses.separator}></div>
<Label styles={labelStyles}>{strings.DessertLabel}</Label>
<div className={styleClasses.fieldLabelStyle}>
{state.menuDetails[props.dessertFieldName]}
</div>
<div className={styleClasses.separator}></div>
</>
)}
</Stack>
</>
);
};

View File

@ -0,0 +1,91 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
.linkButtonStyle {
min-Width: 45px;
font-weight: $ms-font-weight-semibold;
font-size: $ms-font-size-m;
height: 32px;
display: flex;
align-Items: "center";
justify-Content: "center",
}
.linkButtonStyle:not(:last-child){
margin-right: 5px;
}
.restaurantMenu {
.container {
max-width: 700px;
margin: 0px auto;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.row {
@include ms-Grid-row;
@include ms-fontColor-white;
background-color: $ms-color-themeDark;
padding: 20px;
}
.column {
@include ms-Grid-col;
@include ms-lg10;
@include ms-xl8;
@include ms-xlPush2;
@include ms-lgPush1;
}
.title {
@include ms-font-xl;
@include ms-fontColor-white;
}
.subTitle {
@include ms-font-l;
@include ms-fontColor-white;
}
.description {
@include ms-font-l;
@include ms-fontColor-white;
}
.button {
// Our button
text-decoration: none;
height: 32px;
// Primary Button
min-width: 80px;
background-color: $ms-color-themePrimary;
border-color: $ms-color-themePrimary;
color: $ms-color-white;
// Basic Button
outline: transparent;
position: relative;
font-family: "Segoe UI WestEuropean","Segoe UI",-apple-system,BlinkMacSystemFont,Roboto,"Helvetica Neue",sans-serif;
-webkit-font-smoothing: antialiased;
font-size: $ms-font-size-m;
font-weight: $ms-font-weight-regular;
border-width: 0;
text-align: center;
cursor: pointer;
display: inline-block;
padding: 0 16px;
.label {
font-weight: $ms-font-weight-semibold;
font-size: $ms-font-size-m;
height: 32px;
line-height: 32px;
margin: 0 4px;
vertical-align: top;
display: inline-block;
}
}
}

View File

@ -0,0 +1,348 @@
import * as React from "react";
import styles from "./RestaurantMenu.module.scss";
import { IRestaurantMenuProps } from "./IRestaurantMenuProps";
import { escape } from "@microsoft/sp-lodash-subset";
import {
mergeStyleSets,
Customizer,
Stack,
IStackTokens,
FontIcon,
Label,
Text,
} from "office-ui-fabric-react";
import moment from "moment";
import { EWeekdays } from "./EWeekDays";
import { MenuDetail } from "./MenuDetail";
import { css } from "office-ui-fabric-react/lib/Utilities";
import { WebPartTitle } from "@pnp/spfx-controls-react";
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
import { toUpper } from "lodash";
import { DisplayMode } from "@microsoft/sp-core-library";
import { PropertyPaneSlider } from "@microsoft/sp-webpart-base";
import strings from "RestaurantMenuWebPartStrings";
const stackTokens: IStackTokens = {
childrenGap: 10,
};
// Component Styles
const stackStyles = {
root: {
width: "100%",
},
};
export const RestaurantMenu: React.FunctionComponent<IRestaurantMenuProps> = (
props: IRestaurantMenuProps
) => {
const [monday, setMonday] = React.useState<boolean>(false);
const [tuesday, setTuesday] = React.useState<boolean>(false);
const [wednesday, setWednesday] = React.useState<boolean>(false);
const [thursday, setThursday] = React.useState<boolean>(false);
const [friday, setFriday] = React.useState<boolean>(false);
const [showMenuDetails, setShowMenuDetails] = React.useState<boolean>(false);
const [showMenuForDay, setShowMenuForDay] = React.useState<EWeekdays>( () =>
{
if ( moment().isoWeekday() === EWeekdays.Sunday || moment().isoWeekday() === EWeekdays.Saturday ) {
return (EWeekdays.Friday);
}else{
return moment().isoWeekday();
}
}
);
const styleClasses = mergeStyleSets({
menuIcon: {
fontSize: 18,
},
webPartTitle: {
marginBottom: 0,
},
stylContainerDetails: {
marginTop: 25,
display: "grid",
justifyContent: "stretch",
alignItems: "center",
gridTemplateColumns: "repeat( auto-fit, minmax(45px, 1fr) )",
gridTemplateRows: "auto",
},
separator: {
borderBottomStyle: "solid",
borderWidth: 1,
borderBottomColor: props.themeVariant.palette.themeLighter,
},
styleIcon: {
maxWidth: 44,
minWidth: 44,
minHeight: 30,
height: 30,
borderColor: props.themeVariant.palette.themePrimary,
borderRightWidth: 0,
borderRightStyle: "none",
borderLeftWidth: 1,
borderLeftStyle: "solid",
borderTopWidth: 1,
borderTopStyle: "solid",
borderBottomWidth: 1,
borderBottomStyle: "solid",
display: "flex",
alignItems: "center",
justifyContent: "center",
},
listContainer: {
maxWidth: "100%",
overflowY: "auto",
marginTop: 0,
padding: 25,
boxShadow: props.showBox
? "0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1)"
: "",
},
linkButtonStyle: {
minWidth: 45,
height: 32,
display: "flex",
alignItems: "center",
justifyContent: "center",
fontWeight: 600,
backgroundColor: props.themeVariant.palette.neutralLighter,
"&:not(:last-child)": {
marginRight: 5,
},
":hover": {
backgroundColor: props.themeVariant.palette.themePrimary,
color: props.themeVariant.palette.white,
cursor: "pointer",
},
},
linkButtonActiveStyle: {
backgroundColor: props.themeVariant.palette.themePrimary,
color: props.themeVariant.palette.white,
},
});
const _weekDescription = `${moment().isoWeekday(1).format("Do")} ${toUpper(
moment().isoWeekday(1).format("MMMM")
)} to ${moment().isoWeekday(5).format("Do")} ${toUpper(
moment().isoWeekday(5).format("MMMM")
)}`;
React.useEffect(() => {
(async () => {
setMonday(false);
setTuesday(false);
setWednesday(false);
setThursday(false);
setFriday(false);
setShowMenuForDay(undefined);
try {
let _currentDay = moment().isoWeekday();
console.log(_currentDay);
switch (_currentDay) {
case EWeekdays.Monday:
setShowMenuForDay(EWeekdays.Monday);
setMonday(true);
break;
case EWeekdays.Tuesday:
setShowMenuForDay(EWeekdays.Tuesday);
setTuesday(true);
break;
case EWeekdays.Wednesday:
setShowMenuForDay(EWeekdays.Wednesday);
setWednesday(true);
break;
case EWeekdays.Thursday:
setShowMenuForDay(EWeekdays.Thursday);
setThursday(true);
break;
case EWeekdays.Friday:
setShowMenuForDay(EWeekdays.Friday);
setFriday(true);
break;
case EWeekdays.Saturday:
setShowMenuForDay(EWeekdays.Friday);
setFriday(true);
break;
case EWeekdays.Sunday:
setShowMenuForDay(EWeekdays.Friday);
setFriday(true);
break;
}
} catch (error) {
console.log(error);
}
})();
}, [props.listId, props.site]);
if ( (!props.listId ||props.listId.length === 0) && props.site.length === 0) {
return (
<Placeholder
iconName="Edit"
iconText={strings.PlaceHolderIconTextLabel}
description={strings.PlaceholderDescription}
buttonLabel={strings.PlaceholderButtonLabel}
hideButton={props.displayMode === DisplayMode.Read}
onConfigure={() => {
props.propertyPanel.open();
}}
/>
);
}
return (
<>
<Customizer settings={{ theme: props.themeVariant }}>
<WebPartTitle
displayMode={props.displayMode}
title={props.title}
themeVariant={props.themeVariant}
updateProperty={props.updateProperty}
className={styleClasses.webPartTitle}
/>
<div className={styleClasses.listContainer}>
<Stack tokens={stackTokens}>
<Stack
horizontal
verticalAlign="center"
horizontalAlign="center"
tokens={{ childrenGap: 10 }}
styles={{
root: {
backgroundColor: props.themeVariant.palette.neutralLight,
width: "100%",
paddingRight: 10,
paddingLeft: 10,
minHeight: 32,
},
}}
>
<FontIcon
iconName="ContextMenu"
className={styleClasses.menuIcon}
></FontIcon>
<Text variant="mediumPlus" styles={{ root: { fontWeight: 600 } }}>
MENU
</Text>
</Stack>
<div className={styleClasses.separator}></div>
<Label
styles={{
root: {
fontSize: props.themeVariant.fonts.mediumPlus.fontSize,
color: props.themeVariant.palette.themePrimary,
textAlign: "center",
verticalAlign: "center",
fontWeight: 600,
marginBottom: 20,
},
}}
>
{_weekDescription}
</Label>
<div className={styleClasses.stylContainerDetails}>
<div
className={
monday
? `${styleClasses.linkButtonStyle} ${styleClasses.linkButtonActiveStyle} `
: styleClasses.linkButtonStyle
}
onClick={(ev) => {
ev.preventDefault();
setShowMenuForDay(EWeekdays.Monday);
setMonday(true);
setTuesday(false);
setWednesday(false);
setThursday(false);
setFriday(false);
}}
>
MON
</div>
<div
className={
tuesday
? `${styleClasses.linkButtonStyle} ${styleClasses.linkButtonActiveStyle} `
: styleClasses.linkButtonStyle
}
onClick={(ev) => {
ev.preventDefault();
setShowMenuForDay(EWeekdays.Tuesday);
setMonday(false);
setTuesday(true);
setWednesday(false);
setThursday(false);
setFriday(false);
}}
>
TUE
</div>
<div
className={
wednesday
? `${styleClasses.linkButtonStyle} ${styleClasses.linkButtonActiveStyle} `
: styleClasses.linkButtonStyle
}
onClick={(ev) => {
ev.preventDefault();
setShowMenuForDay(EWeekdays.Wednesday);
setMonday(false);
setTuesday(false);
setWednesday(true);
setThursday(false);
setFriday(false);
}}
>
WED
</div>
<div
className={
thursday
? `${styleClasses.linkButtonStyle} ${styleClasses.linkButtonActiveStyle} `
: styleClasses.linkButtonStyle
}
onClick={(ev) => {
ev.preventDefault();
setShowMenuForDay(EWeekdays.Thursday);
setMonday(false);
setTuesday(false);
setWednesday(false);
setThursday(true);
setFriday(false);
}}
>
THU
</div>
<div
className={
friday
? `${styleClasses.linkButtonStyle} ${styleClasses.linkButtonActiveStyle} `
: styleClasses.linkButtonStyle
}
onClick={(ev) => {
ev.preventDefault();
setShowMenuForDay(EWeekdays.Friday);
setMonday(false);
setTuesday(false);
setWednesday(false);
setThursday(false);
setFriday(true);
}}
>
FRI
</div>
</div>
<div style={{ paddingTop: 15 }}>
{props.listId && props.site[0].url && (
<MenuDetail dayOfWeek={showMenuForDay} {...props}></MenuDetail>
)}
</div>
</Stack>
</div>
</Customizer>
</>
);
};

View File

@ -0,0 +1,25 @@
define([], function() {
return {
PlaceholderButtonLabel: "Configure",
PlaceholderDescription: "Please configure the web part with information required",
PlaceHolderIconTextLabel: "Configure Restaurant Menu web part",
DateFieldPropertyLabel: "Date Field",
DateInformationMessage: " \"Date field is required to filter menu information\"",
SoupFieldPropertyLabel: "Soup field",
MeatFieldPropertyLabel: "Meat field",
FishFieldPropertyLabel: "Fish field",
DietFieldPropertyLabel: "Diet field",
VeganFieldPropertyLabel: "Vegan field",
DessertFieldPropertyLabel: "Dessert field",
NoInformationLabel: "No information found",
SoupLabel: " SOUP",
MeatLabel: " MEAT",
FishLabel: " FISH",
DietLabel: " DIET",
VeganLabel: " VEGAN",
DessertLabel: "DESSERT",
"PropertyPaneDescription": "Select list and mapping fields to each menu option, the date is required to query information",
"BasicGroupName": "Properties",
"DescriptionFieldLabel": "Description Field"
}
});

View File

@ -0,0 +1,28 @@
declare interface IRestaurantMenuWebPartStrings {
PlaceholderButtonLabel: string;
PlaceholderDescription: string;
PlaceHolderIconTextLabel: string;
DateFieldPropertyLabel: string;
DateInformationMessage: string;
SoupFieldPropertyLabel: string;
MeatFieldPropertyLabel: string;
FishFieldPropertyLabel: string;
DietFieldPropertyLabel: string;
VeganFieldPropertyLabel: string;
DessertFieldPropertyLabel: string;
NoInformationLabel: string;
SoupLabel: string;
MeatLabel: string;
FishLabel: string;
DietLabel: string;
VeganLabel: string;
DessertLabel: string;
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'RestaurantMenuWebPartStrings' {
const strings: IRestaurantMenuWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 383 B

View File

@ -0,0 +1,41 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.7/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"
],
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
],
"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-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
}