text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
import { Page } from '@playwright/test'
import * as po from './actions'
export class Account {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
getQuotaValue(): Promise<string> {
return po.getQuotaValue({ page: this.#page })
}
getUserInfo(key: string): Promise<string> {
return po.getUserInfo({ page: this.#page, key })
}
async openAccountPage(): Promise<void> {
await po.openAccountPage({ page: this.#page })
}
async requestGdprExport(): Promise<void> {
await po.requestGdprExport({ page: this.#page })
}
downloadGdprExport(): Promise<string> {
return po.downloadGdprExport({ page: this.#page })
}
changeLanguage(language, isAnonymousUser = false): Promise<string> {
return po.changeLanguage({ page: this.#page, language, isAnonymousUser })
}
getTitle(): Promise<string> {
return po.getTitle({ page: this.#page })
}
}
| owncloud/web/tests/e2e/support/objects/account/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/account/index.ts",
"repo_id": "owncloud",
"token_count": 307
} | 882 |
import { Page, expect } from '@playwright/test'
import util from 'util'
import { sidebar } from '../utils'
import { getActualExpiryDate } from '../../../utils/datePicker'
import { clickResource } from '../resource/actions'
import { shareRoles } from '../share/collaborator'
export interface createLinkArgs {
page: Page
role?: string
resource?: string
name?: string
space?: boolean
password?: string
}
export interface copyLinkArgs {
page: Page
resource: string
name?: string
via?: string
}
export type changeNameArgs = {
page: Page
resource?: string
newName: string
space?: boolean
}
export type addExpirationArgs = {
page: Page
resource: string
linkName: string
expireDate: string
}
export type addPasswordArgs = {
page: Page
resource: string
linkName: string
newPassword: string
}
export type changeRoleArgs = {
page: Page
resource?: string
linkName: string
role: string
space?: boolean
}
export type deleteLinkArgs = {
page: Page
resourceName: string
name: string
}
export type publicLinkAndItsEditButtonVisibilityArgs = {
page: Page
linkName: string
resource?: string
space?: boolean
}
const publicLinkSetRoleButton = `#files-role-%s`
const linkExpiryDatepicker = '.link-expiry-picker:not(.vc-container)'
const publicLinkEditRoleButton =
`//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]//ancestor::li//div[contains(@class, "link-details")]/` +
`div/button[contains(@class, "link-role-dropdown-toggle")]`
const addPublicLinkButton = '#files-file-link-add'
const publicLinkNameList =
'//div[@id="oc-files-file-link"]//ul//h4[contains(@class,"oc-files-file-link-name")]'
const publicLinkUrlList =
'//div[@id="oc-files-file-link"]//ul//p[contains(@class,"oc-files-file-link-url")]'
const publicLink = `//ul//h4[text()='%s']/following-sibling::div//p`
const publicLinkCurrentRole =
'//button[contains(@class,"link-role-dropdown-toggle")]//span[contains(@class,"link-current-role")]'
const linkUpdateDialog = '//div[contains(@class,"oc-notification-message-title")]'
const editPublicLinkButton =
`//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]` +
`//ancestor::li//div[contains(@class, "details-buttons")]//button[contains(@class, "edit-drop-trigger")]`
const editPublicLinkRenameButton =
'//div[contains(@id,"edit-public-link-dropdown")]//button/span[text()="Rename"]'
const editPublicLinkSetExpirationButton =
'//div[contains(@id,"edit-public-link-dropdown")]//button/span[text()="Set expiration date"]'
const editPublicLinkAddPasswordButton =
'//div[contains(@id,"edit-public-link-dropdown")]//button/span[text()="Edit password"]'
const editPublicLinkInput = '.oc-modal-body input.oc-text-input'
const editPublicLinkRenameConfirm = '.oc-modal-body-actions-confirm'
const deleteLinkButton =
`//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]` +
`//ancestor::li//div[contains(@class, "details-buttons")]//button/span[text()="Delete link"]`
const confirmDeleteButton = `//button[contains(@class,"oc-modal-body-actions-confirm") and text()="Delete"]`
const notificationContainer = 'div.oc-notification'
const publicLinkPasswordErrorMessage = `//div[contains(@class, "oc-text-input-message oc-text-input-danger")]/span`
const cancelButton = '.oc-modal-body-actions-cancel'
const showOrHidePasswordButton = '.oc-text-input-show-password-toggle'
const copyPasswordButton = '.oc-text-input-copy-password-button'
const generatePasswordButton = '.oc-text-input-generate-password-button'
const expectedRegexForGeneratedPassword = /^[A-Za-z0-9\s\S]{12}$/
const passwordInputDescription = '.oc-text-input-description .oc-text-input-description'
const getRecentLinkUrl = async (page: Page): Promise<string> => {
return await page.locator(publicLinkUrlList).first().textContent()
}
const getRecentLinkName = async (page: Page): Promise<string> => {
return await page.locator(publicLinkNameList).first().textContent()
}
export const createLink = async (args: createLinkArgs): Promise<string> => {
const { space, page, resource, password, role } = args
if (!space) {
const resourcePaths = resource.split('/')
const resourceName = resourcePaths.pop()
if (resourcePaths.length) {
await clickResource({ page: page, path: resourcePaths.join('/') })
}
await sidebar.open({ page: page, resource: resourceName })
await sidebar.openPanel({ page: page, name: 'sharing' })
}
await page.locator(addPublicLinkButton).click()
if (role) {
await page.locator(util.format(publicLinkSetRoleButton, shareRoles[role])).click()
}
role === 'Invited people'
? await expect(page.locator(passwordInputDescription).first()).toHaveText(
'Password cannot be set for internal links'
)
: await page.locator(editPublicLinkInput).fill(password)
await Promise.all([
page.waitForResponse(
(res) =>
res.url().includes('createLink') &&
res.request().method() === 'POST' &&
res.status() === 200
),
page.locator(editPublicLinkRenameConfirm).click()
])
await clearCurrentPopup(page)
return await getRecentLinkUrl(page)
}
export const changeRole = async (args: changeRoleArgs): Promise<string> => {
const { page, resource, linkName, role, space } = args
// clear all popups
await clearAllPopups(page)
let resourceName = null
let shareType = 'space-share'
if (!space) {
const resourcePaths = resource.split('/')
resourceName = resourcePaths.pop()
shareType = 'sharing'
if (resourcePaths.length) {
await clickResource({ page: page, path: resourcePaths.join('/') })
}
}
await sidebar.open({ page: page, resource: resourceName })
await sidebar.openPanel({ page: page, name: shareType })
await page.locator(util.format(publicLinkEditRoleButton, linkName)).click()
await Promise.all([
page.waitForResponse(
(res) =>
res.url().includes('permissions') &&
res.request().method() === 'PATCH' &&
res.status() === 200
),
page.locator(util.format(publicLinkSetRoleButton, shareRoles[role])).click()
])
const message = await page.locator(linkUpdateDialog).textContent()
expect(message.trim()).toBe('Link was updated successfully')
return await page.locator(publicLinkCurrentRole).textContent()
}
export const changeName = async (args: changeNameArgs): Promise<string> => {
const { page, resource, space, newName } = args
// clear all popups
await clearAllPopups(page)
if (!space) {
const resourcePaths = resource.split('/')
const resourceName = resourcePaths.pop()
if (resourcePaths.length) {
await clickResource({ page: page, path: resourcePaths.join('/') })
}
await sidebar.open({ page: page, resource: resourceName })
await sidebar.openPanel({ page: page, name: 'sharing' })
}
await page.locator(util.format(editPublicLinkButton, 'Link')).click()
await page.locator(editPublicLinkRenameButton).click()
await page.locator(editPublicLinkInput).fill(newName)
await page.locator(editPublicLinkRenameConfirm).click()
const message = await page.locator(linkUpdateDialog).textContent()
expect(message.trim()).toBe('Link was updated successfully')
return await getRecentLinkName(page)
}
export const fillPassword = async (args: addPasswordArgs): Promise<void> => {
const { page, resource, linkName, newPassword } = args
// clear all popups
await clearAllPopups(page)
const resourcePaths = resource.split('/')
const resourceName = resourcePaths.pop()
if (resourcePaths.length) {
await clickResource({ page: page, path: resourcePaths.join('/') })
}
await sidebar.open({ page: page, resource: resourceName })
await sidebar.openPanel({ page: page, name: 'sharing' })
await page.locator(util.format(editPublicLinkButton, linkName)).click()
await page.locator(editPublicLinkAddPasswordButton).click()
await page.locator(editPublicLinkInput).fill(newPassword)
await page.locator(editPublicLinkRenameConfirm).click()
}
export const addPassword = async (args: addPasswordArgs): Promise<void> => {
const { page } = args
await fillPassword(args)
const message = await page.locator(linkUpdateDialog).textContent()
expect(message.trim()).toBe('Link was updated successfully')
}
export const showOrHidePassword = async (args): Promise<void> => {
const { page, showOrHide } = args
await page.locator(showOrHidePasswordButton).click()
showOrHide === 'reveals'
? await expect(page.locator(editPublicLinkInput)).toHaveAttribute('type', 'text')
: await expect(page.locator(editPublicLinkInput)).toHaveAttribute('type', 'password')
}
export const copyEnteredPassword = async (page: Page): Promise<void> => {
const enteredPassword = await page.locator(editPublicLinkInput).inputValue()
await page.locator(copyPasswordButton).click()
const copiedPassword = await page.evaluate('navigator.clipboard.readText()')
expect(enteredPassword).toBe(copiedPassword)
}
export const generatePassword = async (page: Page): Promise<void> => {
await page.locator(generatePasswordButton).click()
const generatedPassword = await page.locator(editPublicLinkInput).inputValue()
expect(generatedPassword).toMatch(expectedRegexForGeneratedPassword)
}
export const setPassword = async (page: Page): Promise<void> => {
await Promise.all([
page.waitForResponse(
(res) =>
res.url().includes('permissions') &&
res.request().method() === 'POST' &&
res.status() === 200
),
page.locator(editPublicLinkRenameConfirm).click()
])
}
export const addExpiration = async (args: addExpirationArgs): Promise<void> => {
const { page, resource, linkName, expireDate } = args
const resourcePaths = resource.split('/')
const resourceName = resourcePaths.pop()
if (resourcePaths.length) {
await clickResource({ page: page, path: resourcePaths.join('/') })
}
await sidebar.open({ page: page, resource: resourceName })
await sidebar.openPanel({ page: page, name: 'sharing' })
await page.locator(util.format(editPublicLinkButton, linkName)).click()
await page.locator(editPublicLinkSetExpirationButton).click()
const newExpiryDate = getActualExpiryDate(
expireDate.toLowerCase().match(/[dayrmonthwek]+/)[0] as any,
expireDate
)
await page.locator(linkExpiryDatepicker).evaluate(
(datePicker: any, { newExpiryDate }): any => {
datePicker?.__vueParentComponent?.refs?.calendar.move(newExpiryDate)
},
{ newExpiryDate }
)
}
export const deleteLink = async (args: deleteLinkArgs): Promise<void> => {
const { page, resourceName, name } = args
// clear all popups
await clearAllPopups(page)
await sidebar.open({ page: page, resource: resourceName })
await sidebar.openPanel({ page: page, name: 'sharing' })
await page.locator(util.format(editPublicLinkButton, name)).click()
await page.locator(util.format(deleteLinkButton, name)).click()
await page.locator(confirmDeleteButton).click()
const message = await page.locator(linkUpdateDialog).textContent()
expect(message.trim()).toBe('Link was deleted successfully')
}
export const getPublicLinkVisibility = async (
args: publicLinkAndItsEditButtonVisibilityArgs
): Promise<string> => {
const { page, linkName, resource, space } = args
let shareType = 'space-share'
let resourceName = null
if (!space) {
shareType = 'sharing'
const resourcePaths = resource.split('/')
resourceName = resourcePaths.pop()
if (resourcePaths.length) {
await clickResource({ page: page, path: resourcePaths.join('/') })
}
}
await sidebar.open({ page: page, resource: resourceName })
await sidebar.openPanel({ page: page, name: shareType })
return await page.locator(util.format(publicLink, linkName)).textContent()
}
export const getLinkEditButtonVisibility = async (
args: publicLinkAndItsEditButtonVisibilityArgs
): Promise<boolean> => {
const { page, linkName } = args
return await page.locator(util.format(editPublicLinkButton, linkName)).isVisible()
}
export const clearAllPopups = async (page: Page): Promise<void> => {
const count = await page.locator(notificationContainer).evaluate((container) => {
Object.values(container.children).forEach((child) => {
container.removeChild(child)
})
return container.children.length
})
if (count) {
throw new Error(`Failed to clear ${count} notifications`)
}
await expect(page.locator(linkUpdateDialog)).not.toBeVisible()
}
export const clearCurrentPopup = async (page: Page): Promise<void> => {
await expect(page.locator(linkUpdateDialog)).toBeVisible()
await clearAllPopups(page)
}
export const getPublicLinkPasswordErrorMessage = async (page: Page): Promise<string> => {
return await page.locator(publicLinkPasswordErrorMessage).innerText()
}
export const clickOnCancelButton = async (page: Page): Promise<void> => {
await page.locator(cancelButton).click()
}
| owncloud/web/tests/e2e/support/objects/app-files/link/actions.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/link/actions.ts",
"repo_id": "owncloud",
"token_count": 4211
} | 883 |
import { Page } from '@playwright/test'
import * as po from './actions'
import { resourceIsNotOpenable, isAcceptedSharePresent, resourceIsSynced } from './utils'
import { createLinkArgs } from '../link/actions'
import { ICollaborator, IAccessDetails } from './collaborator'
export class Share {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
async create(args: Omit<po.createShareArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.createShare({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async enableSync(args: Omit<po.ShareStatusArgs, 'page'>): Promise<void> {
await po.enableSync({ ...args, page: this.#page })
}
async disableSync(args: Omit<po.ShareStatusArgs, 'page'>): Promise<void> {
await po.disableSync({ ...args, page: this.#page })
}
async syncAll(): Promise<void> {
await po.syncAllShares({ page: this.#page })
}
async changeShareeRole(args: Omit<po.ShareArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.changeShareeRole({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async removeSharee(args: Omit<po.removeShareeArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.removeSharee({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async checkSharee(args: Omit<po.ShareArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.checkSharee({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async isAcceptedSharePresent(resource: string, owner: string): Promise<boolean> {
await this.#page.reload()
return await isAcceptedSharePresent({ page: this.#page, resource, owner })
}
async hasPermissionToShare(resource: string): Promise<boolean> {
return await po.hasPermissionToShare({ page: this.#page, resource })
}
async createQuickLink(args: Omit<createLinkArgs, 'page'>): Promise<void> {
await po.createQuickLink({ ...args, page: this.#page })
}
async resourceIsNotOpenable(resource): Promise<boolean> {
return await resourceIsNotOpenable({ page: this.#page, resource })
}
async resourceIsSynced(resource): Promise<boolean> {
return await resourceIsSynced({ page: this.#page, resource })
}
async setDenyShare(args: Omit<po.setDenyShareArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.setDenyShare({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async addExpirationDate({
resource,
collaborator,
expirationDate
}: {
resource: string
collaborator: Omit<ICollaborator, 'role'>
expirationDate: string
}): Promise<void> {
const startUrl = this.#page.url()
await po.addExpirationDate({ resource, collaborator, expirationDate, page: this.#page })
await this.#page.goto(startUrl)
}
async getAccessDetails({
resource,
collaborator
}: {
resource: string
collaborator: Omit<ICollaborator, 'role'>
}): Promise<IAccessDetails> {
const startUrl = this.#page.url()
const accessDetails = await po.getAccessDetails({ resource, collaborator, page: this.#page })
await this.#page.goto(startUrl)
return accessDetails
}
}
| owncloud/web/tests/e2e/support/objects/app-files/share/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/share/index.ts",
"repo_id": "owncloud",
"token_count": 1124
} | 884 |
import { Actor } from '../types'
export const actorStore = new Map<string, Actor>()
| owncloud/web/tests/e2e/support/store/actor.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/store/actor.ts",
"repo_id": "owncloud",
"token_count": 25
} | 885 |
export default function (string) {
return string.replace(/(?![A-Z])([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase()
}
| owncloud/web/tests/helpers/toKebabCase.js/0 | {
"file_path": "owncloud/web/tests/helpers/toKebabCase.js",
"repo_id": "owncloud",
"token_count": 60
} | 886 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
include_once 'header.php';
include_once 'inc/config.inc.php';
$dbhost=DBHOST;
$dbuser=DBUSER;
$dbpw=DBPW;
$dbname=DBNAME;
$mes_connect='';
$mes_create='';
$mes_data='';
$mes_ok='';
if(isset($_POST['submit'])){
//判断数据库连接
if(!@mysqli_connect($dbhost, $dbuser, $dbpw)){
exit('数据连接失败,请仔细检查inc/config.inc.php的配置');
}
$link=mysqli_connect(DBHOST, DBUSER, DBPW);
$mes_connect.="<p class='notice'>数据库连接成功!</p>";
//如果存在,则直接干掉
$drop_db="drop database if exists $dbname";
if(!@mysqli_query($link, $drop_db)){
exit('初始化数据库失败,请仔细检查当前用户是否有操作权限');
}
//创建数据库
$create_db="CREATE DATABASE $dbname";
if(!@mysqli_query($link,$create_db)){
exit('数据库创建失败,请仔细检查当前用户是否有操作权限');
}
$mes_create="<p class='notice'>新建数据库:".$dbname."成功!</p>";
//创建数据.选择数据库
if(!@mysqli_select_db($link, $dbname)){
exit('数据库选择失败,请仔细检查当前用户是否有操作权限');
}
//创建users表
$creat_users=
"CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`password` varchar(66) NOT NULL,
`level` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4";
if(!@mysqli_query($link,$creat_users)){
exit('创建users表失败,请仔细检查当前用户是否有操作权限');
}
//往users表里面插入默认的数据
$insert_users = "insert into `users` (`id`,`username`,`password`,`level`) values (1,'admin',md5('123456'),1),(2,'pikachu',md5('000000'),2),(3,'test',md5('abc123'),3)";
if(!@mysqli_query($link,$insert_users)){
echo $link->error;
exit('创建users表数据失败,请仔细检查当前用户是否有操作权限');
}
//创建留言板的表message
$create_message=
"CREATE TABLE IF NOT EXISTS `message` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`content` varchar(255) NOT NULL,
`time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='stored_xss_1' AUTO_INCREMENT=56";
if(!@mysqli_query($link,$create_message)){
exit('创建message表失败,请仔细检查当前用户是否有操作权限');
}
//创建xssblind的看法收集表
$create_xssblind=
"CREATE TABLE IF NOT EXISTS `xssblind` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`time` datetime NOT NULL,
`content` text NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7";
if(!@mysqli_query($link,$create_xssblind)){
exit('创建xssblind表失败,请仔细检查当前用户是否有操作权限');
}
//创建会员信息的表member
$create_member=
"CREATE TABLE IF NOT EXISTS `member` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(66) NOT NULL,
`pw` varchar(128) NOT NULL,
`sex` char(10) NOT NULL,
`phonenum` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=25";
if(!@mysqli_query($link,$create_member)){
exit('创建member表失败,请仔细检查当前用户是否有操作权限');
}
$insert_member=
"INSERT INTO `member` (`id`, `username`, `pw`, `sex`, `phonenum`, `address`, `email`) VALUES
(1, 'vince', md5('123456'), 'boy', '18626545453', 'chain', 'vince@pikachu.com'),
(2, 'allen', md5('123456'), 'boy', '13676767767', 'nba 76', 'allen@pikachu.com'),
(3, 'kobe', md5('123456'), 'boy', '15988767673', 'nba lakes', 'kobe@pikachu.com'),
(4, 'grady', md5('123456'), 'boy', '13676765545', 'nba hs', 'grady@pikachu.com'),
(5, 'kevin', md5('123456'), 'boy', '13677676754', 'Oklahoma City Thunder', 'kevin@pikachu.com'),
(6, 'lucy', md5('123456'), 'girl', '12345678922', 'usa', 'lucy@pikachu.com'),
(7, 'lili', md5('123456'), 'girl', '18656565545', 'usa', 'lili@pikachu.com')";
if(!@mysqli_query($link,$insert_member)){
exit('创建member数据失败,请仔细检查当前用户是否有操作权限');
}
//创建数据.创建表sqli里面http头注入的信息,httpinfo和数据
$creat_httpinfo=
"CREATE TABLE IF NOT EXISTS `httpinfo` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`userid` int(10) unsigned NOT NULL,
`ipaddress` varchar(255) NOT NULL,
`useragent` varchar(255) NOT NULL,
`httpaccept` varchar(255) NOT NULL,
`remoteport` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=42";
if(!@mysqli_query($link,$creat_httpinfo)){
exit('创建httpinfo表失败,请仔细检查当前用户是否有操作权限');
}
$mes_data="<p class='notice'>创建数据库数据成功!</p>";
$mes_ok="<p class='notice'>好了,可以开搞了~<a href='index.php'>点击这里</a>进入首页</p>";
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<!-- <li>-->
<!-- <i class="ace-icon fa fa-home home-icon"></i>-->
<!-- <a href="#">Home</a>-->
<!-- </li>-->
<li class="active">系统初始化安装</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<div id=install_main>
<p class="main_title">Setup guide:</p>
<p class="main_title">第0步:请提前安装“mysql+php+中间件”的环境;</p>
<p class="main_title">第1步:请根据实际环境修改inc/config.inc.php文件里面的参数;</p>
<p class="main_title">第2步:点击“安装/初始化”按钮;</p>
<form method="post">
<input type="submit" name="submit" value="安装/初始化"/>
</form>
</div>
<div class="info" style="color: #D6487E;padding-top: 40px;">
<?php
echo $mes_connect;
echo $mes_create;
echo $mes_data;
echo $mes_ok;
?>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content --> | zhuifengshaonianhanlu/pikachu/install.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/install.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 3551
} | 887 |
<?php
include_once "inc/mysql.inc.php";
include_once "inc/config.inc.php";
$link=connect();
// 判断是否登录,没有登录不能访问
if(!check_login($link)){
header("location:index.php");
}
if(isset($_GET['logout']) && $_GET['logout'] == 1){
session_unset();
session_destroy();
setcookie(session_name(),'',time()-3600,'/');
header("location:index.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pikachu Xss 后台</title>
<link rel="stylesheet" type="text/css" href="pkxss.css"/>
</head>
<body>
<div id="title">
<h1>pikachu Xss 后台</h1>
<div id="xsstest_main">
<h2 class="left_title">测试模块 |<a href="xssmanager.php?logout=1">退出登陆</a></h2>
<ul class="left_list">
<li><a href="xcookie/pkxss_cookie_result.php">cookie搜集</a></li>
<li><a href="xfish/pkxss_fish_result.php">钓鱼结果</a></li>
<li><a href="rkeypress/pkxss_keypress_result.php">键盘记录</a></li>
</ul>
</div>
</body>
</html> | zhuifengshaonianhanlu/pikachu/pkxss/xssmanager.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/pkxss/xssmanager.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 610
} | 888 |
<?php
$html.=<<<A
<img class=player src="include/ray.png" />
<p class=nabname>
Ray Allen (Ray Allen), was born on July 20, 1975 in California, the beauty of xi, American professional basketball player, the secretary shooting guard, has excellent 3-point shooting ability.
</p>
A;
?> | zhuifengshaonianhanlu/pikachu/vul/fileinclude/include/file5.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/fileinclude/include/file5.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 85
} | 889 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "rce.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.php';
include_once $PIKA_ROOT_DIR . "inc/config.inc.php";
include_once $PIKA_ROOT_DIR . "inc/function.php";
include_once $PIKA_ROOT_DIR . "inc/mysql.inc.php";
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="rce.php">rce</a>
</li>
<li class="active">概述</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<div id="vul_info">
<dl>
<dt class="vul_title">RCE(remote command/code execute)概述</dt>
<dd class="vul_detail">
RCE漏洞,可以让攻击者直接向后台服务器远程注入操作系统命令或者代码,从而控制后台系统。
</dd>
<dd class="vul_detail">
<b>远程系统命令执行</b><br/>
一般出现这种漏洞,是因为应用系统从设计上需要给用户提供指定的远程命令操作的接口<br />
比如我们常见的路由器、防火墙、入侵检测等设备的web管理界面上<br />
一般会给用户提供一个ping操作的web界面,用户从web界面输入目标IP,提交后,后台会对该IP地址进行一次ping测试,并返回测试结果。
而,如果,设计者在完成该功能时,没有做严格的安全控制,则可能会导致攻击者通过该接口提交“意想不到”的命令,从而让后台进行执行,从而控制整个后台服务器
<br />
<br />
现在很多的甲方企业都开始实施自动化运维,大量的系统操作会通过"自动化运维平台"进行操作。
在这种平台上往往会出现远程系统命令执行的漏洞,不信的话现在就可以找你们运维部的系统测试一下,会有意想不到的"收获"-_-
</dd>
<dd class="vul_detail">
<br />
<b>远程代码执行</b><br/>
同样的道理,因为需求设计,后台有时候也会把用户的输入作为代码的一部分进行执行,也就造成了远程代码执行漏洞。
不管是使用了代码执行的函数,还是使用了不安全的反序列化等等。
</dd>
<dd class="vul_detail">
因此,如果需要给前端用户提供操作类的API接口,一定需要对接口输入的内容进行严格的判断,比如实施严格的白名单策略会是一个比较好的方法。
</dd>
<dd class="vul_detail_1">
你可以通过“RCE”对应的测试栏目,来进一步的了解该漏洞。
</dd>
</dl>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/rce/rce.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/rce/rce.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2613
} | 890 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "sqli_widebyte.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','','','','','','','','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.php';
include_once $PIKA_ROOT_DIR . "inc/config.inc.php";
include_once $PIKA_ROOT_DIR . "inc/function.php";
include_once $PIKA_ROOT_DIR . "inc/mysql.inc.php";
$link=connect();
$html='';
if(isset($_POST['submit']) && $_POST['name']!=null){
$name = escape($link,$_POST['name']);
$query="select id,email from member where username='$name'";//这里的变量是字符型,需要考虑闭合
//设置mysql客户端来源编码是gbk,这个设置导致出现宽字节注入问题
$set = "set character_set_client=gbk";
execute($link,$set);
//mysqi_query不打印错误描述
$result=mysqli_query($link, $query);
if(mysqli_num_rows($result) >= 1){
while ($data=mysqli_fetch_assoc($result)){
$id=$data['id'];
$email=$data['email'];
$html.="<p class='notice'>your uid:{$id} <br />your email is: {$email}</p>";
}
}else{
$html.="<p class='notice'>您输入的username不存在,请重新输入!</p>";
}
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="../sqli.php">sqli</a>
</li>
<li class="active">wide byte注入</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="kobe/123456,先搜索下什么是宽字节注入搞懂了在来测试吧">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="sqli_main">
<p class="sqli_title">what's your username?</p>
<form method="post">
<input class="sqli_in" type="text" name="name" />
<input class="sqli_submit" type="submit" name="submit" value="查询" />
</form>
<?php echo $html;?>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_widebyte.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_widebyte.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1546
} | 891 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "xss_01.php"){
$ACTIVE = array('','','','','','','','active open','','','','','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR.'header.php';
$html = '';
if(isset($_GET['submit']) && $_GET['message'] != null){
//这里会使用正则对<script进行替换为空,也就是过滤掉
$message=preg_replace('/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/', '', $_GET['message']);
// $message=str_ireplace('<script>',$_GET['message']);
if($message == 'yes'){
$html.="<p>那就去人民广场一个人坐一会儿吧!</p>";
}else{
$html.="<p>别说这些'{$message}'的话,不要怕,就是干!</p>";
}
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="xss.php">xss</a>
</li>
<li class="active">xss之过滤</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="有些内容被过滤了,试试看怎么绕过?">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="xssr_main">
<p class="xssr_title">阁下,请问你觉得人生苦短吗?</p>
<form method="get">
<input class="xssr_in" type="text" name="message" />
<input class="xssr_submit" type="submit" name="submit" value="submit" />
</form>
<?php echo $html;?>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR.'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/xss/xss_01.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/xss/xss_01.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1325
} | 892 |
# 8th Wall Web Examples
Example 8th Wall Web projects, by 3D framework
## A-Frame
* [Tap to place](https://github.com/8thwall/web/tree/master/examples/aframe/placeground) - This interactive example allows the user to grow trees on the ground by tapping. This showcases raycasting, instantiating objects, importing 3D models and the animation system.
* [Toss an object](https://github.com/8thwall/web/tree/master/examples/aframe/tossobject) - This interactive example lets the user tap the screen to toss tomatoes. When they hit the ground, they splat and make a sound. This introduces physics, collision events and playing sounds.
* [Portal](https://github.com/8thwall/web/tree/master/examples/aframe/portal) - This example shows off the popular portal illusion in web AR using three.js materials and the camera position as an event trigger.
* [Manipulate](https://github.com/8thwall/web/tree/master/examples/aframe/manipulate) - This example shows how to use touch gestures to manipulate a 3D object.
* [Capture a photo](https://github.com/8thwall/web/tree/master/examples/aframe/capturephoto) - This example allows the user to capture photo evidence of a UFO abduction.
* [Change animations](https://github.com/8thwall/web/tree/master/examples/aframe/animation-mixer) - This interactive example allows the user to position, scale, rotate, and change between animations embedded in a 3D model. This showcases raycasting, gesture inputs and using A-Frame's animation-mixer.
Tap to place | Toss Object | Portal
:----------: | :---------: | :----:
 |  | 
[Try Demo (mobile)](https://templates.8thwall.app/placeground-aframe) | [Try Demo (mobile)](https://templates.8thwall.app/tossobject-aframe) | [Try Demo (mobile)](https://templates.8thwall.app/portal-aframe)
or scan on phone:<br>  | or scan on phone:<br>  | or scan on phone:<br> 
Manipulate | Capture a photo | Change animations
:--------: | :-------------: | :-------------:
 |  | 
[Try Demo (mobile)](https://templates.8thwall.app/manipulate-aframe) | [Try Demo (mobile)](https://templates.8thwall.app/capturephoto-aframe) | [Try Demo (mobile)](https://templates.8thwall.app/animation-mixer-aframe)
or scan on phone:<br>  | or scan on phone:<br>  | or scan on phone:<br> 
### Marker Based
* [Art gallery](https://github.com/8thwall/web/tree/master/examples/aframe/artgallery) - This example uses image targets to show information about paintings in AR. This showcases image target tracking, as well as loading dynamic content and using the xrextras-generate-image-targets component.
* [Flyer](https://github.com/8thwall/web/tree/master/examples/aframe/flyer) - This example uses image targets to display information about jellyfish on a flyer. It uses the xrextras-named-image-target component to connect an <a-entity> to an image target by name while the xrextras-play-video component enables video playback.
* [Alpha Video](https://github.com/8thwall/web/tree/master/examples/aframe/alpha-video) - This example uses an image target to trigger a video. An A-Frame component is used for background removal of an mp4 video file to give a "green screen" effect.
Art gallery | Flyer | Alpha Video
:---------: | :---: | :---------:
 |  | 
[Image targets for demo](./aframe/artgallery/gallery.jpg) | [Image targets for demo](./aframe/flyer/flyer.jpg) | [Imaget target for demo](./aframe/alpha-video/targets/outside.jpg)
[Try Demo (mobile)](https://templates.8thwall.app/artgallery-aframe) | [Try Demo (mobile)](https://templates.8thwall.app/flyer-aframe) | [Try Demo (mobile)](https://templates.8thwall.app/alpha-video-aframe)
or scan on phone:<br>  | or scan on phone:<br>  | or scan on phone:<br> 
## Babylon.js
* [Tap to place](https://github.com/8thwall/web/tree/master/examples/babylonjs/placeground) - This interactive example allows the user to grow trees on the ground by tapping. This showcases raycasting, instantiating objects, importing 3D models, and animation.
Tap to place
:----------:

[Try Demo (mobile)](https://templates.8thwall.app/placeground-babylonjs)
or scan on phone:<br> 
## three.js
* [Tap to place](https://github.com/8thwall/web/tree/master/examples/threejs/placeground) - This interactive example allows the user to grow trees on the ground by tapping. This showcases raycasting, instantiating objects, importing 3D models, and animation.
* [8i hologram](https://github.com/8thwall/web/tree/master/examples/threejs/8i-hologram) - This example illustrates how to integrate an 8i hologram (www.8i.com) into an 8th Wall Web experience.
* [Flyer](https://github.com/8thwall/web/tree/master/examples/threejs/flyer) - This example uses image targets to display information about jellyfish on a flyer.
Tap to place | 8i hologram | Flyer
:----------: | :---------: | :---:
 |  | 
[Try Demo (mobile)](https://templates.8thwall.app/placeground-threejs) | [Try Demo (mobile)](https://templates.8thwall.app/hologram-8i-threejs) | [Try Demo (mobile)](https://templates.8thwall.app/flyer-threejs)
or scan on phone:<br>  | or scan on phone:<br>  | or scan on phone:<br> 
| 8thwall/web/examples/README.md/0 | {
"file_path": "8thwall/web/examples/README.md",
"repo_id": "8thwall",
"token_count": 2041
} | 0 |
// import { render, screen } from '@testing-library/react';
// import App from './App';
// test('renders a-scene', () => {
// const result = render(<App />);
// const ascene = result.container.querySelector('#ascene');
// expect(ascene).toBeInTheDocument();
// });
| 8thwall/web/examples/aframe/reactapp/src/App.test.js/0 | {
"file_path": "8thwall/web/examples/aframe/reactapp/src/App.test.js",
"repo_id": "8thwall",
"token_count": 91
} | 1 |
# JSQRCode
This directory and all of its code were forked from [jsqrcode](https://github.com/LazarSoft/jsqrcode)
for the purpose of illustrating how to integrate 8th Wall Web's camera pipeline with existing
libraries for computer vision. Use of this software is subject its license (Apache 2.0) as listed
in [copying](COPYING).
# Library
JavaScript QRCode reader for HTML5 enabled browser.
2011 Lazar Laszlo http://lazarsoft.info
Try it online: http://webqr.com
This is a port of ZXing qrcode scanner, http://code.google.com/p/zxing.
Usage:
Include the scripts in the following order:
* <script type="text/javascript" src="grid.js"></script>
* <script type="text/javascript" src="version.js"></script>
* <script type="text/javascript" src="detector.js"></script>
* <script type="text/javascript" src="formatinf.js"></script>
* <script type="text/javascript" src="errorlevel.js"></script>
* <script type="text/javascript" src="bitmat.js"></script>
* <script type="text/javascript" src="datablock.js"></script>
* <script type="text/javascript" src="bmparser.js"></script>
* <script type="text/javascript" src="datamask.js"></script>
* <script type="text/javascript" src="rsdecoder.js"></script>
* <script type="text/javascript" src="gf256poly.js"></script>
* <script type="text/javascript" src="gf256.js"></script>
* <script type="text/javascript" src="decoder.js"></script>
* <script type="text/javascript" src="qrcode.js"></script>
* <script type="text/javascript" src="findpat.js"></script>
* <script type="text/javascript" src="alignpat.js"></script>
* <script type="text/javascript" src="databr.js"></script>
Set qrcode.callback to function "func(data)", where data will get the decoded information.
Decode image with: qrcode.decode(url or DataURL).
Decode from canvas with "qr-canvas" ID: qrcode.decode()
[new from 2014.01.09]
For webcam qrcode decoding (included in the test.html) you will need a browser with getUserMedia (WebRTC) capability.
| 8thwall/web/examples/camerapipeline/qrcode/jsqrcode/README.md/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/README.md",
"repo_id": "8thwall",
"token_count": 621
} | 2 |
/*
Ported to JavaScript by Lazar Laszlo 2011
lazarsoft@gmail.com, www.lazarsoft.info
*/
/*
*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function ReedSolomonDecoder(field)
{
this.field = field;
this.decode=function(received, twoS)
{
var poly = new GF256Poly(this.field, received);
var syndromeCoefficients = new Array(twoS);
for(var i=0;i<syndromeCoefficients.length;i++)syndromeCoefficients[i]=0;
var dataMatrix = false;//this.field.Equals(GF256.DATA_MATRIX_FIELD);
var noError = true;
for (var i = 0; i < twoS; i++)
{
// Thanks to sanfordsquires for this fix:
var evalu = poly.evaluateAt(this.field.exp(dataMatrix?i + 1:i));
syndromeCoefficients[syndromeCoefficients.length - 1 - i] = evalu;
if (evalu != 0)
{
noError = false;
}
}
if (noError)
{
return ;
}
var syndrome = new GF256Poly(this.field, syndromeCoefficients);
var sigmaOmega = this.runEuclideanAlgorithm(this.field.buildMonomial(twoS, 1), syndrome, twoS);
var sigma = sigmaOmega[0];
var omega = sigmaOmega[1];
var errorLocations = this.findErrorLocations(sigma);
var errorMagnitudes = this.findErrorMagnitudes(omega, errorLocations, dataMatrix);
for (var i = 0; i < errorLocations.length; i++)
{
var position = received.length - 1 - this.field.log(errorLocations[i]);
if (position < 0)
{
throw "ReedSolomonException Bad error location";
}
received[position] = GF256.addOrSubtract(received[position], errorMagnitudes[i]);
}
}
this.runEuclideanAlgorithm=function( a, b, R)
{
// Assume a's degree is >= b's
if (a.Degree < b.Degree)
{
var temp = a;
a = b;
b = temp;
}
var rLast = a;
var r = b;
var sLast = this.field.One;
var s = this.field.Zero;
var tLast = this.field.Zero;
var t = this.field.One;
// Run Euclidean algorithm until r's degree is less than R/2
while (r.Degree >= Math.floor(R / 2))
{
var rLastLast = rLast;
var sLastLast = sLast;
var tLastLast = tLast;
rLast = r;
sLast = s;
tLast = t;
// Divide rLastLast by rLast, with quotient in q and remainder in r
if (rLast.Zero)
{
// Oops, Euclidean algorithm already terminated?
throw "r_{i-1} was zero";
}
r = rLastLast;
var q = this.field.Zero;
var denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree);
var dltInverse = this.field.inverse(denominatorLeadingTerm);
while (r.Degree >= rLast.Degree && !r.Zero)
{
var degreeDiff = r.Degree - rLast.Degree;
var scale = this.field.multiply(r.getCoefficient(r.Degree), dltInverse);
q = q.addOrSubtract(this.field.buildMonomial(degreeDiff, scale));
r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
//r.EXE();
}
s = q.multiply1(sLast).addOrSubtract(sLastLast);
t = q.multiply1(tLast).addOrSubtract(tLastLast);
}
var sigmaTildeAtZero = t.getCoefficient(0);
if (sigmaTildeAtZero == 0)
{
throw "ReedSolomonException sigmaTilde(0) was zero";
}
var inverse = this.field.inverse(sigmaTildeAtZero);
var sigma = t.multiply2(inverse);
var omega = r.multiply2(inverse);
return new Array(sigma, omega);
}
this.findErrorLocations=function( errorLocator)
{
// This is a direct application of Chien's search
var numErrors = errorLocator.Degree;
if (numErrors == 1)
{
// shortcut
return new Array(errorLocator.getCoefficient(1));
}
var result = new Array(numErrors);
var e = 0;
for (var i = 1; i < 256 && e < numErrors; i++)
{
if (errorLocator.evaluateAt(i) == 0)
{
result[e] = this.field.inverse(i);
e++;
}
}
if (e != numErrors)
{
throw "Error locator degree does not match number of roots";
}
return result;
}
this.findErrorMagnitudes=function( errorEvaluator, errorLocations, dataMatrix)
{
// This is directly applying Forney's Formula
var s = errorLocations.length;
var result = new Array(s);
for (var i = 0; i < s; i++)
{
var xiInverse = this.field.inverse(errorLocations[i]);
var denominator = 1;
for (var j = 0; j < s; j++)
{
if (i != j)
{
denominator = this.field.multiply(denominator, GF256.addOrSubtract(1, this.field.multiply(errorLocations[j], xiInverse)));
}
}
result[i] = this.field.multiply(errorEvaluator.evaluateAt(xiInverse), this.field.inverse(denominator));
// Thanks to sanfordsquires for this fix:
if (dataMatrix)
{
result[i] = this.field.multiply(result[i], xiInverse);
}
}
return result;
}
} | 8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/rsdecoder.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/rsdecoder.js",
"repo_id": "8thwall",
"token_count": 2243
} | 3 |
// Manages the position of the image target.
AFRAME.registerComponent('image-target', {
init: function () {
const {object3D, sceneEl} = this.el
object3D.visible = false
// Sets the position of the frame to match the image target.
const showImage = ({detail}) => {
object3D.position.copy(detail.position)
object3D.quaternion.copy(detail.rotation)
object3D.scale.set(detail.scale, detail.scale, detail.scale)
object3D.visible = true
}
// Update the position of the frame when the image target is found or updated.
sceneEl.addEventListener('xrimagefound', showImage)
sceneEl.addEventListener('xrimageupdated', showImage)
// Hide the image target when tracking is lost.
sceneEl.addEventListener('xrimagelost', () => {object3D.visible = false})
}
})
// Displays the name of the image target as it was set in the 8th Wall console.
AFRAME.registerComponent('targetname', {
init: function () {
const el = this.el
el.sceneEl.addEventListener('xrimagefound', ({detail}) => {
el.setAttribute(
'value', detail.name.length > 20 ? `${detail.name.substring(0, 17)}...` : detail.name)
})
}
})
| 8thwall/web/gettingstarted/aframe-imagetarget/index.js/0 | {
"file_path": "8thwall/web/gettingstarted/aframe-imagetarget/index.js",
"repo_id": "8thwall",
"token_count": 411
} | 4 |
/* eslint-disable no-undef */
// Copyright (c) 2022 8th Wall, Inc.
const imageFramePipelineModule = () => {
const LIGHT_PURPLE = 0xAD50FF
const CHERRY = 0xDD0065
const MINT = 0x00EDAF
const MANGO = 0xFFC828
const GRAY = 0x8083A2
const DARK_GRAY = 0x464766
const allFrames = {}
let scene
// Renders one side of a picture frame rectangle.
const frameEdge = (x, y, w1, h1, w2, h2) => {
const edge = new THREE.Group()
const big = new THREE.Mesh(new THREE.CubeGeometry(w1, h1, 0.008),
new THREE.MeshBasicMaterial({color: DARK_GRAY}))
big.position.set(x, y, 0)
const small = new THREE.Mesh(new THREE.CubeGeometry(w2, h2, 0.012),
new THREE.MeshBasicMaterial({color: GRAY}))
small.position.set(x, y, 0)
edge.add(big)
edge.add(small)
return edge
}
// Renders a picture frame rectangle.
const frameBorder = (scaledWidth, scaledHeight) => {
const border = new THREE.Group()
border.add(frameEdge(-scaledWidth / 2, 0, 0.05, scaledHeight + 0.05, 0.03, scaledHeight + 0.03))
border.add(frameEdge(scaledWidth / 2, 0, 0.05, scaledHeight + 0.05, 0.03, scaledHeight + 0.03))
border.add(frameEdge(0, -scaledHeight / 2, scaledWidth + 0.05, 0.05, scaledWidth + 0.03, 0.03))
border.add(frameEdge(0, scaledHeight / 2, scaledWidth + 0.05, 0.05, scaledWidth + 0.03, 0.03))
return border
}
// Adds a tinted-glass effect.
const framePane = (scaledWidth, scaledHeight) => {
const material = new THREE.MeshBasicMaterial({color: LIGHT_PURPLE})
material.alphaMap = new THREE.DataTexture(new Uint8Array([0, 127, 0]), 1, 1, THREE.RGBFormat)
material.alphaMap.needsUpdate = true
material.transparent = true
return new THREE.Mesh(new THREE.CubeGeometry(scaledWidth, scaledHeight, 0.001), material)
}
// Adds an oriented axis.
const axis = () => {
const axes = new THREE.Group()
const axisLength = 0.2
const cylinder = new THREE.CylinderBufferGeometry(0.01, 0.01, axisLength, 32)
const xAxis = new THREE.Mesh(cylinder, new THREE.MeshBasicMaterial({color: MANGO}))
const yAxis = new THREE.Mesh(cylinder, new THREE.MeshBasicMaterial({color: CHERRY}))
const zAxis = new THREE.Mesh(cylinder, new THREE.MeshBasicMaterial({color: MINT}))
xAxis.rotateZ(Math.PI / 2)
xAxis.position.set(axisLength / 2, 0, 0)
yAxis.position.set(0, axisLength / 2, 0)
zAxis.rotateX(Math.PI / 2)
zAxis.position.set(0, 0, axisLength / 2)
axes.add(xAxis)
axes.add(yAxis)
axes.add(zAxis)
return axes
}
// Constructs a picture frame out of threejs primitives.
const buildPrimitiveFrame = ({scaledWidth, scaledHeight}) => {
const frame = new THREE.Group()
frame.add(frameBorder(scaledWidth, scaledHeight))
frame.add(framePane(scaledWidth, scaledHeight))
frame.add(axis())
scene.add(frame)
return frame
}
// Updates the position of a picture frame that covers an image target.
const showImageFrame = ({detail}) => {
let frame = allFrames[detail.name]
if (!frame) {
frame = buildPrimitiveFrame(detail)
allFrames[detail.name] = frame
}
frame.position.copy(detail.position)
frame.quaternion.copy(detail.rotation)
frame.scale.set(detail.scale, detail.scale, detail.scale)
frame.visible = true
}
// Hides the image frame when the target is no longer detected.
const hideImageFrame = ({detail}) => {
allFrames[detail.name].visible = false
}
// Grab a handle to the threejs scene and set the camera position on pipeline startup.
const onStart = ({canvasWidth, canvasHeight}) => {
// Get the 3js sceen from xr3js.
const {camera} = XR8.Threejs.xrScene()
scene = XR8.Threejs.xrScene().scene
// Set the initial camera position relative to the scene we just laid out. This must be at a
// height greater than y=0.
camera.position.set(0, 3, 0)
// Sync the xr controller's 6DoF position and camera paremeters with our scene.
XR8.XrController.updateCameraProjectionMatrix({
origin: camera.position,
facing: camera.quaternion,
})
}
return {
// Camera pipeline modules need a name. It can be whatever you want but must be unique within
// your app.
name: 'targetframes',
// onStart is called once when the camera feed begins. In this case, we need to wait for the
// XR8.Threejs scene to be ready before we can access it to add content. It was created in
// XR8.Threejs.pipelineModule()'s onStart method.
onStart,
// Listeners are called right after the processing stage that fired them. This guarantees that
// updates can be applied at an appropriate synchronized point in the rendering cycle.
listeners: [
{event: 'reality.imagefound', process: showImageFrame},
{event: 'reality.imageupdated', process: showImageFrame},
{event: 'reality.imagelost', process: hideImageFrame},
],
}
}
const onxrloaded = () => {
// If your app only interacts with image targets and not the world, disabling world tracking can
// improve speed.
XR8.XrController.configure({disableWorldTracking: true})
XR8.addCameraPipelineModules([ // Add camera pipeline modules.
// Existing pipeline modules.
XR8.GlTextureRenderer.pipelineModule(), // Draws the camera feed.
XR8.Threejs.pipelineModule(), // Creates a ThreeJS AR Scene.
XR8.XrController.pipelineModule(), // Enables SLAM tracking.
window.LandingPage.pipelineModule(), // Detects unsupported browsers and gives hints.
XRExtras.FullWindowCanvas.pipelineModule(), // Modifies the canvas to fill the window.
XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup.
XRExtras.RuntimeError.pipelineModule(), // Shows an error image on runtime error.
// Custom pipeline modules.
imageFramePipelineModule(), // Draws a frame around detected image targets.
])
// Open the camera and start running the camera run loop.
XR8.run({canvas: document.getElementById('camerafeed')})
}
// Show loading screen before the full XR library has been loaded.
window.onload = () => { XRExtras.Loading.showLoading({onxrloaded}) }
| 8thwall/web/gettingstarted/threejs-imagetarget/index.js/0 | {
"file_path": "8thwall/web/gettingstarted/threejs-imagetarget/index.js",
"repo_id": "8thwall",
"token_count": 2220
} | 5 |
<!doctype html>
<html>
<head>
<title>XRExtras: Camera Pipeline</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="dist/xrextras.js"></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="https://apps.8thwall.com/xrweb?appKey=XXXXXXXX"></script>
<script src="index.js"></script>
</head>
<body>
<canvas id="camerafeed"></canvas>
</body>
</html>
| 8thwall/web/xrextras/index.html/0 | {
"file_path": "8thwall/web/xrextras/index.html",
"repo_id": "8thwall",
"token_count": 241
} | 6 |
const xrPrimitives = () => {
const faceAnchorPrimitive = {
defaultComponents: {
'xrextras-faceanchor': {},
},
mappings: {
'face-id': 'xrextras-faceanchor.faceId',
},
}
const resourcePrimitive = {
defaultComponents: {
'xrextras-resource': {},
},
mappings: {
src: 'xrextras-resource.src',
},
}
const pbrMaterialPrimitive = {
defaultComponents: {
'xrextras-pbr-material': {},
},
mappings: {
tex: 'xrextras-pbr-material.tex',
metalness: 'xrextras-pbr-material.metalness',
normals: 'xrextras-pbr-material.normals',
roughness: 'xrextras-pbr-material.roughness',
alpha: 'xrextras-pbr-material.alpha',
opacity: 'xrextras-pbr-material.opacity',
},
}
const basicMaterialPrimitive = {
defaultComponents: {
'xrextras-basic-material': {},
},
mappings: {
tex: 'xrextras-basic-material.tex',
alpha: 'xrextras-basic-material.alpha',
opacity: 'xrextras-basic-material.opacity',
},
}
const videoMaterialPrimitive = {
defaultComponents: {
'xrextras-video-material': {},
},
mappings: {
video: 'xrextras-video-material.video',
alpha: 'xrextras-video-material.alpha',
autoplay: 'xrextras-video-material.autoplay',
opacity: 'xrextras-video-material.opacity',
},
}
const faceMeshPrimitive = {
defaultComponents: {
'xrextras-face-mesh': {},
},
mappings: {
'material-resource': 'xrextras-face-mesh.material-resource',
},
}
const faceAttachmentPrimitive = {
defaultComponents: {
'xrextras-face-attachment': {},
},
mappings: {
point: 'xrextras-face-attachment.point',
},
}
const earAttachmentPrimitive = {
defaultComponents: {
'xrextras-ear-attachment': {},
},
mappings: {
point: 'xrextras-ear-attachment.point',
},
}
const captureButtonPrimitive = {
defaultComponents: {
'xrextras-capture-button': {},
},
mappings: {
'capture-mode': 'xrextras-capture-button.captureMode',
},
}
const capturePreviewPrimitive = {
defaultComponents: {
'xrextras-capture-preview': {},
},
mappings: {
'action-button-view-text': 'xrextras-capture-preview.actionButtonViewText',
'action-button-share-text': 'xrextras-capture-preview.actionButtonShareText',
'finalize-text': 'xrextras-capture-preview.finalizeText',
},
}
const captureConfigPrimitive = {
defaultComponents: {
'xrextras-capture-config': {},
},
mappings: {
'enable-end-card': 'xrextras-capture-config.enableEndCard',
'short-link': 'xrextras-capture-config.shortLink',
'cover-image-url': 'xrextras-capture-config.coverImageUrl',
'footer-image-url': 'xrextras-capture-config.footerImageUrl',
'max-duration-ms': 'xrextras-capture-config.maxDurationMs',
'end-card-call-to-action': 'xrextras-capture-config.endCardCallToAction',
'max-dimension': 'xrextras-capture-config.maxDimension',
'watermark-image-url': 'xrextras-capture-config.watermarkImageUrl',
'watermark-max-width': 'xrextras-capture-config.watermarkMaxWidth',
'watermark-max-height': 'xrextras-capture-config.watermarkMaxHeight',
'watermark-location': 'xrextras-capture-config.watermarkLocation',
'file-name-prefix': 'xrextras-capture-config.fileNamePrefix',
'request-mic': 'xrextras-capture-config.requestMic',
'include-scene-audio': 'xrextras-capture-config.includeSceneAudio',
'exclude-scene-audio': 'xrextras-capture-config.excludeSceneAudio', // deprecated
},
}
const namedImageTargetPrimitive = {
defaultComponents: {
'xrextras-named-image-target': {},
},
mappings: {
name: 'xrextras-named-image-target.name',
},
}
const targetMeshPrimitive = {
defaultComponents: {
'xrextras-target-mesh': {},
},
mappings: {
'material-resource': 'xrextras-target-mesh.material-resource',
'target-geometry': 'xrextras-target-mesh.geometry',
'height': 'xrextras-target-mesh.height',
'width': 'xrextras-target-mesh.width',
},
}
const curvedTargetContainerPrimitive = {
defaultComponents: {
'xrextras-curved-target-container': {},
},
mappings: {
'color': 'xrextras-curved-target-container.color',
'width': 'xrextras-curved-target-container.width',
'height': 'xrextras-curved-target-container.height',
},
}
const targetVideoFadePrimitive = {
defaultComponents: {
'xrextras-target-video-fade': {},
},
mappings: {
'video': 'xrextras-target-video-fade.video',
'width': 'xrextras-target-video-fade.width',
'height': 'xrextras-target-video-fade.height',
},
}
const targetVideoSoundPrimitive = {
defaultComponents: {
'xrextras-target-video-sound': {},
},
mappings: {
'video': 'xrextras-target-video-sound.video',
'thumb': 'xrextras-target-video-sound.thumb',
'width': 'xrextras-target-video-sound.width',
'height': 'xrextras-target-video-sound.height',
},
}
const opaqueBackgroundPrimitive = {
defaultComponents: {
'xrextras-opaque-background': {},
},
mappings: {
remove: 'xrextras-opaque-background.remove',
},
}
// Register hand attachment point primitive
const handAttachmentPrimitive = {
defaultComponents: {
'xrextras-hand-attachment': {},
},
mappings: {
'point': 'xrextras-hand-attachment.point',
'point-type': 'xrextras-hand-attachment.pointType',
},
}
// Register hand anchor primitive
const handAnchorPrimitive = {
defaultComponents: {
'xrextras-hand-anchor': {},
},
}
// Register hand mesh primitive
const handMeshPrimitive = {
defaultComponents: {
'xrextras-hand-mesh': {},
},
mappings: {
'material-resource': 'xrextras-hand-mesh.material-resource',
'wireframe': 'xrextras-hand-mesh.wireframe',
'uv-orientation': 'xrextras-hand-mesh.uv-orientation',
},
}
// Register hand mesh primitive
const handOccluderPrimitive = {
defaultComponents: {
'xrextras-hand-occluder': {},
},
mappings: {
'show': 'xrextras-hand-occluder.show',
'adjustment': 'xrextras-hand-occluder.adjustment',
},
}
return {
'xrextras-faceanchor': faceAnchorPrimitive,
'xrextras-resource': resourcePrimitive,
'xrextras-pbr-material': pbrMaterialPrimitive,
'xrextras-basic-material': basicMaterialPrimitive,
'xrextras-video-material': videoMaterialPrimitive,
'xrextras-face-mesh': faceMeshPrimitive,
'xrextras-face-attachment': faceAttachmentPrimitive,
'xrextras-ear-attachment': earAttachmentPrimitive,
'xrextras-capture-button': captureButtonPrimitive,
'xrextras-capture-preview': capturePreviewPrimitive,
'xrextras-capture-config': captureConfigPrimitive,
'xrextras-curved-target-container': curvedTargetContainerPrimitive,
'xrextras-named-image-target': namedImageTargetPrimitive,
'xrextras-target-mesh': targetMeshPrimitive,
'xrextras-target-video-fade': targetVideoFadePrimitive,
'xrextras-target-video-sound': targetVideoSoundPrimitive,
'xrextras-opaque-background': opaqueBackgroundPrimitive,
'xrextras-hand-attachment': handAttachmentPrimitive,
'xrextras-hand-anchor': handAnchorPrimitive,
'xrextras-hand-mesh': handMeshPrimitive,
'xrextras-hand-occluder': handOccluderPrimitive,
}
}
export {
xrPrimitives,
}
| 8thwall/web/xrextras/src/aframe/xr-primitives.js/0 | {
"file_path": "8thwall/web/xrextras/src/aframe/xr-primitives.js",
"repo_id": "8thwall",
"token_count": 3206
} | 7 |
<div id="previewContainer">
<div class="top-bar">
<div class="preview-box">
<button id="closePreviewButton" class="style-reset icon-button">
<img src="//cdn.8thwall.com/web/img/mediarecorder/close-v2.svg">
</button>
<img id="imagePreview">
<video id="videoPreview" playsinline loop></video>
<button id="toggleMuteButton" class="style-reset icon-button" >
<img id="muteButtonImg" src="//cdn.8thwall.com/web/img/mediarecorder/sound-on-v1.svg">
</button>
</div>
</div>
<div class="bottom-bar">
<div class="finalize-container">
<div id="finalizeText"></div>
<progress id="finalizeProgressBar" value="0" max="100"></progress>
</div>
<button id="downloadButton" class="style-reset icon-button">
<img src="//cdn.8thwall.com/web/img/mediarecorder/download-v1.svg">
</button>
<div id="openSafariText" class="style-reset">Downloading is only available in Safari</div>
<div id="tapAndHoldText" class="style-reset">Tap + Hold to Share</div>
<button id="actionButton" class="style-reset show-with-download-button">
<span id="actionButtonText"></span>
<img id="actionButtonImg">
</button>
</div>
</div>
| 8thwall/web/xrextras/src/mediarecorder/media-preview.html/0 | {
"file_path": "8thwall/web/xrextras/src/mediarecorder/media-preview.html",
"repo_id": "8thwall",
"token_count": 490
} | 8 |
#runtimeErrorContainer {
z-index: 800;
background-color: #101118;
}
.xrextras-old-style #runtimeErrorContainer {
background-color: #FFFFFF;
}
.floater {
-webkit-filter: drop-shadow(5px 5px 5px #222);
}
| 8thwall/web/xrextras/src/runtimeerrormodule/runtime-error-module.css/0 | {
"file_path": "8thwall/web/xrextras/src/runtimeerrormodule/runtime-error-module.css",
"repo_id": "8thwall",
"token_count": 82
} | 9 |
## 一、HTML5 简介
### 1、什么是 HTML5
HTML5 不是一门新的语言,而是我们之前学习的 HTML 的第五次重大修改版本。
### 2、HTML 的发展历史
- 超文本标记语言(第一版,不叫 HTML 1.0)——在 1993 年 6 月作为互联网工程工作小组(IETF)工作草案发布(并非标准);
- HTML 2.0——1995 年 11 月作为 RFC 1866 发布,在 RFC 2854 于 2000 年 6 月发布之后被宣布已经过时
- HTML 3.2——1997 年 1 月 14 日,W3C 推荐标准
- HTML 4.0——1997 年 12 月 18 日,W3C 推荐标准
- HTML 4.01(微小改进)——1999 年 12 月 24 日,W3C 推荐标准
- HTML 5——2014 年 10 月 28 日,W3C 推荐标准
### 3、HTML5 的设计目的
HTML5 的设计目的是**为了在移动设备上支持多媒体**。之前网页如果想嵌入视频音频,需要用到 flash ,但是苹果设备是不支持 flash 的,所以为了改变这一现状,html5 应运而生。
新的语法特征被引进以支持视频音频,如 video、audio 和 canvas 标记。
HTML5 还引进了新的功能,可以真正改变用户与文档的交互方式。比如增加了新特性:语义标签,本地存储,网页多媒体等等,以及 CSS3 特性。
相比之前的进步:
- 取消了一些过时的 HTML4 标签
- 新的表单控件(比如 date、time、email、url、search)
- 语义化标签(比如 article、footer、header、nav、section)
- 对本地离线存储的更好的支持
- 用于绘画的 canvas 元素
- 用于多媒体的 video 和 audio 元素
## 二、语义化标签
### 1、什么是语义化标签?
类似于 p,span,img 等这样的,看见标签就知道里面应该保存的是什么内容的是语义化标签。
像 div 这样的里面可以装任意东西的就是非语义化标签。
以前我们要做下面这个结构可能会这么布局:

```html
<div class="header"></div>
<div class="nav"></div>
<div class="main">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="footer"></div>
```
那么在 html5 下语义化标签怎么做呢?

```html
<header></header>
<nav></nav>
<main>
<article></article>
<aside></aside>
</main>
<footer></footer>
```
是不是语义化的代码结构更清晰、简洁呢?
### 2、HTML5 部分新增的标签
#### 2.1、结构标签
- `header`:一个区块的头部信息/标题;
- `footer`:一个区块的底部信息;
- `nav`:导航栏区域;
- `section`:一个通用独立章节或者区域。一般来说会包含一个标题。
- `article`:一块独立区块,表示一块相对比较独立的内容;
- `aside`:表示一个和主体内容几乎无关的部分,可以被单独的拆分出来而不会使整体受影响。
#### 2.2、表单标签
- email:邮件控件;
- url:地址控件;
- range:数字范围控件;
- 日期选择器:
- date:选取日、月、年
- month:选取月、年
- week:选取周和年
- time:选取时间(小时和分钟)
- datetime:选取时间、日、月、年(UTC 时间)
- datetime-local:选取时间、日、月、年(本地时间)
- search:搜索控件;
- color:颜色控件
综合示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
form {
width: 600px;
margin: 10px auto;
}
form > fieldset {
padding: 10px 10px;
}
form > fieldset > meter,
form > fieldset > input {
width: 100%;
height: 30px;
margin: 8px 0;
border: none;
border: 1px solid #aaa;
border-radius: 4px;
font-size: 16px;
padding-left: 5px;
box-sizing: border-box; /*避免padding+border的影响*/
}
form > fieldset > meter {
padding: 0;
}
</style>
</head>
<body>
<form action="">
<fieldset>
<legend>学生档案</legend>
<label for="txt">姓名:</label>
<input type="text" name="userName" id="txt" placeholder="请输入姓名" required>
<label for="phone">手机号码:</label>
<input type="tel" name="phone" id="phone" required
pattern="^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$">
<label for="em">邮箱:</label>
<input type="email" name="myemail" id="em" required>
<label for="collage">学院:</label>
<input type="text" name="collage" id="collage" list="dl" required>
<datalist id="dl">
<option value="电气与电子工程学院"></option>
<option value="经济与管理学院"></option>
<option value="外国语学院"></option>
<option value="艺术与传媒学院"></option>
</datalist>
<label for="num">入学成绩:</label>
<input type="number" name="num" id="num" required max="100" min="0" value="0" step="0.5">
<label for="level">基础水平:</label>
<meter id="level" max="100" min="0" high="90" low="59"></meter>
<label for="edt">入学日期:</label>
<input type="date" name="dt" id="edt" required>
<label for="ldt">毕业日期:</label>
<input type="date" name="dt" id="ldt" required>
<input type="submit" id="sub">
</fieldset>
</form>
<script>
document.getElementById("phone").oninvalid = function () {
this.setCustomValidity("请输入11位正确的手机号码!");
};
document.getElementById("num").oninput = function () {
document.getElementById("level").value = this.value;
};
</script>
</body>
</html>
```

**表单标签新增的一些属性:**
- `autofocus`:自动获取焦点
- `required`:不能为空
- `disabled`:禁用
- `hidden`:隐藏
#### 2.3、媒体标签
- video:视频;
- audio:音频;
- embed:嵌入内容(包括各种媒体),Midi、Wav、AU、MP3、Flash、AIFF 等。
```html
<body>
<!--audio:音频-->
<!--
src:播放文件的路径
controls:音频播放器的控制器面板
autoplay:自动播放
loop:循环播放
muted:静音
preload:
auto 默认加载音频文件所有数据;
metadata:仅加载多媒体文件元数据(文件属性,比如文件时长,音质信息等)
none: 不加载任何内容。
-->
<audio src="../mp3/aa.mp3" controls></audio>
<!--video:视频-->
<!--
src:播放文件的路径
controls:音频播放器的控制器面板
autoplay:自动播放
loop:循环播放
poster:指定视频还没有完全下载完毕,或者用户没有点击播放前显示的封面。 默认显示当前视频文件的第一副图像
width:视频的宽度
height:视频的高度
-->
<!--注意事项:视频始终会保持原始的宽高比。意味着如果你同时设置宽高,并不是真正的将视频的画面大小设置为指定的大小,而只是将视频的占据区域设置为指定大小,除非你设置的宽高刚好就是原始的宽高比例。所以建议:在设置视频宽高的时候,一般只会设置宽度或者高度,让视频文件自动缩放-->
<video
src="../mp3/mp4.mp4"
poster="../images/l1.jpg"
controls
height="600"
></video>
<!--source:因为不同的浏览器所支持的视频格式不一样,为了保证用户能够看到视频,我们可以提供多个视频文件让浏览器自动选择-->
<video src="../mp3/flv.flv" controls></video>
<video controls>
<!--视频源,可以有多个源-->
<source src="../mp3/flv.flv" type="video/flv" />
<source src="../mp3/mp4.mp4" type="video/mp4" />
</video>
</body>
```
> 注意:Chrome 在 2018 年 4 月份更新后关闭了 audio、video 媒体标签的 autoplay 自动播放 , 这个改变是在 Google Chrome 版本 66 开始的时候,不再自动开始播放音频和视频文件,阻止对广告视频和其他烦人的网页元素进行自动播放,原因大概是为了提高用户体验,防止一进入网页会自动播放声音过大的音频。在之后测试发现火狐浏览器也有类似情况发生。
>
> 测试后发现,如果使用的是 video 标签,可以添加 muted 属性,这样视频可以自动播放,但是是为静音模式。
**媒体标签的方法:(20190221)**
参考连接:[HTML 音频/视频 - 菜鸟教程](http://www.runoob.com/tags/ref-av-dom.html)
可以通过 js 控制音视频的播放:(所有网页音视频的控制都应该使用 js 控制,播放的控件自己画,这样才能达到跨平台界面相同。)
参看连接:http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp
1、获取媒体标签的 dom 元素(例如叫 mdom)
2、控制媒体的行为的方法和属性和触发事件。
```js
// 方法
mdom.play() // 开始播放
mdom.pause() // 暂停播放
mdom.load() // 重新加载音视频
// 属性
autoplay // 设置或返回歌曲是否自动播放
controls // 设置或返回是否显示原生播放控件
currentSrc // 获取当前的播放地址
paused // 是否是暂停状态
currentTime: // 获取或者设置当前音视频播放时长
defaultMuted // 设置或返回当前音频视频是否默认静音
muted // 设置或返回当前音视频是否静音
duration // 返回当前音频/视频的长度(以秒计)。需要在媒体加载完成后获取
// 一般使用 mdom.addEventListener('durationchange',function() {
// console.log(this.duration)
// }
defaultPlaybackRate // 设置或返回默认的播放速度
// 正值为正向播放,负值为负向播放
// 1 为正常速度, <1 慢速, >1 加速
playbackRate // 设置或返回当前的播放速度,值同上
ended // 返回当前资源是否播放结束
error // 返回播放错误信息
loop // 设置或返回是否循环播放
preload // 设置加载机制(自动,metadata,none)
readyState // 返回当前音视频是否准备完毕
volume // 设置或返回当前音量
// 事件
canplay // 当前资源可以被播放的时候
durationchange // 当播放总时长发送改变的时候
pause // 当前资源被暂停时
play // 当前资源被播放时
playing // 包含上面play时机,但是因网络原因导致播放终止而后重新开始播放时只会触发playing
ratechange // 播放速度发生变化时触发
seeked // 由用户更改当前播放时长时触发
seeking // 由用户刚开始更改播放时长时触发
timeupdate // 当播放位置发生变化时触发(无论是否由用户操作)
volumechange // 当音量发生变化时触发
```
#### 2.4、其他功能标签
- mark:标注;
---
- progress:进度条;
- ` <progress max="100" value="20"></progress>`
属性: max 最大值,value:当前值
- meter(度量器):
属性:
high:被界定为高的值的范围。
low:被界定为低的值的范围。
max:规定范围的最大值。
min:规定范围的最小值。
optimum: 规定度量的最优值。
value:规定度量的当前值。
```html
<progress max="100" value="30"></progress>
<br>
<meter max="100" min="0" high="70" low="30" value="20"></meter>
<meter max="100" min="0" high="70" low="30" value="50"></meter>
<meter max="100" min="0" high="70" low="30" value="90"></meter>
```

---
- time:数据标签,给搜索引擎使用;
- 发布日期 `<time datetime="2014-12-25T09:00">9:00</time>`
- 更新日期 `<time datetime="2015-01-23T04:00" pubdate>4:00</time>`
- ruby 和 rt:对某一个字进行注释;
- ` <ruby> 汉 <rt>han</rt> 字 <rt>zi</rt> </ruby>`
- canvas:绘图标签;
- deteils :展开菜单;
- datalist:数据列表元素;
```html
<form action="">
<!--专业:
<select name="" id="">
<option value="1">前端与移动开发</option>
<option value="2">java</option>
<option value="3">javascript</option>
<option value="4">c++</option>
</select>-->
<!--不仅可以选择,还应该可以输入-->
<!--建立输入框与datalist的关联 list="datalist的id号"-->
专业:<input type="text" list="subjects" /> <br />
<!--通过datalist创建选择列表-->
<datalist id="subjects">
<!--创建选项值:value:具体的值 label:提示信息,辅助值-->
<!--option可以是单标签也可以是双标签-->
<option value="英语" label="不会" />
<option value="前端与移动开发" label="前景非常好"></option>
<option value="java" label="使用人数多"></option>
<option value="javascript" label="做特效"></option>
<option value="c" label="不知道"></option>
</datalist>
网址:<input type="url" list="urls" />
<datalist id="urls">
<!--如果input输入框的type类型是url,那么value值必须添加http://-->
<option value="http://www.baidu.com" label="百度"></option>
<option value="http://www.sohu.com"></option>
<option value="http://www.163.com"></option>
</datalist>
</form>
```
| Daotin/Web/01-HTML/02-HTML5/01-HTML5概述,语义化标签.md/0 | {
"file_path": "Daotin/Web/01-HTML/02-HTML5/01-HTML5概述,语义化标签.md",
"repo_id": "Daotin",
"token_count": 8143
} | 10 |
## 一、CSS初始化
### 1、什么是CSS初始化呢?
CSS初始化是指**重设浏览器的样式**。不同的浏览器默认的样式可能不尽相同,所以开发时的第一件事可能就是如何把它们统一。如果没对CSS初始化往往会出现浏览器之间的页面差异。每次新开发网站或新网页时候通过初始化CSS样式的属性,为我们将用到的CSS或html标签更加方便准确,使得我们开发网页内容时更加方便简洁,同时减少CSS代码量,节约网页下载时间。
### 2、为什么要初始化CSS呢?
为了考虑到**浏览器的兼容问题**,其实不同浏览器对有些标签的默认值是不同的,如果没对CSS初始化往往会出现浏览器之间的页面差异。当然,初始化样式会对SEO有一定的影响,但鱼和熊掌不可兼得,但力求影响最小的情况下初始化。
最简单的初始化方法就是:` * {padding: 0; margin: 0;} ` 。有很多人也是这样写的。这确实很简单,但有人就会感到疑问:*号这样一个通用符在编写代码的时候是快,但如果网站很大,CSS样式表文件很大,这样写的话,他会把所有的标签都初始化一遍,这样就大大的加强了网站运行的负载,会使网站加载的时候需要很长一段时间。
写过css的都知道每个网页引进的css首先都需要初始化,而出名的css reset有YUI css reset(QQ、淘宝等都出现他的影子),业内用的最多的还有Erik Meyer’s CSS Reset。
[以上参考链接:Gavin_zhong](https://www.cnblogs.com/Gavinzhong/p/6995328.html)
### 3、常见的一些CSS初始化代码
- 腾讯
```css
body,ol,ul,h1,h2,h3,h4,h5,h6,p,th,td,dl,dd,form,fieldset,legend,input,textarea,select{margin:0;padding:0}
body{font:12px"宋体","Arial Narrow",HELVETICA;background:#fff;-webkit-text-size-adjust:100%;}
a{color:#2d374b;text-decoration:none}
a:hover{color:#cd0200;text-decoration:underline}
em{font-style:normal}
li{list-style:none}
img{border:0;vertical-align:middle}
table{border-collapse:collapse;border-spacing:0}
p{word-wrap:break-word}
```
- 新浪
```css
body,ul,ol,li,p,h1,h2,h3,h4,h5,h6,form,fieldset,table,td,img,div{margin:0;padding:0;border:0;}
body{background:#fff;color:#333;font-size:12px; margin-top:5px;font-family:"SimSun","宋体","Arial Narrow";}
ul,ol{list-style-type:none;}
select,input,img,select{vertical-align:middle;}
a{text-decoration:none;}
a:link{color:#009;}
a:visited{color:#800080;}
a:hover,a:active,a:focus{color:#c00;text-decoration:underline;}
```
- 淘宝
```css
body, h1, h2, h3, h4, h5, h6, hr, p, blockquote, dl, dt, dd, ul, ol, li, pre, form, fieldset, legend, button, input, textarea, th, td { margin:0; padding:0; }
body, button, input, select, textarea { font:12px/1.5tahoma, arial, \5b8b\4f53; }
h1, h2, h3, h4, h5, h6{ font-size:100%; }
address, cite, dfn, em, var { font-style:normal; }
code, kbd, pre, samp { font-family:couriernew, courier, monospace; }
small{ font-size:12px; }
ul, ol { list-style:none; }
a { text-decoration:none; }
a:hover { text-decoration:underline; }
sup { vertical-align:text-top; }
sub{ vertical-align:text-bottom; }
legend { color:#000; }
fieldset, img { border:0; }
button, input, select, textarea { font-size:100%; }
table { border-collapse:collapse; border-spacing:0; }
```
## 二、overflow 属性
> overflow 属性规定当内容溢出元素框时发生的事情.

> `visible`: 默认值。如果内容超出了元素框,则会在框外显示。
> `hidden`: 如果内容超出了元素框,则会隐藏超出的内容。
> `scroll`:不管内容有没有超出元素框,一直显示滚动条.
> `auto`:只有内容出了盒子才显示滚动条。
> `inherit`: 规定应该从父元素继承 overflow 属性的值。
## 三、定位
### 1、静态定位(默认)
```css
position: static; // 就是文档流模式的定位。
```
### 2、绝对定位
```css
position: absolute;
```
**然后使用left | right | top | bottom 来确定具体位置。**
> 特点:
> 1.元素使用绝对定位之后不占据原来的位置(脱标)
> 2.元素使用绝对定位,位置是从浏览器出发。
> 3.嵌套的盒子,父盒子没有使用定位,子盒子绝对定位,子盒子位置是从浏览器出发。
> 4.嵌套的盒子,父盒子使用定位,子盒子绝对定位,子盒子位置是从父元素位置出发。
> 5.给行内元素使用绝对定位之后,转换为行内块。(不推荐使用,推荐使用`display:inline-block;`)
### 3、相对定位
```css
position: relative;
```
> 特点:
> 1.使用相对定位,位置从自身出发。
> 2.**不脱标**,其他的元素不能占有其原来的位置。
> **3.子绝父相(父元素相对定位,子元素绝对定位),用的最多的场景。**
> 4.行内元素使用相对定位不能转行内块元素。
### 4、固定定位
```css
position:fixed;
```
> 特点:
> 1.固定定位之后,不占据原来的位置(脱标)
> 2.元素使用固定定位之后,位置从浏览器出发。
> 3.元素使用固定定位之后,会转化为行内块(不推荐,推荐使用display:inline-block;)
### 5、定位(脱标)的盒子居中对齐
`margin:0 auto; ` 只能让标准流的盒子居中对齐
**定位的盒子居中:子绝父相,然后子盒子先往右走父盒子的一半50%,在向左走子盒子的一半(margin-left:负值。**

## 四、标签包含规范
- div可以包含所有的标签。
- p标签不能包含div, h1等标签(一般包含行内元素)。
- h1可以包含p,div等标签(一般不这样)。
- 行内元素尽量包含行内元素,行内元素不要包含块元素。

## 五、规避脱标流
1. **尽量使用标准流。**
2. **标准流解决不了的使用浮动。**
3. **浮动解决不了的使用定位。**
```css
margin-left:auto; //盒子一直往右冲,一直冲不动为止。也是 margin:0 auto; 的由来。
```
## 六、图片和文字垂直居中对齐
```css
vertical-align 主要用在 inline-block 标签上,效果最好。
默认属性是: vertical-align:baseline;
```

| Daotin/Web/02-CSS/01-CSS基础/04-CSS初始化、定位、overflow、标签规范.md/0 | {
"file_path": "Daotin/Web/02-CSS/01-CSS基础/04-CSS初始化、定位、overflow、标签规范.md",
"repo_id": "Daotin",
"token_count": 3764
} | 11 |
## 其他总结
1、高和行高也可以撑开盒子,背景图不行。
2、文字不设置行高,是包含文字的盒子的行高。
3、行内元素有定位就可以直接设置宽高
4、文字不在设置的行高等背景里面是因为没有设置行高
5、如果给了定位,但是没有给left,top等值,默认会腾出行内元素、padding的位置,有的时候我们可以使用这些特性,有的时候我们不熟悉的话可能产生bug。
6、较少功能使用较少代码(a代替ui>li>a)
7、如果盒子都是左对齐的话,最后一个盒子在右边的位置不够的话,会掉下来,如果第一个盒子A比第二个盒子B高,那么最后一个盒子C掉下来后跟第二个盒子B左对齐,而不是跟第一个盒子A左对齐。如果最后一个盒子C后面还有一个盒子D的话,D盒子的顶端跟C对齐。

8、标准流中的文字不会被浮动的盒子遮挡住。所以一个大盒子中的小盒子要么都浮动要么都不浮动。

9、父盒子高度为0 ,子盒子如果是浮动的话不占位置,下面的标准流盒子将会跑到子盒子下面。或者,父盒子高度为0,然后子绝父相,下面的标准流盒子依然会跑到子盒子下面。(这个可以做类似京东的侧边栏,如果侧边栏挡住了跑上来的标准流盒子,那么把包含标准流的整个大盒子定位:position:relative ,因为定位的层级高,所以就可以显示标准流的所有内容了。)

10、想要盒子随着界面变大变小,而盒子随着界面的中线能够移动的时候(类似定位/脱标的盒子居中对齐),不要加版心。
11、父盒子有高度,但是子盒子太高,父盒子会被撑破;如果父盒子没有高度,那么父盒子会被撑开,是所有子盒子最高的高度。撑开的盒子可能会产生影响。**(不要让浮动的盒子超出父盒子)**
12、浮动盒子的相互影响,不管是否在一个大盒子里面(蓝盒子是包含在粉红盒子里面的,紫盒子和粉红盒子是并列的)。

13、定位的时候,left的权限比right权限高,top比bottom高,提高权限也没用。
14、行高可以继承。
15、如果一个大盒子装的是li标签,而且li标签是浮动的,如果li里面的内容超过了大盒子的话,会有li标签掉下来,如何使得所有的li标签在一行显示呢?
用一个辅助盒子装下所有的li标签,然后大盒子只装辅助盒子,这样对于大盒子来说,所有的li标签都会在一行显示,即使大盒子很小。而辅助盒子可以使用ul来代替,给ui一个所有li加起来的宽度即可。
16、行内元素给了定位,不需要转block,唯有static, relative不行。
17、background: url("spirit.png") -135px 0;
关于背景の问题:
有时候我发现background后面两个px可以调节位置,有的时候又必须使用left,top等调位置。其实后面的两个px本来就是调位置的,而且调的是整个背景的位置,当需要整张图片的时候,调节这两个px就可以了,但是精灵图因为需要的只是某一个区域的图,调节这两个px只是将选中的区域移动到原点,这样方便使用left,top等来调到具体的位置。
18、.current类选择器:给谁用,谁显示。
| Daotin/Web/02-CSS/01-CSS基础/其他总结.md/0 | {
"file_path": "Daotin/Web/02-CSS/01-CSS基础/其他总结.md",
"repo_id": "Daotin",
"token_count": 2290
} | 12 |
一个功能的实现:
需求:**li下面有a标签,要求li之间有竖线间隔,竖线的长度和a相同,鼠标放到li上高亮,高亮的区域没有到达竖线。**如下图:

**实现的方式就是:**
- 设置 li 的`margin`间隔
- 设置 a 的`margin`为负值,`padding`为正值即可。
| Daotin/Web/02-CSS/一个小功能的实现.md/0 | {
"file_path": "Daotin/Web/02-CSS/一个小功能的实现.md",
"repo_id": "Daotin",
"token_count": 280
} | 13 |
## 一、事件
事件是发生并得到处理的操作,即:事情来了,然后处理。
例如:
- 电话铃声响起(事件发生),需要接电话(处理)
- 学生举手请教问题(有事了),需要解答(处理)
- 按钮被点击了,然后对应有处理代码(一般是函数)
- 光标进入文本框的区域了,然后对应一个函数来处理。
## 二、常见的事件
```js
onchange // 区域的内容被改变。
oncopy // 内容被复制
oncontextmenu // 显示上下文菜单(如鼠标右键的时候显示选项菜单)
onclick //单击
ondblclick //双击
onfocus //获得焦点。
onblur //失去焦点。
onkeydown //某个键盘按键被按下。
onkeyup //某个键盘按键被松开。
onkeypress //某个键盘按键被按下并松开。
onload //一张页面或一幅图像完成加载。
onmousedown //鼠标按钮被按下。
onmouseup //鼠标按键被松开。
onmouseover //鼠标移到某元素之上。
onmouseout //鼠标从某元素移开。
onmousemove //鼠标移动。
onreset //重置按钮被点击。
onresize //窗口重新调整大小。
onsubmit //确认(提交)按钮被点击。
onunload //用户关闭页面
```
## 三、event 对象
一个事件一般包括:事件源(触发事件的元素,如:按钮,鼠标的位置及状态、按下的键,事件发生的时间等。而这些信息都属于event对象的属性。(什么时间,发生了什么事情,发生在谁身上等等)。
event对象只在事件发生(如:点击事件)的过程中才有效。如:当点击按钮时,就会自动产生event对象。event对象是自带的对象,是固定写法。
在W3C标准中,直接在函数中声明该参数即可:
```js
btn.onclick = function(event) { //event在调用和函数定义时,都写上也是考虑兼容问题
//兼容性写法,支持老版本的IE
var evt = event || window.event || event;
};
```
## 四、event 事件的属性
```js
e.button //返回当事件被触发时,哪个鼠标按钮被点击(鼠标左键,鼠标中键,鼠标右键)。
e.altKey //返回当事件被触发时,"ALT" 是否被按下,按下为 true。
e.shiftKey //返回当事件被触发时,"SHIFT" 键是否被按下。
e.ctrlKey //返回当事件被触发时,"CTRL" 键是否被按
e.clientX //返回当事件被触发时,鼠标指针的水平坐标(等同于 e.screenX)。
e.clientY //返回当事件被触发时,鼠标指针的垂直坐标(等同于 e.screenY)。
e.pageX // 返回鼠标距离页面左边的距离(包含滚动条滚动的距离 + 鼠标距左边可是区域的距离)
e,pageY
```
## 五、键盘事件
获取键盘对应的编码:
```js
document.onkeydown = document.onkeyup = function (e) {
var e = window.event || e;
var keyCode = evt.which || evt.keyCode; // 获取按下键对应的编码
}
```
| Daotin/Web/03-JavaScript/02-DOM/07-事件.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/02-DOM/07-事件.md",
"repo_id": "Daotin",
"token_count": 2121
} | 14 |
原文链接:[js变量提升与函数提升的过程详解](https://daotin.github.io/2019/05/16/js%E5%8F%98%E9%87%8F%E6%8F%90%E5%8D%87%E4%B8%8E%E5%87%BD%E6%95%B0%E6%8F%90%E5%8D%87%E7%9A%84%E8%AF%A6%E7%BB%86%E8%BF%87%E7%A8%8B.html)
| Daotin/Web/03-JavaScript/02-DOM/js变量提升与函数提升的过程详解.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/02-DOM/js变量提升与函数提升的过程详解.md",
"repo_id": "Daotin",
"token_count": 178
} | 15 |
前面我们写了这么多 Ajax 的代码,其实都是基于 js 的原生代码,在 jQuery 的内部,对 Ajax 已经进行了封装,它提供了很多方法可以供开发者进行调用。不过这些封装都是基于一个方法的基础上进行的修改,这个方法就是`$.ajax()` 。
我们主要学习3个方法:
- $.ajax();
- $.get();
- $.post();
### 1、$.ajax()
$.ajax() 和 自己的 myAjax2() 使用起来非常的相似,基本上原理一致。同样是传入一个对象,有些参数不传递的话也有默认值。
```js
// 其他代码省略
userObj.blur(function () {
$.ajax({
url: "./server/checkUsername.php",
type: "get",
data: {uname: this.value},
success: function (result) {
if(result == "ok") {
userSpanObj.text("用户名可用");
} else if(result == "error") {
userSpanObj.text("用户名不可用");
}
}
});
});
```
### 2、$.get() 和 \$.post
只需要传两个参数,第一个参数是url(带param的,里面有参数和值),第二个参数是回调函数。
```js
// $.get()
$.get(url + "?" + params, function (result) {});
// $.post()
$.post(url, {参数: 值}, function(result) {});
```
示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="dv">
<h1>用户注册</h1>
用户名:<input type="text" name="username"><span id="user-span"></span><br>
邮箱:<input type="text" name="email"><span id="email-span"></span><br>
手机:<input type="text" name="phone"><span id="phone-span"></span><br>
</div>
<script src="jquery-1.12.4.min.js"></script>
<script>
// 获取所有元素
var userObj = $("input[name='username']");
var emailObj = $("input[name='email']");
var phoneObj = $("input[name='phone']");
var userSpanObj = $("#user-span");
var emailSpanObj = $("#email-span");
var phoneSpanObj = $("#phone-span");
//用户名文本框失去焦点事件
userObj.blur(function () {
$.get("./server/checkUsername.php?uname=" + $(this).val(), function (result) {
if (result == "ok") {
userSpanObj.text("用户名可用");
} else if (result == "error") {
userSpanObj.text("用户名不可用");
}
});
});
//邮箱文本框失去焦点事件
emailObj.blur(function () {
$.post("./server/checkEmail.php", {e: $(this).val()}, function (result) {
if (result == 0) {
emailSpanObj.text("邮箱可用");
} else if (result == 1) {
emailSpanObj.text("邮箱不可用");
}
});
});
//手机号文本框失去焦点事件
phoneObj.blur(function () {
$.post("./server/checkPhone.php", {phonenumber: $(this).val()}, function (result) {
result = JSON.parse(result);
if (result.status == 0) {
phoneSpanObj.text(result.message.tips + " " + result.message.phonefrom);
} else if (result.status == 1) {
phoneSpanObj.text(result.message);
}
});
});
</script>
</body>
</html>
```
| Daotin/Web/06-Ajax/09-jQuery中的Ajax.md/0 | {
"file_path": "Daotin/Web/06-Ajax/09-jQuery中的Ajax.md",
"repo_id": "Daotin",
"token_count": 1800
} | 16 |
常见的网页布局方式分为以下四种:
1、**固定宽度布局**:为网页设置一个固定的宽度,通常以px做为长度单位,常见于PC端网页。
2、**流式布局**:为网页设置一个相对的宽度,通常以百分比做为长度单位。
3、**栅格化布局**:将网页宽度人为的划分成均等的长度,然后排版布局时则以这些均等的长度做为度量单位,通常利用百分比做为长度单位来划分成均等的长度。
4、**响应式布局**:通过检测设备信息,决定网页布局方式,即用户如果采用不同的设备访问同一个网页,有可能会看到不一样的内容,一般情况下是检测设备屏幕的宽度来实现。
> 注:以上几种布局方式并不是独立存在的,实际开发过程中往往是相互结合使用的。"
## 1、响应式布局
响应式布局,意在**实现不同屏幕分辨率的终端上浏览网页的不同展示方式**。
通过响应式设计能使网站在手机和平板电脑上有更好的浏览阅读体验,如下图:

如上图所示,屏幕尺寸不一样展示给用户的网页内容也不一样,我们利用 **媒体查询** 可以检测到屏幕的尺寸(主要检测宽度),并设置不同的CSS样式,就可以实现响应式的布局。

## 2、响应式布局的缺点
我们利用响应式布局可以满足不同尺寸的终端设备非常完美的展现网页内容,使得用户体验得到了很大的提升,但是为了实现这一目的我们不得不利用媒体查询**写很多冗余的代码**,使整体网页的体积变大,应用在移动设备上就会带来严重的性能问题。
响应式布局**常用于企业的官网、博客、新闻资讯类型网站**,这些网站以浏览内容为主,没有复杂的交互。
## 3、屏幕尺寸的划分
一般我们会对常见的设备尺寸进行划分后,再分别确定为不同的尺寸的设备设计专门的布局方式,如下图所示
| 类型 | 布局宽度 |
| ------- | ----------- |
| 大屏幕 | \>= 1200px |
| 默认 | \>= 980px |
| 平板 | \>= 768px |
| 手机到平板之间 | <= 767px |
| 手机 | <= 480px |
## 4、媒体查询
参考链接:http://www.runoob.com/cssref/css3-pr-mediaquery.html
使用 `@media` 查询,你可以针对不同的媒体类型定义不同的样式。
`@media` 可以针对不同的屏幕尺寸设置不同的样式,特别是如果你需要设置设计响应式的页面,@media 是非常有用的。
当你重置浏览器大小的过程中,页面也会根据浏览器的宽度和高度重新渲染页面。
**CSS 语法:**
```css
@media mediatype and|not|only (media feature) {
/*CSS-Code*/
}
/*或者引入不同样式文件的判断:当满足某个条件的时候,引入mystylesheet.css样式*/
<link rel="stylesheet" media="mediatype and|not|only (media feature)" href="mystylesheet.css">
```
**mediatype 取值:**
> all 用于所有设备
>
> print 用于打印机和打印预览
>
> screen 用于电脑屏幕,平板电脑,智能手机等。
>
> speech 应用于屏幕阅读器等发声设备
**and|not|only:**
> and 同时满足,相当于 &&;
>
> not 取反(一般写在 mediatype 前面)
**示例:**
```css
<style>
body{
background-color: red;
}
/* 不在768-992之间的时候,设置背景颜色为蓝色*/
@media not screen and (min-width: 768px) and (max-width: 992px){
body{
background-color: blue;
}
}
</style>
```
**media feature 取值**:(主要关注以下三个宽度)
> device-height 定义输出设备的屏幕可见高度。
>
> **device-width** 定义输出设备的屏幕可见宽度。
>
> max-device-height 定义输出设备的屏幕可见的最大高度。
>
> max-device-width 定义输出设备的屏幕最大可见宽度。
>
> min-device-width 定义输出设备的屏幕最小可见宽度。
>
> min-device-height 定义输出设备的屏幕的最小可见高度。
>
> max-height 定义输出设备中的页面最大可见区域高度。
>
> **max-width** 定义输出设备中的页面最大可见区域宽度。
>
> min-height 定义输出设备中的页面最小可见区域高度。
>
> **min-width** 定义输出设备中的页面最小可见区域宽度。
### 4.1、min-width 与 min-device-height 的区别
device 表示的是设备,所以加了 device 的 范围取值表示的是**设备的宽度范围**。
- 在移动端,由于通过模拟器改变的是移动端设备的宽度,所以 min-width 与 min-device-height 效果一样;
- 在 PC 端,如果改变浏览器的宽度,而我们电脑的宽度并没有改变,所以设备的宽度一定,最终的效果就是只有一个范围起作用。
### 4.2、案例:控制不同屏幕尺寸下屏幕背景色,
```css
<style>
.container{
width:1200px;
margin: 0 auto;
height:1200px;
background-color: red;
}
/*媒体查询:注意and后面空格的添加*/
/*iphone: w < 768px*/
@media screen and (max-width: 768px){
.container{
width:100%;
background-color: green;
}
}
/*pad: w >= 768 && w< 992*/
@media screen and (max-width: 992px) and (min-width: 768px) {
.container{
width:750px;
background-color: blue;
}
}
/*中等屏幕 w >= 992 && w<1200*/
@media screen and (max-width: 1200px) and (min-width: 992px) {
.container{
width:970px;
background-color: pink;
}
}
</style>
```
### 4.3、媒体查询条件判断的顺序
原因:如果结构如上面示例的那样,并且媒体查询条件由重叠的话,后面的媒体查询样式设置会覆盖前面的媒体查询设置,为了避免发生这种情况,我们就应该遵循一定的规律,使得不同的媒体查询条件下,执行不同的样式,而不会发生冲突。
**特点:**
> **向上兼容:如果设置了宽度更小时的样式,默认这些样式也会传递到宽度更大的条件范围内.**
>
> 向下覆盖:宽度更大的样式会将前面宽度更小的样式覆盖
**书写建议:**
- **如果是判断最小值 (min-width),那么范围就应该从小到大写**
- **如果是判断最大值 (max-width),那么范围就应该从大到小写**
**例如:**
```css
@media screen and (min-width: 768px){
body{
background-color: green;
}
}
!*w:992!1200 blue min-width: 992px:当屏幕的宽度大于等于992的时候*!
@media screen and (min-width: 992px){
body{
background-color: blue;
}
}
!*w>1200 pink*!
@media screen and (min-width: 1200px){
body{
background-color: pink;
}
}
```
| Daotin/Web/07-移动Web开发/06-响应式布局.md/0 | {
"file_path": "Daotin/Web/07-移动Web开发/06-响应式布局.md",
"repo_id": "Daotin",
"token_count": 4484
} | 17 |
* {
margin: 0;
padding: 0;
}
.section {
overflow: hidden;
}
/* 第一屏 */
.first {
padding-top: 100px;
}
.first .logo {
width: 251px;
height: 186px;
background-image: url("../images/logo.png");
margin: 0 auto;
}
.first .text {
text-align: center;
margin: 100px 0 20px 0;
}
.first .text > img {
margin: 0 20px;
opacity: 0.1;
transition: margin 0.8s,opacity 0.8s;
}
.first .info1 {
width: 772px;
height: 49px;
background-image: url("../images/info_1.png");
margin: 0 auto;
}
/* 第一屏动画 */
.first.current .text > img {
margin: 0 5px;
opacity: 1;
}
/* 第二屏 */
.second > div{
display: flex;
justify-content: space-around;
align-items: center;
}
.second .shield {
width: 440px;
font-size: 0; /* 消除盾牌之间的间隙*/
}
.second .shield > img {
opacity: 0.1;
transition: transform 0.8s, opacity 0.8s;
}
.second .shield > img:nth-of-type(1){
transform: translate(-100px, 200px) rotate(30deg);
}
.second .shield > img:nth-of-type(2){
transform: translate(300px, 20px) rotate(60deg);
}
.second .shield > img:nth-of-type(3){
transform: translate(300px, 10px) rotate(-50deg);
}
.second .shield > img:nth-of-type(4){
transform: translate(600px, 20px) rotate(-90deg);
}
.second .shield > img:nth-of-type(5){
transform: translate(30px, 200px) rotate(90deg);
}
.second .shield > img:nth-of-type(6){
transform: translate(-30px, -30px) rotate(-30deg);
}
.second .shield > img:nth-of-type(7){
transform: translate(0px, 100px) rotate(-30deg);
}
.second .shield > img:nth-of-type(8){
transform: translate(320px, 150px) rotate(30deg);
}
.second .shield > img:nth-of-type(9){
transform: translate(-190px, -280px) rotate(-30deg);
}
.second .info2 {
width: 635px;
height: 309px;
background-image: url("../images/info_2.png");
}
/* 第二屏动画 */
.second.current .shield > img {
transform: none;
opacity: 1;
}
/* 第三屏 */
.third {
position: relative;
}
.third .info3 {
width: 631px;
height: 278px;
background-image: url("../images/info_3.png");
position: absolute;
left:50%;
top: 50%;
transform: translate(-100%,-50%);
}
.third .circle {
width: 453px;
height: 449px;
background-image: url("../images/circle.png");
position: absolute;
left: 57%;
top: 50%;
transform: translateY(-50%);
}
.third .circle .rocket {
width: 203px;
height: 204px;
background-image: url("../images/rocket.png");
position: absolute;
left: -50%;
top: 150%;
transition: left 0.8s, top 0.8s;
}
/* 第三屏动画 */
.third.current .circle .rocket {
left: 115px;
top: 115px;
}
/* 第四屏 */
.fourth {
position: relative;
}
.fourth .search {
width: 529px;
height: 438px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-115%, -50%);
overflow: hidden;
}
.fourth .search .search-bar{
width: 529px;
height: 66px;
background-image: url("../images/search.png");
transform: translateX(-100%);
}
.fourth .search .search-text{
width: 0;
height: 22px;
background-image: url("../images/key.png");
position: absolute;
left: 18px;
top: 23px;
}
.fourth .search .search-content{
width: 529px;
height: 0;
background-image: url("../images/result.png");
margin-top: -12px;
}
.fourth .info4 {
width: 612px;
height: 299px;
background-image: url("../images/info_4.png");
position: absolute;
left: 50%;
top: 50%;
transform: translateY(-50%);
}
/* 第四屏动画 */
.fourth.current .search .search-bar{
transform: none;
transition: transform 0.8s;
}
.fourth.current .search .search-text{
width: 99px;
transition: width 0.8s 0.8s steps(5);
}
.fourth.current .search .search-content{
height: 372px;
transition: height 0.8s 1.6s;
}
| Daotin/Web/07-移动Web开发/案例源码/01-仿360浏览器全屏首页/css/360Page.css/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/01-仿360浏览器全屏首页/css/360Page.css",
"repo_id": "Daotin",
"token_count": 1699
} | 18 |
window.onload = function () {
bannerEffect();
timeCount();
slideshowEffect();
};
// 搜索栏上下滚动时改变透明度
function bannerEffect() {
var bannerObj = document.querySelector(".search");
var slideshowObj = document.querySelector(".slideshow")
// 获取搜索栏的高度
var bannerHeight = bannerObj.offsetHeight; //40
// 获取轮播图高度
var slideshowHeight = slideshowObj.offsetHeight; //311
window.addEventListener("scroll", function () {
// 页面向上滚动的距离(兼容代码)
var scrolllen = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
if (scrolllen < (slideshowHeight - bannerHeight)) {
var setopacity = scrolllen / (slideshowHeight - bannerHeight);
bannerObj.style.backgroundColor = "rgba(233, 35, 34, " + setopacity + ")";
}
}, false);
}
// 主体内容秒杀栏目的倒计时
function timeCount() {
var spanObjs = document.querySelector(".content-title-left-time").children;
var titleCount = 2 * 60 * 60; // 2小时倒计时
var timeId = setInterval(function () {
titleCount--;
var hour = Math.floor(titleCount / 3600);
var minute = Math.floor((titleCount % 3600) / 60);
var second = titleCount % 60;
if (titleCount >= 0) {
// 下面的true实际想表达的是不执行任何操作,但是必须要写个语句,所以用true代替。
spanObjs[0].innerHTML == Math.floor(hour / 10) ? true : spanObjs[0].innerHTML = Math.floor(hour / 10);
spanObjs[1].innerHTML == hour % 10 ? (true) : spanObjs[1].innerHTML = hour % 10;
spanObjs[3].innerHTML == Math.floor(minute / 10) ? true : spanObjs[3].innerHTML = Math.floor(minute / 10);
spanObjs[4].innerHTML == minute % 10 ? true : spanObjs[4].innerHTML = minute % 10;
spanObjs[6].innerHTML == Math.floor(second / 10) ? true : spanObjs[6].innerHTML = Math.floor(second / 10);
spanObjs[7].innerHTML == second % 10 ? true : spanObjs[7].innerHTML = second % 10;
} else {
titleCount = 0;
clearInterval(timeId);
return;
}
}, 1000);
}
// 轮播图
function slideshowEffect() {
// 1. 自动轮播图
// 思路:1.1、使用js在图片开头动态添加原本最后一张图片
// 1.2、使用js在图片结尾动态添加原本第一张图片
// 获取轮播图
var slideshowObj = document.querySelector(".slideshow");
// 获取ul
var ulObj = document.querySelector(".slideshow-img");
// 获取所有li
var liObjs = ulObj.children;
// 设置li的索引值
var index = 1;
// 要添加的第一个li和最后一个li
var first = liObjs[0].cloneNode(true);
var last = liObjs[liObjs.length - 1].cloneNode(true);
// 在li开头结尾添加克隆图片
ulObj.appendChild(first);
ulObj.insertBefore(last, ulObj.firstElementChild);
// 设置ul宽度
ulObj.style.width = liObjs.length + "00%";
// 设置每个li的宽度
for (var i = 0; i < liObjs.length; i++) {
liObjs[i].style.width = slideshowObj.offsetWidth + "px";
}
// 默认显示第一张图
ulObj.style.transform = "translateX(" + -(slideshowObj.offsetWidth) + "px)"
// 改变窗口大小的时候自动调节轮播图的宽度
window.addEventListener("resize", function () {
ulObj.style.width = liObjs.length + "00%";
for (var i = 0; i < liObjs.length; i++) {
liObjs[i].style.width = slideshowObj.offsetWidth + "px";
}
// 改变窗口的大小的时候,不能仅仅回到第一张,要回到第index张
ulObj.style.transform = "translateX(" + -(slideshowObj.offsetWidth * index) + "px)"
}, false);
// 1. 实现自动轮播效果
var timerId;
var timerStart = function () {
timerId = setInterval(function () {
index++;
ulObj.style.transition = "transform 0.5s ease-in-out";
ulObj.style.transform = "translateX(" + -(slideshowObj.offsetWidth * index) + "px)";
// 设置小白点
if(index >= liObjs.length - 1) {
setDot(1);
return;
}
setDot(index);
// 由于过渡效果,使得过渡的时候,就进行if、判断,无法显示最后一张图片。
// 所以进行延时过渡的时候,等所有过渡效果完成后再进行判断是否到达最后一张。
setTimeout(function () {
if (index >= liObjs.length - 1) {
index = 1;
// 从最后一张调到第一张的时候,取消过渡效果
ulObj.style.transition = "none";
ulObj.style.transform = "translateX(" + -(slideshowObj.offsetWidth * index) + "px)";
}
}, 500);
}, 1500);
};
timerStart();
// 2. 轮播图的手动滑动效果
// 2.1、记录手指的起始位置
// 2.2、记录手指滑动时与起始位置水平轴的偏移距离
// 2.3、设置当手指松开后,判断偏移距离的大小,决定回弹还是翻页。
var startX, diffX;
// 设置节流阀,避免手动滑动过快,在过渡过程中也有滑动,造成的最后图片会有空白的操作,也就是index越界了,没有执行相应的 webkitTransitionEnd 事件。
var isEnd = true;
ulObj.addEventListener("touchstart", function (e) {
// 手指点击轮播图时,停止自动轮播效果
clearInterval(timerId);
startX = e.targetTouches[0].clientX;
}, false);
// 最开始的时候不触发,原因ul的高度为0
ulObj.addEventListener("touchmove", function (e) {
if (isEnd) {
// 手指移动的距离
diffX = e.targetTouches[0].clientX - startX;
// 关闭过渡效果,否则手指滑动困难
ulObj.style.transition = "none";
ulObj.style.transform = "translateX(" + -(slideshowObj.offsetWidth * index - diffX) + "px)";
}
}, false);
ulObj.addEventListener("touchend", function (e) {
isEnd = false;
// 判断当前滑动的距离是否超过一定的距离,则翻页
if (Math.abs(diffX) > 100) {
if (diffX > 0) {
index--;
} else {
index++;
}
// 翻页
ulObj.style.transition = "transform 0.5s ease-in-out";
ulObj.style.transform = "translateX(-" + slideshowObj.offsetWidth * index + "px)";
} else if (Math.abs(diffX) > 0) { // 回弹
ulObj.style.transition = "transform 0.5s ease-in-out";
ulObj.style.transform = "translateX(-" + slideshowObj.offsetWidth * index + "px)";
}
// 每次离开手指清除startX, diffX的值
startX = 0;
diffX = 0;
if(index == liObjs.length-1) {
setDot(1);
return;
} else if(index == 0) {
setDot(liObjs.length-2);
return;
}
setDot(index);
// 手指离开重新开启定时器
timerStart();
}, false);
// 我们发现在第一张往右滑动,或者最后一张往左滑动时,会造成空白
/*webkitTransitionEnd:可以监听当前元素的过渡效果执行完毕,当一个元素的过渡效果执行完毕的时候,会触发这个事件*/
ulObj.addEventListener("webkitTransitionEnd", function () {
// 如果到了第一张(index=0),让index=count-2
// 如果到了最后一张(index=count-1),让index=1;
if (index == 0) {
index = liObjs.length - 2;
// 从第一张到最后一张的时候,取消过渡效果
ulObj.style.transition = "none";
ulObj.style.transform = "translateX(" + -(slideshowObj.offsetWidth * index) + "px)";
} else if (index >= liObjs.length - 1) {
index = 1;
// 从最后一张调到第一张的时候,取消过渡效果
ulObj.style.transition = "none";
ulObj.style.transform = "translateX(" + -(slideshowObj.offsetWidth * index) + "px)";
}
// 设置过渡效果完成后,才可以继续滑动
setTimeout(function () {
isEnd = true;
}, 100);
}, false);
// 3. 设置轮播图小白点
function setDot(index) {
var dotliObjs = document.querySelector(".slideshow-dot").children;
// 建议不使用className,因为class属性可能有多个,使用dotliObjs[i].className = "";可能将其他的类样式一起清除。
for (var i = 0; i < dotliObjs.length; i++) {
// 清除所有select样式
dotliObjs[i].classList.remove("select");
}
// 设置当前索引的样式为select
dotliObjs[index-1].classList.add("select");
}
} | Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/js/index.js/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/js/index.js",
"repo_id": "Daotin",
"token_count": 5008
} | 19 |
/*公共css样式*/
body {
font-family: "Microsoft YaHei", sans-serif;
font-size: 14px;
color: #333;
}
a {
text-decoration: none;
color: #333;
}
a:hover {
text-decoration: none;
color: #333;
}
/*左边距*/
.m_l10 {
margin-left: 10px;
}
/*右边距*/
.m_r10 {
margin-right: 10px;
}
/*自定义字体*/
@font-face {
font-family: 'wjs';
src: url('../fonts/MiFie-Web-Font.eot');
/* IE9*/
src: url('../lib/fonts/MiFie-Web-Font.eot') format('embedded-opentype'), /* IE6-IE8 */
url('../lib/fonts/MiFie-Web-Font.woff') format('woff'), /* chrome、firefox */
url('../lib/fonts/MiFie-Web-Font.ttf') format('truetype'), /* chrome、firefox、opera、Safari, Android, iOS 4.2+*/
url('../lib/fonts/MiFie-Web-Font.svg') format('svg');
/* iOS 4.1- */
}
/*自定义字体使用样式*/
.wjs_icon {
font-family: wjs;
}
/*手机图标对应的编码*/
.wjs_icon_phone::before {
content: "\e908";
}
/*电话图标对应的编码*/
.wjs_icon_tel::before {
content: "\e909";
font-size: 14px;
}
/*wjs logo*/
.wjs_icon_logo::before {
content: "\e920";
}
/*wjs 文本*/
.wjs_icon_text::before {
content: "\e93e";
}
.wjs_icon_new01::before {
content: "\e90e";
}
.wjs_icon_new02::before {
content: "\e90f";
}
.wjs_icon_new03::before {
content: "\e910";
}
.wjs_icon_new04::before {
content: "\e911";
}
.wjs_icon_partner01::before {
content: "\e946";
}
.wjs_icon_partner02::before {
content: "\e92f";
}
.wjs_icon_partner03::before {
content: "\e92e";
}
.wjs_icon_partner04::before {
content: "\e92a";
}
.wjs_icon_partner05::before {
content: "\e929";
}
.wjs_icon_partner06::before {
content: "\e931";
}
.wjs_icon_partner07::before {
content: "\e92c";
}
.wjs_icon_partner08::before {
content: "\e92b";
}
.wjs_icon_partner09::before {
content: "\e92d";
}
.wjs_iconn_E903::before {
content: "\e903";
}
.wjs_icon_E906::before {
content: "\e906";
}
.wjs_icon_E905::before {
content: "\e905";
}
.wjs_icon_E907::before {
content: "\e907";
}
.wjs_icon_E901::before {
content: "\e901";
}
.wjs_icon_E900::before {
content: "\e900";
}
.wjs_icon_E904::before {
content: "\e904";
}
.wjs_icon_E902::before {
content: "\e902";
}
.wjs_icon_E906::before {
content: "\e906";
} | Daotin/Web/07-移动Web开发/案例源码/03-微金所/css/common.css/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/css/common.css",
"repo_id": "Daotin",
"token_count": 1208
} | 20 |
// Screen Readers
// -------------------------
.sr-only { @include sr-only(); }
.sr-only-focusable { @include sr-only-focusable(); }
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_screen-reader.scss/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_screen-reader.scss",
"repo_id": "Daotin",
"token_count": 42
} | 21 |
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
(function(w){
"use strict";
w.matchMedia = w.matchMedia || (function( doc, undefined ) {
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement( "body" ),
div = doc.createElement( "div" );
div.id = "mq-test-1";
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
docElem.insertBefore( fakeBody, refNode );
bool = div.offsetWidth === 42;
docElem.removeChild( fakeBody );
return {
matches: bool,
media: q
};
};
}( w.document ));
}( this ));
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/respond/matchmedia.polyfill.js/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/respond/matchmedia.polyfill.js",
"repo_id": "Daotin",
"token_count": 397
} | 22 |
## 一、内置模块
### 1、url
描述:可以对地址字符串进行解析
```js
let url = require("url");
let urlStr = "https://www.baidu.com/s?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6";
let urlObj = url.parse(urlStr); // 将字符串形式的地址转换成对象格式
console.log(urlObj);
// Url {
// protocol: 'https:', // 协议
// slashes: true, // 是否有"//"
// auth: null,
// host: 'www.baidu.com',
// port: null,
// hostname: 'www.baidu.com',
// hash: null,
// search: '?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6',
// query: 'ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6',
// pathname: '/s',
// path: '/s?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6',
// href: 'https://www.baidu.com/s?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6'
// }
console.log(url.format(urlObj));// 将对象形式的地址转换成字符串
// https://www.baidu.com/s?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6
```
在parse再加一个参数true的时候:query后面的值会变成对象形式:
```js
let urlObj = url.parse(urlStr,true);
//Url {
// protocol: 'https:',
// slashes: true,
// auth: null,
// host: 'www.baidu.com',
// port: null,
// hostname: 'www.baidu.com',
// hash: null,
// search: '?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6',
// query: { ie: 'utf-8', wd: '周杰伦' },
// pathname: '/s',
// path: '/s?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6',
// href: 'https://www.baidu.com/s?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6' }
```
如果在加一个参数:true,则可以解析不带’http’的地址:此时protocol字段为null。
```js
let urlObj = url.parse(urlStr, true, true);
// Url {
// protocol: null,
// slashes: true,
// auth: null,
// host: 'www.baidu.com',
// port: null,
// hostname: 'www.baidu.com',
// hash: null,
// search: '?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6',
// query: { ie: 'utf-8', wd: '周杰伦' },
// pathname: '/s',
// path: '/s?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6',
// href: '//www.baidu.com/s?ie=utf-8&&wd=%E5%91%A8%E6%9D%B0%E4%BC%A6' }
```
### 2、querystring
描述:用户将地址栏传参的字符串类型转换成对象类型(类似jq的ajax传参的对象形式)
```js
let qs = require("querystring");
let obj = {
user: "daotin",
pwd: "123456"
}
/**
* qs.stringify(args1 [, args2, args3])
* args1: 需要转换成字符串的对象
* args2: 指定每个键值对之间的间隔符
* args3: 指定键和值之间的间隔符
*/
let str1 = qs.stringify(obj);
let str2 = qs.stringify(obj, "#");
let str3 = qs.stringify(obj, "#", ":");
console.log(str1); //user=daotin&pwd=123456
console.log(str2); //user=daotin#pwd=123456
console.log(str3); //user:daotin#pwd:123456
/**
* qs.parse(args1 [,args2,args3])
*
* args1: 需要转换成对象的字符串
* args2: 指定每个键值对之间的间隔符
* args3: 指定键和值之间的间隔符
*
*/
console.log(qs.parse(str1)); //{ user: 'daotin', pwd: '123456' }
console.log(qs.parse(str2, "#")); //{ user: 'daotin', pwd: '123456' }
console.log(qs.parse(str3, "#", ":")); //{ user: 'daotin', pwd: '123456' }
```
> 注意: 在转换的时候,如果不是标准地址传值参数的形式的字符串,需要转换成标准形式的字符串才能正确的转成对象。
querystring 还可以将地址栏中的中文转换成字符编码形式。
`escape`:中文转字符编码
`unescape`:字符编码转中文
```js
let qs = require("querystring");
let str = "周杰伦";
let tmp = qs.escape(str); // 中文转字符编码
console.log(tmp); //%E5%91%A8%E6%9D%B0%E4%BC%A6
console.log(qs.unescape(tmp)); // 周杰伦
```
### 3、events
描述:事件模块
```js
let EventEmitter = require("events").EventEmitter; //事件模块的构造函数
let event = new EventEmitter();
let myFunc = (str) => {
console.log("event 事件触发1次" + str);
}
// 事件监听方式一
event.on("daotin", myFunc);
// 事件监听方式二
event.addListener("daotin", (str) => {
console.log("event 事件触发2次" + str);
});
// 事件触发
event.emit("daotin", "我是参数");
setTimeout(() => {
//移除事件监听(必须有函数名,不能像jq一样不写函数名,有点类似原生js)
event.removeListener("daotin", myFunc);
event.emit("daotin","我是参数");
}, 3000);
```
>**事假监听有三种:**
>`event.on("daotin", myFunc);`
>
>`event.addListener("daotin", (str) => {
> console.log("event 事件触发2次" + str);
>});`
>
>`event.once("daotin", (str) => { **// event.emit抛发多次的时候只执行一次**
> console.log("event 事件触发2次" + str);
>});`
>
>
>
>**移除事件监听:**
>
>1、一定要有函数名
>
>2、不能使用off解绑
>
>`event.removeListener("daotin", myFunc);`
>
>`event.removeAllListeners("daotin")` // 删除指定事件上的所有监听函数,此时不需要函数名。
>
>`event.removeAllListeners()` // 如果不传参数(事件名) 则所有事件的所有监听函数都会被删除
>
>
>
>**event.emit 可以传入两个参数:**
>
>参数1:事件名
>
>参数2:参数(如果是多个参数,可以传入一个对象)。
第一次 event.emit 触发 ‘daotin’事件的时候,打印两次结果。
第二次 event.emit 的时候,由于移除有函数名的事件监听对象,所以只打印第二次。
当向event中添加事件监听的时候,是有事件个数的限制的,如果绑定的事件超出了默认个数,会出现警告,但是不会报错,程序依然可以正常执行。如果我们想要改变警告上限,可以使用下面方式:
```js
event.setMaxListeners(40); // 设置绑定事件警告上限为40
```
### 4、fs
描述:文件操作模块。可以操作本地文件的增删改查,文件目录的新增修改删除等操作,还有文件读取流,文件写作流。
**文件相关操作:**
```js
let fs = require("fs");
// 创建一个目录
// err 是创建失败的参数,创建成功则为空
fs.mkdir("logs", err => {
if (!err) {
console.log("创建目录成功");
}
});
// 创建或修改文件
// 参数1:文件名
// 参数2:文件的内容
// 参数3:成功或失败回调函数
fs.writeFile("logs/test", "这是一个测试文件", err => {
if (!err) {
console.log("文件创建/修改成功");
}
});
/**
* 文件追加内容
*/
fs.appendFile("logs/test", "这是一个新的测试文件", err => {
if (!err) {
console.log("文件追加成功");
}
});
// 文件读取
fs.readFile("logs/1.txt", "utf-8", (err, data) => {
if (!err) {
console.log(data);
}
});
/**
* 删除文件
*/
fs.unlink("logs/test", err => {
if (!err) {
console.log("删除文件成功");
}
});
```
> `fs.writeFile(filename,content,callback)` 替换文件内容/创建文件(当文件不存在时) 第一个参数代表文件名(可以包含文件路径)
>
> `fs.appednFile(filename,content,callback)` 向已存在的文件末尾添加文本内容
>
> `fs.readFile(filename,ecode,callback)` 读取文件内容,第二个参数代表读取时的字符编码集,回调有两个参数,第一个参数是失败时的打印信息;第二个参数是读取到的data数据。
>
> `fs.unlink(filename,callback)` 删除指定名字的文件
**文件夹相关操作:**
```js
/**
* 修改目录名或文件名
* 如果不是相同的目录,那么不仅修改文件名或目录名,并且移动其路径
*/
fs.rename("logs", "msg", err => {
if (!err) {
console.log("文件名修改成功");
}
});
/**
* 读取目录文件
*/
fs.readdir("msg", (err, data) => {
if (!err) {
console.log(data); // 结果是一个数组集合 [ '1.txt', 'log1.txt', 'log2.txt', 'test' ]
}
});
/**
* 删除目录
* (目录必须为空才可以,没有强制删除其内容的指令)
*/
fs.rmdir("logs", (err, data) => {
if(!err) {
console.log(data);
}
});
/**
* 读取目录或文件的相关信息
* 读取目录或文件相关信息,可通过回调函数的第二个形参的isFile()/ifDirectory()方法判断是否为文件或目录。
* ifFile():判断是否为文件,是文件返回true
* ifDirectory():判断是否为目录,是文件返回true
*/
fs.stat("msg/test", (err, info) => {
if (!err) {
if (info.isFile()) {
console.log("文件类型");
} else if (info.isDirectory()) {
console.log("目录类型");
}
}
});
```
> `fs.mkdir(dirname,callback)` :创建目录,第一个参数代表目录名
>
> `fs.rename(oldname,newname,callback)` :修改文件或者目录名(路径一致时)/移动文件或者目录(路径不一致时))
>
> `fs.readdir(path,callback)` :读取目录,(返回的结果为数组包含该目录中所有的文件名和目录名)
>
> `fs.rmdir(pathname,callback)` :删除目录,(目录必须为空)
>
> `fs.stat(pathname,callback)` :读取目录或文件相关信息,可通过回调函数的第二个形参的isFile()方法判断是否为文件 以及 isDirectory()来判断是否为目录。
**文件流**
当我们一个文件非常大的时候,就不能使用readFile的方式来读取了,需要采用数据流的方式来阶段性的读取。这时候就需要采用数据流的读取和写入模式。
```js
let fs = require("fs");
// 创建读取流对象
let rs = fs.createReadStream("msg/log1.txt");
// 创建写入流对象
let rw = fs.createWriteStream("msg/log2.txt");
let count = 0;
// 读取流每读取一定大小的数据就会触发“data”事件
rs.on("data", msg => {
count++;
if (count === 1) {
console.log(msg.toString()); // 读取的数据时buffer类型的数据,需要先转换成字符串类型的数据
}
});
// end事件表示,所有数据读取完全的时候触发。
rs.on("end", () => {
console.log(count);
});
// rs是数据读取流,读取到的数据可以使用接收流来接收数据,这时读取到的数据就流入到
// rw对应的文件中。
rs.pipe(rw);
```
> 所有文件的读取和写入都是异步操作的。
如果想要同步实现,可以加上下面一句话:
```js
fs.appendFileSync()
```
### 5、http
描述:用于创建web服务
下面创建一个简单的web服务:
```js
let http = require("http");
/**
* 创建一个server服务
* req:表示客户端请求的数据
* res:表示服务器回应的数据
*/
let server = http.createServer((req, res) => {
// 200是响应状态码
//"Content-Type": "text/html; charset=utf8"是响应头中部分内容类型的数据,返回的是什么格式的文本,字符编码是什么。
res.writeHead(200, {
"Content-Type": "text/html; charset=utf8"
});
//返回响应正文
res.write("hello world");
// 服务器响应完毕
res.end();
});
/**
* 启动服务,监听端口
* 参数1:端口号
* 参数2:域名(省略则默认是locolhost)
* 参数3:打印语句
*/
server.listen(3000, () => {
console.log("server running at http://localhost:3000");
});
```
**http请求过程如下:**
请求行包括:
- 请求方式:get/post
- 请求路径:path 域名后面的内容
- http的请求版本号(常用HTTP/1.1)
请求头:JSON的字符串
请求正文:post的data地址参数对象。(get没有在地址中包含)
状态行:
- http版本号
- 状态码200/404等
响应头:JSON字符串
响应正文:

> PS:所有Node自带模块都可以在这里找到:http://nodejs.cn/api/
| Daotin/Web/10-Node.js/02-Nodejs内置模块.md/0 | {
"file_path": "Daotin/Web/10-Node.js/02-Nodejs内置模块.md",
"repo_id": "Daotin",
"token_count": 7095
} | 23 |
演示案例还是接着 **vue的组件**
---
## 一、http代理
走秀后台接口文档地址:<http://39.105.136.190:3000/>

现在想在我们的vue项目中调用ajax获取这些信息。
为了方便演示,我们按照jquery来使用ajax,仅仅是演示,一般vue项目不推荐使用jquery,后面还会介绍专门用来获取ajax的工具,比如:axios。
我们在首页Home请求商品列表:
```js
// Home.js
import $ from 'jquery'
export let Home = {
template: `
<div>
<h1>首页</h1>
<router-view></router-view>
<router-view name="b"></router-view>
</div>
`,
mounted() {
$.ajax({
url: 'http://39.105.136.190:3000/zhuiszhu/goods/getList',
success(data) {
console.log(data);
}
})
},
}
```
这时候我们看到了一个熟悉的错误,这明显是跨域导致的。

现在我们项目ajax请求的图示如下:

### 1、什么是http代理
我们不能直接访问node-server的数据,但是可以把webpack-dev-server作为中间人,我们把ajax请求发给webpack-dev-server然后由它转发给node-server,由于服务器之间不存在同源策略的限制,所以这是行得通的。
node-server返回数据的时候也是一样的,借助webpack-dev-server来返回给我们vue项目。
这个模式就叫做http代理。
配置config文件:
```json
devServer: {
contentBase: __dirname + '/dist',
port: 3000,
inline: true,
// 每当我们访问/zhuiszhu地址的时候,就把请求转发给target地址的服务器。
proxy: {
'/zhuiszhu': {
target: 'http://39.105.136.190:3000',
secure: false,
changeOrigin: true
}
}
}
```
在devServer属性中添加proxy属性,表示每当我们访问/zhuiszhu地址的时候,webpack-dev-server就把请求转发给target地址的服务器。
然后我们的ajax请求的url也要修改一下:
```js
import $ from 'jquery'
export let Home = {
//...
mounted() {
$.ajax({
url: '/zhuiszhu/goods/getList',
success(data) {
console.log(data);
}
})
},
}
```
这样就可以打印数据了。
## 二、axios
我们说过vue项目中不要使用jquery,那么要发起ajax请求,还有一些比较好的插件,专门用来发送ajax请求的,axios就是其中一种。Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
安装axios
```
npm i axios -S
```
### 1、get
使用axios,我们获取到的值就在`data.data`里面,so easy 不是吗?
```js
axios.get('https://raw.githubusercontent.com/Daotin/pic/master/a.json').then(data => {
console.log(data.data);
})
```
如何传参数呢?get或post的第二个参数是一个对象,在这个对象的params属性中传递参数id=2。
**(或者直接使用问号传参的方式也是可以的)**
```js
axios.get('https://raw.githubusercontent.com/Daotin/pic/master/a.json',{params:{id:2}}).then(data => {
console.log(data.data);
})
```
### 2、post
post和get是一样的,只不过第二个参数不需要params,直接传递参数对象。
```js
axios.get('https://raw.githubusercontent.com/Daotin/pic/master/a.json',{id:2}).then(data => {
console.log(data.data);
})
```
| Daotin/Web/12-Vue/10-webpack配置http代理,axios.md/0 | {
"file_path": "Daotin/Web/12-Vue/10-webpack配置http代理,axios.md",
"repo_id": "Daotin",
"token_count": 2097
} | 24 |
## 一、react项目概述
React 起源于 Facebook 的内部项目,因为该公司对市场上所有 JavaScript MVC 框架,都不满意,就决定自己写一套,用来架设 Instagram 的网站。做出来以后,发现这套东西很好用,就在2013年5月开源了。
由于 React的设计思想极其独特,属于革命性创新,性能出众,代码逻辑却非常简单。所以,越来越多的人开始关注和使用,认为它可能是将来 Web 开发的主流工具。
这个项目本身也越滚越大,从最早的UI引擎变成了一整套前后端通吃的 Web App 解决方案。衍生的 React Native 项目,目标更是宏伟,希望用写 Web App 的方式去写 Native App。如果能够实现,整个互联网行业都会被颠覆,因为同一组人只需要写一次 UI ,就能同时运行在服务器、浏览器和手机。
React主要用于构建UI。你可以在React里传递多种类型的参数,如声明代码,帮助你渲染出UI、也可以是静态的HTML DOM元素、也可以传递动态变量、甚至是可交互的应用组件。
特点:
1.声明式设计:React采用声明范式,可以轻松描述应用。
2.高效:React通过对DOM的模拟,最大限度地减少与DOM的交互。
3.灵活:React可以与已知的库或框架很好地配合。
### 1、Tips:
设置vscode beautify 不格式化jsx语法,并且使得jsx中html可以自动补全:
在设置中:
```json
"emmet.includeLanguages": {"javascript": "javascriptreact"},
"emmet.triggerExpansionOnTab": true,
// 设置对象一行显示
// 参考链接:https://github.com/beautify-web/js-beautify/issues/315#issuecomment-397524391
"beautify.config": {
"brace_style": "collapse,preserve-inline"
},
```
## 二、react项目构建
还是使用webpack来构建项目:
使用`npm init -y` 生成package.json文件,安装可能使用到的模块。其内容如下:
```js
{
"name": "reactdemo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --inline",
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^2.1.0",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^3.0.1",
"html-webpack-plugin": "^3.2.0",
"less": "^3.9.0",
"less-loader": "^4.1.0",
"string-loader": "0.0.1",
"url-loader": "^1.1.2",
"webpack": "^3.11.0"
}
}
```
编写config配置文件,由于和vue相同,这里直接放源码:
```js
let Hwp = require("html-webpack-plugin")
let Ext = require("extract-text-webpack-plugin")
module.exports = {
entry: __dirname + "/src/main.js",
output: {
path: __dirname + "/dist/",
filename: "app.js"
},
devtool: "source-map",
devServer: {
contentBase: __dirname + "/dist/",
port: 3000,
inline: true,
// proxy: {
// "/assets": {
// target: "http://localhost:3000"
// }
// }
},
resolve: {
alias: {
"vue": "vue/dist/vue.js"
}
},
module: {
rules: [
{ test: /\.css$/, loader: Ext.extract("css-loader") },
{ test: /\.less$/, loader: Ext.extract("css-loader!less-loader") },
{ test: /\.html$/, loader: "string-loader" },
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
{ test: /\.(png|jpg|gif)$/, use: [{ loader: 'url-loader', options: { limit: 8192 } }] }
]
},
plugins: [
new Hwp({
template: "index.html",
filename: "index.html",
inject: true
}),
new Ext("app.css")
]
}
```
由于是react项目所以还需要安装react模块:
```
npm i react react-dom -S
```
然后新建入口文件:`main.js`,这里面将进行我们第一个react示例。
## 三、第一个react示例
```jsx
import ReactDOM from 'react-dom';
import React from 'react';
// 参数一:要渲染的DOM
// 参数二:渲染到的元素
ReactDOM.render(<h1>第一个react示例</h1>, document.getElementById('app'));
```
### 1、jsx语法
上面代码第一个参数是一个html标签,和js混合在了一起,这种写法叫做`jsx`语法。
但是浏览器默认是不认识jsx语法的,所以需要插件对jsx代码进行编译解析。
这个插件就是`babel-preset-react`:
安装插件:
```
npm i babel-preset-react -D
```
修改`.babelrc`
```json
{
"presets":["env","stage-2","react"]
}
```
之后编译运行,会报错说 React 找不到:

我们先看看原来的代码编译之后的样子:

由于会用到React对象,所以要先引入React模块:
```js
import React from 'react'
```
### 2、定义组件
#### 2.1、定义完整组件
举例:定义Box组件
```jsx
import ReactDOM from 'react-dom';
import React from 'react';
class Box extends React.Component {
// 有些类似于vue的template
render() {
let username = 'Daotin';
return (
// 顶层元素,只能有一个
<div>
<p>{username}</p>
</div>
);
}
}
// 渲染Box组件
ReactDOM.render(<Box />, document.getElementById('app'));
```
> 1、定义的组件必须继承自React.Component;
>
> 2、html代码中的`{}` 表示开辟一个js代码空间,可以书写js代码,一般用来插入变量。
>
> 3、render的返回值类似于vue的template(一般使用`()`包裹起来),**而且顶层元素只有一个。**
#### 2.2、state数据模型
react的数据模型书写在组件的构造函数中:
```jsx
class Box extends React.Component {
constructor() {
super();
// 数据模型
this.state = {
username: 'lvonve'
}
}
render() {
return (
<div>
<p>{this.state.username}</p>
</div>
);
}
}
```
在html模板中插入数据模型需要前缀:`this.state`
如果觉得麻烦,可以事先解构赋值出来:
```jsx
render() {
let { username } = this.state;
return (
<div>
<p>{username}</p>
</div>
);
}
```
#### 2.3、绑定事件
绑定事件采用类似 `onClick={this.点击事件名}` 的方式进行事件绑定。
比如点击按钮,age自加:
```jsx
render() {
let { username, age } = this.state;
return (
<div>
<p>{username}</p>
<p>{age}</p>
<button onClick={this.myClick}>按钮</button>
</div>
);
}
myClick() {
// this.state.age++;
this.setState({
age: this.state.age + 1
});
}
```
在操作数据模型的时候,类似于vuex,不能直接操作,而是要借助 `setState` 方法才可以。
> 有的时候看到有人直接 this.state.age++;,之后`this.forceUpdate();` 强制更新视图,也可以改变age的值,但是不推荐这样做!!!
由于此时的`this.setState` 的this不是Box了,所以要重新制定this的指向。
可以在Box初始化的时候就制定好事件的this指向。
```jsx
constructor() {
super();
// 数据模型
this.state = {
username: 'lvonve',
age: 18
};
this.myClick = this.myClick.bind(this);
}
```
或者在html中指定:
```html
<button onClick={this.myClick.bind(this)}>按钮</button>
```
但是这中方式只在本次有效,下次绑定这个方法的时候就无效了。
##### 事件传递参数
还是刚才的点击按钮事件,不过这次age加的是我们传入的参数。
```jsx
render() {
let { username, age } = this.state;
return (
<div>
<p>{username}</p>
<p>{age}</p>
<button onClick={this.myClick(10)}>按钮</button>
</div>
);
}
myClick(num) {
// this就是Box
return (function () {
this.setState({
age: this.state.age + num
});
}).bind(this);
}
```
在绑定的事件后面传递参数。
由于onClick需要的是函数体,所以在myClick里面返回值就是一个函数体。
> 不过需要注意的是,在myClick内部,this就是Box类,所以不需要在构造函数中绑定this,而是在返回的函数体中绑定this。
#### 2.4、定义简单组件
简单组件**仅用来显示父组件传递来的数据**,无法进行事件绑定等操作。
```jsx
let Box2 = function (props) {
return (
<h3>{props.title}</h3>
);
}
// 渲染Box组件
ReactDOM.render(<Box2 title="BBB" text="AAA" />, document.getElementById('app'));
```
> props为父组件传递给子组件所有数据的对象集合。
### 3、组件间传值
#### 3.1、父传子
子组件使用`this.props`接收父组件传递的数据。
```jsx
import ReactDOM from 'react-dom';
import React from 'react';
class Box extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<div>
{/* 接收到父组件传递的参数 */}
<p>接收到父组件传递的参数:{this.props.title}</p>
<p>接收到父组件传递的参数:{this.props.text}</p>
</div>
);
}
}
// 渲染Box组件
ReactDOM.render(<Box title="BBB" text="AAA" />, document.getElementById('app'));
```
如果需要在构造函数中使用的话,就需要在构造函数的参数中注入props.
```jsx
class Box extends React.Component {
// 构造函数中注入props
constructor(props) {
super(props);
this.state = {
title: this.props.title,
text: this.props.text,
};
}
render() {
return (
<div>
{/* 接收到父组件传递的参数 */}
<p>接收到父组件传递的参数:{this.state.title}</p>
<p>接收到父组件传递的参数:{this.state.text}</p>
</div>
);
}
}
```
#### 3.2、参数的类型验证
首先需要引入`prop-types`模块,这个模块是在react安装的时候自动生成的。
```js
import propTypes from 'prop-types'
```
设置传入参数的类型有两种方式:
##### 方式一
在子组件class的外面定义:
```jsx
class Box extends React.Component {
// ...
}
Box.propTypes = {
title: propTypes.string, // 规定title为string类型
text: propTypes.string // 规定text为string类型
}
ReactDOM.render(<Box title="BBB" text="AAA" />, document.getElementById('app'));
```
##### 方式二
在子组件class的内部定义:
```jsx
import propTypes from 'prop-types'
class Box extends React.Component {
constructor(props) {
super(props);
this.state = {
title: this.props.title,
text: this.props.text,
};
}
render() {
return (
<div>
{/* 接收到父组件传递的参数 */}
<p>接收到父组件传递的参数:{this.state.title}</p>
<p>接收到父组件传递的参数:{this.state.text}</p>
</div>
);
}
// 定义在class内部
static propTypes = {
title: propTypes.string, // 规定title为string类型
text: propTypes.string // 规定text为string类型
}
}
ReactDOM.render(<Box title="BBB" text="AAA" />, document.getElementById('app'));
```
如果还要加一个必填属性,只需在规则后面加上:`isRequired`即可。
```jsx
static propTypes = {
title: propTypes.string.isRequired, // 规定title为string类型
text: propTypes.string.isRequired // 规定text为string类型
}
```
大部分类型的规则如下:
```jsx
import propTypes from 'prop-types'
//...
static propTypes = {
// 你可以将属性声明为以下 JS 原生类型
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// 任何可被渲染的元素(包括数字、字符串、子元素或数组),意思就是不是一个对象。
optionalNode: PropTypes.node,
// 一个 React 元素
optionalElement: PropTypes.element,
// 你也可以声明属性为某个类的实例,这里使用 JS 的
// instanceof 操作符实现。
optionalMessage: PropTypes.instanceOf(Message),
// 你也可以限制你的属性值是某个特定值之一
optionalEnum: PropTypes.oneOf(['News', 'Photos']),
// 限制它为列举类型之一的对象
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
]),
// 一个指定元素类型的数组
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
// 一个指定类型的对象
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
// 一个指定属性及其类型的对象
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
}),
// 你也可以在任何 PropTypes 属性后面加上 `isRequired`
// 后缀,这样如果这个属性父组件没有提供时,会打印警告信息
requiredFunc: PropTypes.func.isRequired,
// 任意类型的数据
requiredAny: PropTypes.any.isRequired,
// 你也可以指定一个自定义验证器。它应该在验证失败时返回
// 一个 Error 对象而不是 `console.warn` 或抛出异常。
// 不过在 `oneOfType` 中它不起作用。
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
},
}
```
说说最后一个:自定义属性验证,看一下这三个参数到底是什么?
```jsx
static propTypes = {
title: function (props, propName, componentName) {
console.log(props, propName, componentName); // {title: "BBB", text: "AAA"} "title" "Box"
}
}
```
> props:所有参数集合对象
>
> propName:当前参数
>
> componentName:当前组件
明白了三个参数的含义,下面书写自定义规则:
```jsx
static propTypes = {
title: function (props, propName, componentName) {
if (props[propName] == 'Daotin') {
// 成功必须返回null
return null;
} else {
// 失败需要返回一个错误对象
return new Error('title的值不为Daotin!');
}
}
}
```
然后就可以收到错误提示:`Warning: Failed prop type: title的值不为Daotin!in Box`
#### 3.3、子传父
在react中没有自定义事件,所以不能使用子组件emit事件,父组件on来监听事件。
但是可以通过:
> 父组件像子组件传递参数的时候,传递的是函数,子组件执行这个函数,然后通过这个函数的参数传递到父组件上实现子传父的功能。
示例:
```jsx
export class Home extends React.Component {
constructor() {
super();
this.receive = this.receive.bind(this);
}
render() {
return (
<div>
<Box sendFun={this.receive} />
</div>
);
}
receive(data) {
// data即是子组件传来的数据
console.log(data);
}
}
class Box extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '我是子组件'
}
this.send = this.send.bind(this);
}
render() {
return (<div>
<button onClick={this.send}>发送</button>
</div>)
}
send() {
// 调用父组件的方法,将子组件数据通过父组件函数参数传给父组件
this.props.sendFun(this.state.name);
}
}
```
| Daotin/Web/13-React/01-react概述,项目搭建,jsx,父子传值.md/0 | {
"file_path": "Daotin/Web/13-React/01-react概述,项目搭建,jsx,父子传值.md",
"repo_id": "Daotin",
"token_count": 9603
} | 25 |
/*
Navicat Premium Data Transfer
Source Server : 阿里云MySQL
Source Server Type : MySQL
Source Server Version : 50718
Source Host : rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306
Source Schema : web
Target Server Type : MySQL
Target Server Version : 50718
File Encoding : 65001
Date: 07/03/2018 09:59:53
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user_info
-- ----------------------------
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`user_id` int(32) NOT NULL AUTO_INCREMENT,
`user_name` char(15) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`user_password` char(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`user_email` char(25) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`user_phone` char(15) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
`user_age` int(32) NULL DEFAULT NULL,
`user_sex` int(32) NULL DEFAULT NULL,
`user_address` char(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
`user_head_url` char(100) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
`user_nick_name` char(30) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
| Humsen/web/docs/数据库部署/第1步 - 创建数据库/user_info.sql/0 | {
"file_path": "Humsen/web/docs/数据库部署/第1步 - 创建数据库/user_info.sql",
"repo_id": "Humsen",
"token_count": 558
} | 26 |
package pers.husen.web.bean.vo;
/**
* @author 何明胜
*
* 2017年9月17日
*/
public class UserInfoVo {
private int userId;
private String userName;
private String userNickName;
private String userPassword;
private String userEmail;
private String userPhone;
private int userAge;
private int userSex;
private String userAddress;
private String userHeadUrl;
@Override
public String toString() {
return "UserInfoVo [userId=" + userId + ", userName=" + userName + ", userNickName=" + userNickName
+ ", userPassword=" + userPassword + ", userEmail=" + userEmail + ", userPhone=" + userPhone
+ ", userAge=" + userAge + ", userSex=" + userSex + ", userAddress=" + userAddress + ", userHeadUrl="
+ userHeadUrl + "]";
}
/**
* @return the userNickName
*/
public String getUserNickName() {
return userNickName;
}
/**
* @param userNickName the userNickName to set
*/
public void setUserNickName(String userNickName) {
this.userNickName = userNickName;
}
/**
* @return the userHeadUrl
*/
public String getUserHeadUrl() {
return userHeadUrl;
}
/**
* @param userHeadUrl the userHeadUrl to set
*/
public void setUserHeadUrl(String userHeadUrl) {
this.userHeadUrl = userHeadUrl;
}
/**
* @return the userId
*/
public int getUserId() {
return userId;
}
/**
* @param userId the userId to set
*/
public void setUserId(int userId) {
this.userId = userId;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the userPassword
*/
public String getUserPassword() {
return userPassword;
}
/**
* @param userPassword the userPassword to set
*/
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
/**
* @return the userEmail
*/
public String getUserEmail() {
return userEmail;
}
/**
* @param userEmail the userEmail to set
*/
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
/**
* @return the userPhone
*/
public String getUserPhone() {
return userPhone;
}
/**
* @param userPhone the userPhone to set
*/
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
/**
* @return the userAge
*/
public int getUserAge() {
return userAge;
}
/**
* @param userAge the userAge to set
*/
public void setUserAge(int userAge) {
this.userAge = userAge;
}
/**
* @return the userSex
*/
public int getUserSex() {
return userSex;
}
/**
* @param userSex the userSex to set
*/
public void setUserSex(int userSex) {
this.userSex = userSex;
}
/**
* @return the userAddress
*/
public String getUserAddress() {
return userAddress;
}
/**
* @param userAddress the userAddress to set
*/
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
}
| Humsen/web/web-core/src/pers/husen/web/bean/vo/UserInfoVo.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/bean/vo/UserInfoVo.java",
"repo_id": "Humsen",
"token_count": 1047
} | 27 |
package pers.husen.web.common.helper;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import pers.husen.web.common.constants.CommonConstants;
import pers.husen.web.dbutil.DbQueryUtils;
/**
* @desc 读取服务器的html文件
*
* @author 何明胜
*
* @created 2017年12月16日 下午11:34:49
*/
public class ReadH5Helper {
private static final Logger logger = LogManager.getLogger(DbQueryUtils.class);
/**
* 读取html文件
*
* @param htmlQualifiedName
* @return
*/
public static String readHtmlByName(String htmlQualifiedName) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(htmlQualifiedName)));
String temp;
while ((temp = br.readLine()) != null) {
sb.append(temp);
sb.append("\n");
}
} catch (IOException e) {
logger.error(e);
}
return sb.toString();
}
/**
* 根据文件路径读取文件并输出至浏览器
*
* @param htmlQualifiedName
* @param response
* @throws IOException
*/
public static void writeHtmlByName(String htmlQualifiedName, HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
OutputStream outStream = response.getOutputStream();
try {
FileInputStream fip = new FileInputStream(htmlQualifiedName);
// 建立缓冲区
byte[] buffer = new byte[1024];
int len;
while ((len = fip.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
fip.close();
outStream.close();
// 关闭输入流,释放系统资源
} catch (Exception e) {
logger.error(StackTrace2Str.exceptionStackTrace2Str(e));
}
}
/**
* 修改html的关键字,并返回html内容
*
* @param htmlQualifiedName
* @param keywords
*/
public static String modifyHtmlKeywords(String htmlQualifiedName, String keywords) {
// 空格变为英文逗号
if (keywords != null && !keywords.equals("") && keywords.indexOf(CommonConstants.ENGLISH_COMMA) == -1) {
keywords = keywords.replaceAll("\\s", ",");
}
File file = new File(htmlQualifiedName);
Document doc = null;
try {
doc = Jsoup.parse(file, "UTF-8");
} catch (IOException e) {
logger.error(StackTrace2Str.exceptionStackTrace2Str(e));
}
Element keywordsElement = doc.select("meta[name=keywords]").first();
keywordsElement.attr("content", keywords);
return doc.html();
}
} | Humsen/web/web-core/src/pers/husen/web/common/helper/ReadH5Helper.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/common/helper/ReadH5Helper.java",
"repo_id": "Humsen",
"token_count": 1124
} | 28 |
package pers.husen.web.dao;
import pers.husen.web.bean.vo.ImageUploadVo;
/**
*
*
* @author 何明胜
*
* 2017年10月20日
*/
public interface ImageUploadDao {
/**
* 插入新纪录到图片数据库
* @param iVo
* @return
*/
public int insertImageUpload(ImageUploadVo iVo);
} | Humsen/web/web-core/src/pers/husen/web/dao/ImageUploadDao.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dao/ImageUploadDao.java",
"repo_id": "Humsen",
"token_count": 132
} | 29 |
package pers.husen.web.dbutil.assist;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pers.husen.web.common.constants.CommonConstants;
import pers.husen.web.common.helper.StackTrace2Str;
import pers.husen.web.config.ProjectDeployConfig;
/**
* 数据库连接工具类
*
* @author 何明胜
*
* 2017年9月17日
*/
public class DbConnectUtils {
/**
* 日志记录器
*/
private static final Logger logger = LogManager.getLogger(DbConnectUtils.class.getName());
/**
* 获取数据库连接
*
* @return
*/
public static Connection getConnection() {
Connection connection = null;
try {
String url;
//正式数据库和测试数据不一样
String dbName;
String username;
String password;
String driveClass;
//读取数据库连接文件
Properties properties = new Properties();
FileInputStream inputStream = new FileInputStream(ProjectDeployConfig.WEB_ROOT_PATH + CommonConstants.DB_CONNECT_INFO_FILE_RELATIVE_PATH);
properties.load(inputStream);
dbName = properties.getProperty("dbname_test");
//如果是在服务器环境,则加载正式数据库
if(ProjectDeployConfig.IS_REMOTE_DEPLOY) {
inputStream = new FileInputStream(ProjectDeployConfig.WEB_ROOT_PATH + CommonConstants.DB_CONNECT_INFO_FILE_RELATIVE_PATH);
properties.load(inputStream);
dbName = properties.getProperty("dbname_official");
}
//获取公共属性
url = properties.getProperty("url_psql");
username = properties.getProperty("username_webuser");
password = properties.getProperty("password_webuser");
driveClass = properties.getProperty("driver_class");
inputStream.close();
Class.forName(driveClass);
connection = DriverManager.getConnection(url+dbName+"?useUnicode=true&characterEncoding=utf-8&useSSL=false", username, password);
//logger.info("成功获取数据库连接, url->" + (url+dbName) + ", username->" + username + ", password->" + password);
} catch (ClassNotFoundException | SQLException | IOException e) {
logger.error(e);
}
return connection;
}
/**
* 关闭连接
*/
public static void closeResouce(ResultSet rs, PreparedStatement ps, Connection conn) {
try {
if(rs != null) {
rs.close();
}
if(ps != null) {
ps.close();
}
if(conn != null) {
conn.close();
}
}catch (SQLException e) {
logger.error(e);
}
}
} | Humsen/web/web-core/src/pers/husen/web/dbutil/assist/DbConnectUtils.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dbutil/assist/DbConnectUtils.java",
"repo_id": "Humsen",
"token_count": 1106
} | 30 |
package pers.husen.web.service;
import java.util.ArrayList;
import pers.husen.web.bean.vo.BlogArticleVo;
import pers.husen.web.dao.BlogArticleDao;
import pers.husen.web.dao.impl.BlogArticleDaoImpl;
/**
* @author 何明胜
*
* 2017年9月17日
*/
public class BlogArticleSvc implements BlogArticleDao{
private static final BlogArticleDaoImpl blogArticleDaoImpl = new BlogArticleDaoImpl();
public ArrayList<BlogArticleVo> queryBlogArticles(){
return blogArticleDaoImpl.queryAllBlogArticles();
}
@Override
public int queryBlogTotalCount(BlogArticleVo bVo) {
return blogArticleDaoImpl.queryBlogTotalCount(bVo);
}
@Override
public ArrayList<BlogArticleVo> queryBlogArticlePerPage(BlogArticleVo bVo, int pageSize, int pageNo){
return blogArticleDaoImpl.queryBlogArticlePerPage(bVo, pageSize, pageNo);
}
@Override
public BlogArticleVo queryPerBlogById(int blogId) {
return blogArticleDaoImpl.queryPerBlogById(blogId);
}
@Override
public int insertBlogArticle(BlogArticleVo bVo) {
return blogArticleDaoImpl.insertBlogArticle(bVo);
}
@Override
public int updateBlogReadById(int blogId) {
return blogArticleDaoImpl.updateBlogReadById(blogId);
}
@Override
public int updateBlogById(BlogArticleVo bVo) {
return blogArticleDaoImpl.updateBlogById(bVo);
}
@Override
public int logicDeleteBlogById(int blogId) {
return blogArticleDaoImpl.logicDeleteBlogById(blogId);
}
@Override
public ArrayList<BlogArticleVo> queryAllBlogArticles() {
return blogArticleDaoImpl.queryAllBlogArticles();
}
@Override
public BlogArticleVo queryPreviousBlog(int blogId) {
return blogArticleDaoImpl.queryPreviousBlog(blogId);
}
@Override
public BlogArticleVo queryNextBlog(int blogId) {
return blogArticleDaoImpl.queryNextBlog(blogId);
}
} | Humsen/web/web-core/src/pers/husen/web/service/BlogArticleSvc.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/service/BlogArticleSvc.java",
"repo_id": "Humsen",
"token_count": 611
} | 31 |
package pers.husen.web.servlet.common;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import pers.husen.web.bean.po.AccessAtatisticsPo;
/**
* 获取网站访问统计
*
* @author 何明胜
*
* 2017年10月18日
*/
@WebServlet(urlPatterns="/accessAtatistics.hms")
public class AccessAtatisticsSvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public AccessAtatisticsSvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
AccessAtatisticsPo aPo = new AccessAtatisticsPo();
aPo.setAccessToday((int) this.getServletContext().getAttribute("visitToday"));
aPo.setAccessTotal((int) this.getServletContext().getAttribute("visitTotal"));
aPo.setOnlineCurrent((int) this.getServletContext().getAttribute("onlineCount"));
String json = JSONObject.fromObject(aPo).toString();
PrintWriter out = response.getWriter();
out.println(json);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/common/AccessAtatisticsSvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/common/AccessAtatisticsSvt.java",
"repo_id": "Humsen",
"token_count": 534
} | 32 |
package pers.husen.web.servlet.userinfo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pers.husen.web.bean.vo.UserInfoVo;
import pers.husen.web.common.constants.RequestConstants;
import pers.husen.web.common.helper.RandomCodeHelper;
import pers.husen.web.common.helper.SendEmailHelper;
import pers.husen.web.service.UserInfoSvc;
/**
* 用户信息操作, 带有验证码操作
*
* @author 何明胜
*
* 2017年10月20日
*/
@WebServlet(urlPatterns = "/userInfo/code.hms")
public class UserInfoCodeSvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public UserInfoCodeSvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Logger logger = LogManager.getLogger(UserInfoCodeSvt.class.getName());
PrintWriter out = response.getWriter();
String operationType = request.getParameter("type");
//如果请求类型为null,说明异常,返回
if(operationType == null) {
out.println(-1);
return;
}
/** 如果为请求发送验证码 */
if (operationType.contains(RequestConstants.REQUEST_TYPE_SEND_CODE)) {
String email = request.getParameter("email");
int randomCode = RandomCodeHelper.producedRandomCode(6);
SendEmailHelper sendEmail = new SendEmailHelper();
int result = 0;
// 如果是找回密码发送验证码
if (operationType.contains(RequestConstants.MODE_RETRIVE_PWD)) {
result = sendEmail.sendEmail2RetrievePwd(email, randomCode);
request.getSession().setAttribute("random_code_retrive", randomCode);
logger.info("验证码暂存:[" + randomCode + "],成功设置找回密码验证码至session属性");
out.println(result);
return;
}
// 如果是注册发送验证码
if (operationType.contains(RequestConstants.MODE_REGISTER)) {
result = sendEmail.sendEmail2Register(email, randomCode);
request.getSession().setAttribute("random_code_register", randomCode);
logger.info("验证码暂存:[" + randomCode + "],成功设置注册用户验证码至session属性");
out.println(result);
return;
}
// 如果是修改邮箱验证原邮箱,发送验证码
if (operationType.contains(RequestConstants.MODE_OLD_EMAIL)) {
result = sendEmail.sendEmail2ModifyEmailAuth(email, randomCode);
request.getSession().setAttribute("random_code_modify_email_auth", randomCode);
logger.info("验证码暂存:[" + randomCode + "],成功设置修改邮箱验证旧邮箱验证码至session属性");
System.out.println(result);
out.println(result);
return;
}
// 如果是修改邮箱绑定新邮箱,发送验证码
if (operationType.contains(RequestConstants.MODE_BIND_EMAIL)) {
result = sendEmail.sendEmail2ModifyEmailBind(email, randomCode);
request.getSession().setAttribute("random_code_modify_email_bind", randomCode);
logger.info("验证码暂存:[" + randomCode + "],成功设置修改邮箱验证新邮箱验证码至session属性");
out.println(result);
return;
}
}
/** 如果为校验验证码 */
if (operationType.contains(RequestConstants.REQUEST_TYPE_AUTH_CODE)) {
String randomCodeFromUser = request.getParameter("randomCode");
Object randomCodeFromSession = 0;
String type = request.getParameter("type");
// 如果是找回密码校验
if (operationType.contains(RequestConstants.MODE_RETRIVE_PWD)) {
randomCodeFromSession = request.getSession().getAttribute("random_code_retrive");
if (String.valueOf(randomCodeFromSession).equals(randomCodeFromUser)) {
logger.info("验证码:" + randomCodeFromUser + " 校验成功,校验类型:" + type);
String userName = request.getParameter("userName");
String email = request.getParameter("email");
UserInfoVo uVo = new UserInfoVo();
uVo.setUserName(userName);
uVo.setUserEmail(email);
uVo.setUserPassword("123456");
UserInfoSvc uSvc = new UserInfoSvc();
int result = uSvc.updateUserPwdByNameAndEmail(uVo);
out.println(result);
} else {
logger.info("验证码校验失败,校验类型:" + type + ",用户验证码:" + randomCodeFromUser + ",session验证码:"
+ randomCodeFromSession);
out.println(0);
}
return;
}
// 如果是用户注册校验
if (operationType.contains(RequestConstants.MODE_REGISTER)) {
randomCodeFromSession = request.getSession().getAttribute("random_code_register");
if (String.valueOf(randomCodeFromSession).equals(randomCodeFromUser)) {
logger.info("验证码:" + randomCodeFromUser + " 校验成功,校验类型:" + type);
out.println(1);
} else {
logger.info("验证码校验失败,校验类型:" + type + ",用户验证码:" + randomCodeFromUser + ",session验证码:" + randomCodeFromSession);
out.println(0);
}
return;
}
// 如果是修改邮箱认证旧邮箱
if (operationType.contains(RequestConstants.MODE_OLD_EMAIL)) {
randomCodeFromSession = request.getSession().getAttribute("random_code_modify_email_auth");
if (String.valueOf(randomCodeFromSession).equals(randomCodeFromUser)) {
logger.info("验证码:" + randomCodeFromUser + " 校验成功,校验类型:" + type);
out.println(1);
} else {
logger.info("验证码校验失败,校验类型:" + type + ",用户验证码:" + randomCodeFromUser + ",session验证码:"
+ randomCodeFromSession);
out.println(0);
}
return;
}
// 如果是修改邮箱绑定新邮箱
if (operationType.contains(RequestConstants.MODE_BIND_EMAIL)) {
randomCodeFromSession = request.getSession().getAttribute("random_code_modify_email_bind");
if (String.valueOf(randomCodeFromSession).equals(randomCodeFromUser)) {
logger.info("验证码:" + randomCodeFromUser + " 校验成功,校验类型:" + type);
String userName = request.getParameter("username");
String email = request.getParameter("email");
UserInfoVo uVo = new UserInfoVo();
uVo.setUserName(userName);
uVo.setUserEmail(email);
UserInfoSvc uSvc = new UserInfoSvc();
int result = uSvc.updateUserEmailByName(uVo);
out.println(result);
} else {
logger.info("验证码校验失败,校验类型:" + type + ",用户验证码:" + randomCodeFromUser + ",session验证码:"
+ randomCodeFromSession);
out.println(0);
}
}
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/userinfo/UserInfoCodeSvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/userinfo/UserInfoCodeSvt.java",
"repo_id": "Humsen",
"token_count": 3216
} | 33 |
@charset "UTF-8";
.cmt-text {
font-size: 14px;
}
.meessage-input {
background-image: none;
margin: 10px 0px 10px 5px;
height: 100px;
width: 100%;
resize: none;
}
.comment-input {
background: transparent;
background-image: none;
margin: 10px 0px -10px 50px;
height: 60px;
width: 500px;
resize: none;
-moz-appearance: none;
box-shadow: none;
border: 2px solid rgba(0, 0, 0, 0.1);
font-weight: 300;
border-radius: 7px;
}
.u-button {
margin: 0px 0px 0px 10px;
}
.f-clear {
position: relative;
}
.f-float-right {
float: right;
margin-bottom: 20px;
}
.user-head {
float: left;
}
.user-float-left {
float: left;
margin-left: 20px;
}
.parent-content {
display: inline-block;
width: 100%;
margin-left: 60px;
margin-bottom: 10px;
}
li {
list-style: none;
}
.f-show {
position: absolute;
top: 0px;
right: 30px;
}
.btn-submit-commit {
margin-top: 5px !important;
margin-left: 600px !important;
}
.cmt-form {
width: 805px;
}
.commit-hr {
border: 1px dotted #036;
height: 1px;
width: 100%;
}
.commit-hr1 {
margin-right: 80px;
}
.message-head-img {
width: 40px;
height: 40px;
}
.mobile-reply {
margin: 10px 0px 10px -35px;
width: 30%;
}
.reply-div-mobile {
margin: -70px 0px 0px 200px;
}
.reply-div-pc {
margin: -50px 0px 0px 550px;
}
.cancel-reply {
display: block;
margin: 1px 0px 0px 18px;
} | Humsen/web/web-mobile/WebContent/css/message/message.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/css/message/message.css",
"repo_id": "Humsen",
"token_count": 616
} | 34 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
if (old == CodeMirror.Init) old = false;
if (!old == !val) return;
if (val) setFullscreen(cm);
else setNormal(cm);
});
function setFullscreen(cm) {
var wrap = cm.getWrapperElement();
cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
width: wrap.style.width, height: wrap.style.height};
wrap.style.width = "";
wrap.style.height = "auto";
wrap.className += " CodeMirror-fullscreen";
document.documentElement.style.overflow = "hidden";
cm.refresh();
}
function setNormal(cm) {
var wrap = cm.getWrapperElement();
wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
document.documentElement.style.overflow = "";
var info = cm.state.fullScreenRestore;
wrap.style.width = info.width; wrap.style.height = info.height;
window.scrollTo(info.scrollLeft, info.scrollTop);
cm.refresh();
}
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/display/fullscreen.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/display/fullscreen.js",
"repo_id": "Humsen",
"token_count": 559
} | 35 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.registerHelper("fold", "markdown", function(cm, start) {
var maxDepth = 100;
function isHeader(lineNo) {
var tokentype = cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0));
return tokentype && /\bheader\b/.test(tokentype);
}
function headerLevel(lineNo, line, nextLine) {
var match = line && line.match(/^#+/);
if (match && isHeader(lineNo)) return match[0].length;
match = nextLine && nextLine.match(/^[=\-]+\s*$/);
if (match && isHeader(lineNo + 1)) return nextLine[0] == "=" ? 1 : 2;
return maxDepth;
}
var firstLine = cm.getLine(start.line), nextLine = cm.getLine(start.line + 1);
var level = headerLevel(start.line, firstLine, nextLine);
if (level === maxDepth) return undefined;
var lastLineNo = cm.lastLine();
var end = start.line, nextNextLine = cm.getLine(end + 2);
while (end < lastLineNo) {
if (headerLevel(end + 1, nextLine, nextNextLine) <= level) break;
++end;
nextLine = nextNextLine;
nextNextLine = cm.getLine(end + 2);
}
return {
from: CodeMirror.Pos(start.line, firstLine.length),
to: CodeMirror.Pos(end, cm.getLine(end).length)
};
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/fold/markdown-fold.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/fold/markdown-fold.js",
"repo_id": "Humsen",
"token_count": 597
} | 36 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
// Depends on js-yaml.js from https://github.com/nodeca/js-yaml
// declare global: jsyaml
CodeMirror.registerHelper("lint", "yaml", function(text) {
var found = [];
try { jsyaml.load(text); }
catch(e) {
var loc = e.mark;
found.push({ from: CodeMirror.Pos(loc.line, loc.column), to: CodeMirror.Pos(loc.line, loc.column), message: e.message });
}
return found;
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/lint/yaml-lint.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/lint/yaml-lint.js",
"repo_id": "Humsen",
"token_count": 314
} | 37 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// Highlighting text that matches the selection
//
// Defines an option highlightSelectionMatches, which, when enabled,
// will style strings that match the selection throughout the
// document.
//
// The option can be set to true to simply enable it, or to a
// {minChars, style, wordsOnly, showToken, delay} object to explicitly
// configure it. minChars is the minimum amount of characters that should be
// selected for the behavior to occur, and style is the token style to
// apply to the matches. This will be prefixed by "cm-" to create an
// actual CSS class name. If wordsOnly is enabled, the matches will be
// highlighted only if the selected text is a word. showToken, when enabled,
// will cause the current token to be highlighted when nothing is selected.
// delay is used to specify how much time to wait, in milliseconds, before
// highlighting the matches.
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var DEFAULT_MIN_CHARS = 2;
var DEFAULT_TOKEN_STYLE = "matchhighlight";
var DEFAULT_DELAY = 100;
var DEFAULT_WORDS_ONLY = false;
function State(options) {
if (typeof options == "object") {
this.minChars = options.minChars;
this.style = options.style;
this.showToken = options.showToken;
this.delay = options.delay;
this.wordsOnly = options.wordsOnly;
}
if (this.style == null) this.style = DEFAULT_TOKEN_STYLE;
if (this.minChars == null) this.minChars = DEFAULT_MIN_CHARS;
if (this.delay == null) this.delay = DEFAULT_DELAY;
if (this.wordsOnly == null) this.wordsOnly = DEFAULT_WORDS_ONLY;
this.overlay = this.timeout = null;
}
CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
var over = cm.state.matchHighlighter.overlay;
if (over) cm.removeOverlay(over);
clearTimeout(cm.state.matchHighlighter.timeout);
cm.state.matchHighlighter = null;
cm.off("cursorActivity", cursorActivity);
}
if (val) {
cm.state.matchHighlighter = new State(val);
highlightMatches(cm);
cm.on("cursorActivity", cursorActivity);
}
});
function cursorActivity(cm) {
var state = cm.state.matchHighlighter;
clearTimeout(state.timeout);
state.timeout = setTimeout(function() {highlightMatches(cm);}, state.delay);
}
function highlightMatches(cm) {
cm.operation(function() {
var state = cm.state.matchHighlighter;
if (state.overlay) {
cm.removeOverlay(state.overlay);
state.overlay = null;
}
if (!cm.somethingSelected() && state.showToken) {
var re = state.showToken === true ? /[\w$]/ : state.showToken;
var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start;
while (start && re.test(line.charAt(start - 1))) --start;
while (end < line.length && re.test(line.charAt(end))) ++end;
if (start < end)
cm.addOverlay(state.overlay = makeOverlay(line.slice(start, end), re, state.style));
return;
}
var from = cm.getCursor("from"), to = cm.getCursor("to");
if (from.line != to.line) return;
if (state.wordsOnly && !isWord(cm, from, to)) return;
var selection = cm.getRange(from, to).replace(/^\s+|\s+$/g, "");
if (selection.length >= state.minChars)
cm.addOverlay(state.overlay = makeOverlay(selection, false, state.style));
});
}
function isWord(cm, from, to) {
var str = cm.getRange(from, to);
if (str.match(/^\w+$/) !== null) {
if (from.ch > 0) {
var pos = {line: from.line, ch: from.ch - 1};
var chr = cm.getRange(pos, from);
if (chr.match(/\W/) === null) return false;
}
if (to.ch < cm.getLine(from.line).length) {
var pos = {line: to.line, ch: to.ch + 1};
var chr = cm.getRange(to, pos);
if (chr.match(/\W/) === null) return false;
}
return true;
} else return false;
}
function boundariesAround(stream, re) {
return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) &&
(stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos)));
}
function makeOverlay(query, hasBoundary, style) {
return {token: function(stream) {
if (stream.match(query) &&
(!hasBoundary || boundariesAround(stream, hasBoundary)))
return style;
stream.next();
stream.skipTo(query.charAt(0)) || stream.skipToEnd();
}};
}
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/search/match-highlighter.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/search/match-highlighter.js",
"repo_id": "Humsen",
"token_count": 1902
} | 38 |
/*!
// CodeMirror v5.0, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// This is CodeMirror (http://codemirror.net), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .
*/
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
color: black;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumbers {}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-guttermarker { color: black; }
.CodeMirror-guttermarker-subtle { color: #999; }
/* CURSOR */
.CodeMirror div.CodeMirror-cursor {
border-left: 1px solid black;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.CodeMirror.cm-fat-cursor div.CodeMirror-cursor {
width: auto;
border: 0;
background: #7e7;
}
.CodeMirror.cm-fat-cursor div.CodeMirror-cursors {
z-index: 1;
}
.cm-animate-fat-cursor {
width: auto;
border: 0;
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
}
@-moz-keyframes blink {
0% { background: #7e7; }
50% { background: none; }
100% { background: #7e7; }
}
@-webkit-keyframes blink {
0% { background: #7e7; }
50% { background: none; }
100% { background: #7e7; }
}
@keyframes blink {
0% { background: #7e7; }
50% { background: none; }
100% { background: #7e7; }
}
/* Can style cursor different in overwrite (non-insert) mode */
div.CodeMirror-overwrite div.CodeMirror-cursor {}
.cm-tab { display: inline-block; text-decoration: inherit; }
.CodeMirror-ruler {
border-left: 1px solid #ccc;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-keyword {color: #708;}
.cm-s-default .cm-atom {color: #219;}
.cm-s-default .cm-number {color: #164;}
.cm-s-default .cm-def {color: #00f;}
.cm-s-default .cm-variable,
.cm-s-default .cm-punctuation,
.cm-s-default .cm-property,
.cm-s-default .cm-operator {}
.cm-s-default .cm-variable-2 {color: #05a;}
.cm-s-default .cm-variable-3 {color: #085;}
.cm-s-default .cm-comment {color: #a50;}
.cm-s-default .cm-string {color: #a11;}
.cm-s-default .cm-string-2 {color: #f50;}
.cm-s-default .cm-meta {color: #555;}
.cm-s-default .cm-qualifier {color: #555;}
.cm-s-default .cm-builtin {color: #30a;}
.cm-s-default .cm-bracket {color: #997;}
.cm-s-default .cm-tag {color: #170;}
.cm-s-default .cm-attribute {color: #00c;}
.cm-s-default .cm-header {color: blue;}
.cm-s-default .cm-quote {color: #090;}
.cm-s-default .cm-hr {color: #999;}
.cm-s-default .cm-link {color: #00c;}
.cm-negative {color: #d44;}
.cm-positive {color: #292;}
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}
.cm-strikethrough {text-decoration: line-through;}
.cm-s-default .cm-error {color: #f00;}
.cm-invalidchar {color: #f00;}
/* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
.CodeMirror-activeline-background {background: #e8f2ff;}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
position: relative;
overflow: hidden;
background: white;
}
.CodeMirror-scroll {
overflow: scroll !important; /* Things will break if this is overridden */
/* 30px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -30px; margin-right: -30px;
padding-bottom: 30px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-sizer {
position: relative;
border-right: 30px solid transparent;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actuall scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
}
.CodeMirror-vscrollbar {
right: 0; top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0; left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0; bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0; bottom: 0;
}
.CodeMirror-gutters {
position: absolute; left: 0; top: 0;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
-moz-box-sizing: content-box;
box-sizing: content-box;
display: inline-block;
margin-bottom: -30px;
/* Hack to make IE7 behave */
*zoom:1;
*display:inline;
}
.CodeMirror-gutter-wrapper {
position: absolute;
z-index: 4;
height: 100%;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-gutter-wrapper {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.CodeMirror-lines {
cursor: text;
min-height: 1px; /* prevents collapsing before first draw */
}
.CodeMirror pre {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
-webkit-tap-highlight-color: transparent;
}
.CodeMirror-wrap pre {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
overflow: auto;
}
.CodeMirror-widget {}
.CodeMirror-code {
outline: none;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-measure pre { position: static; }
.CodeMirror div.CodeMirror-cursor {
position: absolute;
border-right: none;
width: 0;
}
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 3;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
.CodeMirror-crosshair { cursor: crosshair; }
.CodeMirror ::selection { background: #d7d4f0; }
.CodeMirror ::-moz-selection { background: #d7d4f0; }
.cm-searching {
background: #ffa;
background: rgba(255, 255, 0, .4);
}
/* IE7 hack to prevent it from returning funny offsetTops on the spans */
.CodeMirror span { *vertical-align: text-bottom; }
/* Used to force a border model for a node */
.cm-force-border { padding-right: .1px; }
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
/* See issue #2901 */
.cm-tab-wrap-hack:after { content: ''; }
/* Help users use markselection to safely style text background */
span.CodeMirror-selectedtext { background: none; }
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/lib/codemirror.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/lib/codemirror.css",
"repo_id": "Humsen",
"token_count": 3030
} | 39 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("diff", function() {
var TOKEN_NAMES = {
'+': 'positive',
'-': 'negative',
'@': 'meta'
};
return {
token: function(stream) {
var tw_pos = stream.string.search(/[\t ]+?$/);
if (!stream.sol() || tw_pos === 0) {
stream.skipToEnd();
return ("error " + (
TOKEN_NAMES[stream.string.charAt(0)] || '')).replace(/ $/, '');
}
var token_name = TOKEN_NAMES[stream.peek()] || stream.skipToEnd();
if (tw_pos === -1) {
stream.skipToEnd();
} else {
stream.pos = tw_pos;
}
return token_name;
}
};
});
CodeMirror.defineMIME("text/x-diff", "diff");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/diff/diff.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/diff/diff.js",
"repo_id": "Humsen",
"token_count": 481
} | 40 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("groovy", function(config) {
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var keywords = words(
"abstract as assert boolean break byte case catch char class const continue def default " +
"do double else enum extends final finally float for goto if implements import in " +
"instanceof int interface long native new package private protected public return " +
"short static strictfp super switch synchronized threadsafe throw throws transient " +
"try void volatile while");
var blockKeywords = words("catch class do else finally for if switch try while enum interface def");
var atoms = words("null true false this");
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'") {
return startString(ch, stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null;
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
if (stream.eat(/eE/)) { stream.eat(/\+\-/); stream.eatWhile(/\d/); }
return "number";
}
if (ch == "/") {
if (stream.eat("*")) {
state.tokenize.push(tokenComment);
return tokenComment(stream, state);
}
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
if (expectExpression(state.lastToken)) {
return startString(ch, stream, state);
}
}
if (ch == "-" && stream.eat(">")) {
curPunc = "->";
return null;
}
if (/[+\-*&%=<>!?|\/~]/.test(ch)) {
stream.eatWhile(/[+\-*&%=<>|~]/);
return "operator";
}
stream.eatWhile(/[\w\$_]/);
if (ch == "@") { stream.eatWhile(/[\w\$_\.]/); return "meta"; }
if (state.lastToken == ".") return "property";
if (stream.eat(":")) { curPunc = "proplabel"; return "property"; }
var cur = stream.current();
if (atoms.propertyIsEnumerable(cur)) { return "atom"; }
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "keyword";
}
return "variable";
}
tokenBase.isBase = true;
function startString(quote, stream, state) {
var tripleQuoted = false;
if (quote != "/" && stream.eat(quote)) {
if (stream.eat(quote)) tripleQuoted = true;
else return "string";
}
function t(stream, state) {
var escaped = false, next, end = !tripleQuoted;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {
if (!tripleQuoted) { break; }
if (stream.match(quote + quote)) { end = true; break; }
}
if (quote == '"' && next == "$" && !escaped && stream.eat("{")) {
state.tokenize.push(tokenBaseUntilBrace());
return "string";
}
escaped = !escaped && next == "\\";
}
if (end) state.tokenize.pop();
return "string";
}
state.tokenize.push(t);
return t(stream, state);
}
function tokenBaseUntilBrace() {
var depth = 1;
function t(stream, state) {
if (stream.peek() == "}") {
depth--;
if (depth == 0) {
state.tokenize.pop();
return state.tokenize[state.tokenize.length-1](stream, state);
}
} else if (stream.peek() == "{") {
depth++;
}
return tokenBase(stream, state);
}
t.isBase = true;
return t;
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize.pop();
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function expectExpression(last) {
return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) ||
last == "newstatement" || last == "keyword" || last == "proplabel";
}
function Context(indented, column, type, align, prev) {
this.indented = indented;
this.column = column;
this.type = type;
this.align = align;
this.prev = prev;
}
function pushContext(state, col, type) {
return state.context = new Context(state.indented, col, type, null, state.context);
}
function popContext(state) {
var t = state.context.type;
if (t == ")" || t == "]" || t == "}")
state.indented = state.context.indented;
return state.context = state.context.prev;
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: [tokenBase],
context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false),
indented: 0,
startOfLine: true,
lastToken: null
};
},
token: function(stream, state) {
var ctx = state.context;
if (stream.sol()) {
if (ctx.align == null) ctx.align = false;
state.indented = stream.indentation();
state.startOfLine = true;
// Automatic semicolon insertion
if (ctx.type == "statement" && !expectExpression(state.lastToken)) {
popContext(state); ctx = state.context;
}
}
if (stream.eatSpace()) return null;
curPunc = null;
var style = state.tokenize[state.tokenize.length-1](stream, state);
if (style == "comment") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
// Handle indentation for {x -> \n ... }
else if (curPunc == "->" && ctx.type == "statement" && ctx.prev.type == "}") {
popContext(state);
state.context.align = false;
}
else if (curPunc == "{") pushContext(state, stream.column(), "}");
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == "}") {
while (ctx.type == "statement") ctx = popContext(state);
if (ctx.type == "}") ctx = popContext(state);
while (ctx.type == "statement") ctx = popContext(state);
}
else if (curPunc == ctx.type) popContext(state);
else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
pushContext(state, stream.column(), "statement");
state.startOfLine = false;
state.lastToken = curPunc || style;
return style;
},
indent: function(state, textAfter) {
if (!state.tokenize[state.tokenize.length-1].isBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), ctx = state.context;
if (ctx.type == "statement" && !expectExpression(state.lastToken)) ctx = ctx.prev;
var closing = firstChar == ctx.type;
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : config.indentUnit);
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indented + (closing ? 0 : config.indentUnit);
},
electricChars: "{}",
fold: "brace"
};
});
CodeMirror.defineMIME("text/x-groovy", "groovy");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/groovy/groovy.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/groovy/groovy.js",
"repo_id": "Humsen",
"token_count": 3125
} | 41 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's
// CodeMirror 1 mode.
// highlights keywords, strings, comments (no leveling supported! ("[==[")), tokens, basic indenting
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("lua", function(config, parserConfig) {
var indentUnit = config.indentUnit;
function prefixRE(words) {
return new RegExp("^(?:" + words.join("|") + ")", "i");
}
function wordRE(words) {
return new RegExp("^(?:" + words.join("|") + ")$", "i");
}
var specials = wordRE(parserConfig.specials || []);
// long list of standard functions from lua manual
var builtins = wordRE([
"_G","_VERSION","assert","collectgarbage","dofile","error","getfenv","getmetatable","ipairs","load",
"loadfile","loadstring","module","next","pairs","pcall","print","rawequal","rawget","rawset","require",
"select","setfenv","setmetatable","tonumber","tostring","type","unpack","xpcall",
"coroutine.create","coroutine.resume","coroutine.running","coroutine.status","coroutine.wrap","coroutine.yield",
"debug.debug","debug.getfenv","debug.gethook","debug.getinfo","debug.getlocal","debug.getmetatable",
"debug.getregistry","debug.getupvalue","debug.setfenv","debug.sethook","debug.setlocal","debug.setmetatable",
"debug.setupvalue","debug.traceback",
"close","flush","lines","read","seek","setvbuf","write",
"io.close","io.flush","io.input","io.lines","io.open","io.output","io.popen","io.read","io.stderr","io.stdin",
"io.stdout","io.tmpfile","io.type","io.write",
"math.abs","math.acos","math.asin","math.atan","math.atan2","math.ceil","math.cos","math.cosh","math.deg",
"math.exp","math.floor","math.fmod","math.frexp","math.huge","math.ldexp","math.log","math.log10","math.max",
"math.min","math.modf","math.pi","math.pow","math.rad","math.random","math.randomseed","math.sin","math.sinh",
"math.sqrt","math.tan","math.tanh",
"os.clock","os.date","os.difftime","os.execute","os.exit","os.getenv","os.remove","os.rename","os.setlocale",
"os.time","os.tmpname",
"package.cpath","package.loaded","package.loaders","package.loadlib","package.path","package.preload",
"package.seeall",
"string.byte","string.char","string.dump","string.find","string.format","string.gmatch","string.gsub",
"string.len","string.lower","string.match","string.rep","string.reverse","string.sub","string.upper",
"table.concat","table.insert","table.maxn","table.remove","table.sort"
]);
var keywords = wordRE(["and","break","elseif","false","nil","not","or","return",
"true","function", "end", "if", "then", "else", "do",
"while", "repeat", "until", "for", "in", "local" ]);
var indentTokens = wordRE(["function", "if","repeat","do", "\\(", "{"]);
var dedentTokens = wordRE(["end", "until", "\\)", "}"]);
var dedentPartial = prefixRE(["end", "until", "\\)", "}", "else", "elseif"]);
function readBracket(stream) {
var level = 0;
while (stream.eat("=")) ++level;
stream.eat("[");
return level;
}
function normal(stream, state) {
var ch = stream.next();
if (ch == "-" && stream.eat("-")) {
if (stream.eat("[") && stream.eat("["))
return (state.cur = bracketed(readBracket(stream), "comment"))(stream, state);
stream.skipToEnd();
return "comment";
}
if (ch == "\"" || ch == "'")
return (state.cur = string(ch))(stream, state);
if (ch == "[" && /[\[=]/.test(stream.peek()))
return (state.cur = bracketed(readBracket(stream), "string"))(stream, state);
if (/\d/.test(ch)) {
stream.eatWhile(/[\w.%]/);
return "number";
}
if (/[\w_]/.test(ch)) {
stream.eatWhile(/[\w\\\-_.]/);
return "variable";
}
return null;
}
function bracketed(level, style) {
return function(stream, state) {
var curlev = null, ch;
while ((ch = stream.next()) != null) {
if (curlev == null) {if (ch == "]") curlev = 0;}
else if (ch == "=") ++curlev;
else if (ch == "]" && curlev == level) { state.cur = normal; break; }
else curlev = null;
}
return style;
};
}
function string(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped) break;
escaped = !escaped && ch == "\\";
}
if (!escaped) state.cur = normal;
return "string";
};
}
return {
startState: function(basecol) {
return {basecol: basecol || 0, indentDepth: 0, cur: normal};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
var style = state.cur(stream, state);
var word = stream.current();
if (style == "variable") {
if (keywords.test(word)) style = "keyword";
else if (builtins.test(word)) style = "builtin";
else if (specials.test(word)) style = "variable-2";
}
if ((style != "comment") && (style != "string")){
if (indentTokens.test(word)) ++state.indentDepth;
else if (dedentTokens.test(word)) --state.indentDepth;
}
return style;
},
indent: function(state, textAfter) {
var closing = dedentPartial.test(textAfter);
return state.basecol + indentUnit * (state.indentDepth - (closing ? 1 : 0));
},
lineComment: "--",
blockCommentStart: "--[[",
blockCommentEnd: "]]"
};
});
CodeMirror.defineMIME("text/x-lua", "lua");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/lua/lua.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/lua/lua.js",
"repo_id": "Humsen",
"token_count": 2329
} | 42 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("properties", function() {
return {
token: function(stream, state) {
var sol = stream.sol() || state.afterSection;
var eol = stream.eol();
state.afterSection = false;
if (sol) {
if (state.nextMultiline) {
state.inMultiline = true;
state.nextMultiline = false;
} else {
state.position = "def";
}
}
if (eol && ! state.nextMultiline) {
state.inMultiline = false;
state.position = "def";
}
if (sol) {
while(stream.eatSpace());
}
var ch = stream.next();
if (sol && (ch === "#" || ch === "!" || ch === ";")) {
state.position = "comment";
stream.skipToEnd();
return "comment";
} else if (sol && ch === "[") {
state.afterSection = true;
stream.skipTo("]"); stream.eat("]");
return "header";
} else if (ch === "=" || ch === ":") {
state.position = "quote";
return null;
} else if (ch === "\\" && state.position === "quote") {
if (stream.next() !== "u") { // u = Unicode sequence \u1234
// Multiline value
state.nextMultiline = true;
}
}
return state.position;
},
startState: function() {
return {
position : "def", // Current position, "def", "quote" or "comment"
nextMultiline : false, // Is the next line multiline value
inMultiline : false, // Is the current line a multiline value
afterSection : false // Did we just open a section
};
}
};
});
CodeMirror.defineMIME("text/x-properties", "properties");
CodeMirror.defineMIME("text/x-ini", "properties");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/properties/properties.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/properties/properties.js",
"repo_id": "Humsen",
"token_count": 936
} | 43 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// Slim Highlighting for CodeMirror copyright (c) HicknHack Software Gmbh
(function() {
var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, "slim");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
// Requires at least one media query
MT("elementName",
"[tag h1] Hey There");
MT("oneElementPerLine",
"[tag h1] Hey There .h2");
MT("idShortcut",
"[attribute&def #test] Hey There");
MT("tagWithIdShortcuts",
"[tag h1][attribute&def #test] Hey There");
MT("classShortcut",
"[attribute&qualifier .hello] Hey There");
MT("tagWithIdAndClassShortcuts",
"[tag h1][attribute&def #test][attribute&qualifier .hello] Hey There");
MT("docType",
"[keyword doctype] xml");
MT("comment",
"[comment / Hello WORLD]");
MT("notComment",
"[tag h1] This is not a / comment ");
MT("attributes",
"[tag a]([attribute title]=[string \"test\"]) [attribute href]=[string \"link\"]}");
MT("multiLineAttributes",
"[tag a]([attribute title]=[string \"test\"]",
" ) [attribute href]=[string \"link\"]}");
MT("htmlCode",
"[tag&bracket <][tag h1][tag&bracket >]Title[tag&bracket </][tag h1][tag&bracket >]");
MT("rubyBlock",
"[operator&special =][variable-2 @item]");
MT("selectorRubyBlock",
"[tag a][attribute&qualifier .test][operator&special =] [variable-2 @item]");
MT("nestedRubyBlock",
"[tag a]",
" [operator&special =][variable puts] [string \"test\"]");
MT("multilinePlaintext",
"[tag p]",
" | Hello,",
" World");
MT("multilineRuby",
"[tag p]",
" [comment /# this is a comment]",
" [comment and this is a comment too]",
" | Date/Time",
" [operator&special -] [variable now] [operator =] [tag DateTime][operator .][property now]",
" [tag strong][operator&special =] [variable now]",
" [operator&special -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][property parse]([string \"December 31, 2006\"])",
" [operator&special =][string \"Happy\"]",
" [operator&special =][string \"Belated\"]",
" [operator&special =][string \"Birthday\"]");
MT("multilineComment",
"[comment /]",
" [comment Multiline]",
" [comment Comment]");
MT("hamlAfterRubyTag",
"[attribute&qualifier .block]",
" [tag strong][operator&special =] [variable now]",
" [attribute&qualifier .test]",
" [operator&special =][variable now]",
" [attribute&qualifier .right]");
MT("stretchedRuby",
"[operator&special =] [variable puts] [string \"Hello\"],",
" [string \"World\"]");
MT("interpolationInHashAttribute",
"[tag div]{[attribute id] = [string \"]#{[variable test]}[string _]#{[variable ting]}[string \"]} test");
MT("interpolationInHTMLAttribute",
"[tag div]([attribute title]=[string \"]#{[variable test]}[string _]#{[variable ting]()}[string \"]) Test");
})();
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/slim/test.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/slim/test.js",
"repo_id": "Humsen",
"token_count": 1182
} | 44 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
/***
|''Name''|tiddlywiki.js|
|''Description''|Enables TiddlyWikiy syntax highlighting using CodeMirror|
|''Author''|PMario|
|''Version''|0.1.7|
|''Status''|''stable''|
|''Source''|[[GitHub|https://github.com/pmario/CodeMirror2/blob/tw-syntax/mode/tiddlywiki]]|
|''Documentation''|http://codemirror.tiddlyspace.com/|
|''License''|[[MIT License|http://www.opensource.org/licenses/mit-license.php]]|
|''CoreVersion''|2.5.0|
|''Requires''|codemirror.js|
|''Keywords''|syntax highlighting color code mirror codemirror|
! Info
CoreVersion parameter is needed for TiddlyWiki only!
***/
//{{{
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("tiddlywiki", function () {
// Tokenizer
var textwords = {};
var keywords = function () {
function kw(type) {
return { type: type, style: "macro"};
}
return {
"allTags": kw('allTags'), "closeAll": kw('closeAll'), "list": kw('list'),
"newJournal": kw('newJournal'), "newTiddler": kw('newTiddler'),
"permaview": kw('permaview'), "saveChanges": kw('saveChanges'),
"search": kw('search'), "slider": kw('slider'), "tabs": kw('tabs'),
"tag": kw('tag'), "tagging": kw('tagging'), "tags": kw('tags'),
"tiddler": kw('tiddler'), "timeline": kw('timeline'),
"today": kw('today'), "version": kw('version'), "option": kw('option'),
"with": kw('with'),
"filter": kw('filter')
};
}();
var isSpaceName = /[\w_\-]/i,
reHR = /^\-\-\-\-+$/, // <hr>
reWikiCommentStart = /^\/\*\*\*$/, // /***
reWikiCommentStop = /^\*\*\*\/$/, // ***/
reBlockQuote = /^<<<$/,
reJsCodeStart = /^\/\/\{\{\{$/, // //{{{ js block start
reJsCodeStop = /^\/\/\}\}\}$/, // //}}} js stop
reXmlCodeStart = /^<!--\{\{\{-->$/, // xml block start
reXmlCodeStop = /^<!--\}\}\}-->$/, // xml stop
reCodeBlockStart = /^\{\{\{$/, // {{{ TW text div block start
reCodeBlockStop = /^\}\}\}$/, // }}} TW text stop
reUntilCodeStop = /.*?\}\}\}/;
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp;
content = cont;
return style;
}
function jsTokenBase(stream, state) {
var sol = stream.sol(), ch;
state.block = false; // indicates the start of a code block.
ch = stream.peek(); // don't eat, to make matching simpler
// check start of blocks
if (sol && /[<\/\*{}\-]/.test(ch)) {
if (stream.match(reCodeBlockStart)) {
state.block = true;
return chain(stream, state, twTokenCode);
}
if (stream.match(reBlockQuote)) {
return ret('quote', 'quote');
}
if (stream.match(reWikiCommentStart) || stream.match(reWikiCommentStop)) {
return ret('code', 'comment');
}
if (stream.match(reJsCodeStart) || stream.match(reJsCodeStop) || stream.match(reXmlCodeStart) || stream.match(reXmlCodeStop)) {
return ret('code', 'comment');
}
if (stream.match(reHR)) {
return ret('hr', 'hr');
}
} // sol
ch = stream.next();
if (sol && /[\/\*!#;:>|]/.test(ch)) {
if (ch == "!") { // tw header
stream.skipToEnd();
return ret("header", "header");
}
if (ch == "*") { // tw list
stream.eatWhile('*');
return ret("list", "comment");
}
if (ch == "#") { // tw numbered list
stream.eatWhile('#');
return ret("list", "comment");
}
if (ch == ";") { // definition list, term
stream.eatWhile(';');
return ret("list", "comment");
}
if (ch == ":") { // definition list, description
stream.eatWhile(':');
return ret("list", "comment");
}
if (ch == ">") { // single line quote
stream.eatWhile(">");
return ret("quote", "quote");
}
if (ch == '|') {
return ret('table', 'header');
}
}
if (ch == '{' && stream.match(/\{\{/)) {
return chain(stream, state, twTokenCode);
}
// rudimentary html:// file:// link matching. TW knows much more ...
if (/[hf]/i.test(ch)) {
if (/[ti]/i.test(stream.peek()) && stream.match(/\b(ttps?|tp|ile):\/\/[\-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i)) {
return ret("link", "link");
}
}
// just a little string indicator, don't want to have the whole string covered
if (ch == '"') {
return ret('string', 'string');
}
if (ch == '~') { // _no_ CamelCase indicator should be bold
return ret('text', 'brace');
}
if (/[\[\]]/.test(ch)) { // check for [[..]]
if (stream.peek() == ch) {
stream.next();
return ret('brace', 'brace');
}
}
if (ch == "@") { // check for space link. TODO fix @@...@@ highlighting
stream.eatWhile(isSpaceName);
return ret("link", "link");
}
if (/\d/.test(ch)) { // numbers
stream.eatWhile(/\d/);
return ret("number", "number");
}
if (ch == "/") { // tw invisible comment
if (stream.eat("%")) {
return chain(stream, state, twTokenComment);
}
else if (stream.eat("/")) { //
return chain(stream, state, twTokenEm);
}
}
if (ch == "_") { // tw underline
if (stream.eat("_")) {
return chain(stream, state, twTokenUnderline);
}
}
// strikethrough and mdash handling
if (ch == "-") {
if (stream.eat("-")) {
// if strikethrough looks ugly, change CSS.
if (stream.peek() != ' ')
return chain(stream, state, twTokenStrike);
// mdash
if (stream.peek() == ' ')
return ret('text', 'brace');
}
}
if (ch == "'") { // tw bold
if (stream.eat("'")) {
return chain(stream, state, twTokenStrong);
}
}
if (ch == "<") { // tw macro
if (stream.eat("<")) {
return chain(stream, state, twTokenMacro);
}
}
else {
return ret(ch);
}
// core macro handling
stream.eatWhile(/[\w\$_]/);
var word = stream.current(),
known = textwords.propertyIsEnumerable(word) && textwords[word];
return known ? ret(known.type, known.style, word) : ret("text", null, word);
} // jsTokenBase()
// tw invisible comment
function twTokenComment(stream, state) {
var maybeEnd = false,
ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = jsTokenBase;
break;
}
maybeEnd = (ch == "%");
}
return ret("comment", "comment");
}
// tw strong / bold
function twTokenStrong(stream, state) {
var maybeEnd = false,
ch;
while (ch = stream.next()) {
if (ch == "'" && maybeEnd) {
state.tokenize = jsTokenBase;
break;
}
maybeEnd = (ch == "'");
}
return ret("text", "strong");
}
// tw code
function twTokenCode(stream, state) {
var ch, sb = state.block;
if (sb && stream.current()) {
return ret("code", "comment");
}
if (!sb && stream.match(reUntilCodeStop)) {
state.tokenize = jsTokenBase;
return ret("code", "comment");
}
if (sb && stream.sol() && stream.match(reCodeBlockStop)) {
state.tokenize = jsTokenBase;
return ret("code", "comment");
}
ch = stream.next();
return (sb) ? ret("code", "comment") : ret("code", "comment");
}
// tw em / italic
function twTokenEm(stream, state) {
var maybeEnd = false,
ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = jsTokenBase;
break;
}
maybeEnd = (ch == "/");
}
return ret("text", "em");
}
// tw underlined text
function twTokenUnderline(stream, state) {
var maybeEnd = false,
ch;
while (ch = stream.next()) {
if (ch == "_" && maybeEnd) {
state.tokenize = jsTokenBase;
break;
}
maybeEnd = (ch == "_");
}
return ret("text", "underlined");
}
// tw strike through text looks ugly
// change CSS if needed
function twTokenStrike(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "-" && maybeEnd) {
state.tokenize = jsTokenBase;
break;
}
maybeEnd = (ch == "-");
}
return ret("text", "strikethrough");
}
// macro
function twTokenMacro(stream, state) {
var ch, word, known;
if (stream.current() == '<<') {
return ret('brace', 'macro');
}
ch = stream.next();
if (!ch) {
state.tokenize = jsTokenBase;
return ret(ch);
}
if (ch == ">") {
if (stream.peek() == '>') {
stream.next();
state.tokenize = jsTokenBase;
return ret("brace", "macro");
}
}
stream.eatWhile(/[\w\$_]/);
word = stream.current();
known = keywords.propertyIsEnumerable(word) && keywords[word];
if (known) {
return ret(known.type, known.style, word);
}
else {
return ret("macro", null, word);
}
}
// Interface
return {
startState: function () {
return {
tokenize: jsTokenBase,
indented: 0,
level: 0
};
},
token: function (stream, state) {
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
return style;
},
electricChars: ""
};
});
CodeMirror.defineMIME("text/x-tiddlywiki", "tiddlywiki");
});
//}}}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/tiddlywiki/tiddlywiki.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/tiddlywiki/tiddlywiki.js",
"repo_id": "Humsen",
"token_count": 4488
} | 45 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode('z80', function() {
var keywords1 = /^(exx?|(ld|cp|in)([di]r?)?|pop|push|ad[cd]|cpl|daa|dec|inc|neg|sbc|sub|and|bit|[cs]cf|x?or|res|set|r[lr]c?a?|r[lr]d|s[lr]a|srl|djnz|nop|rst|[de]i|halt|im|ot[di]r|out[di]?)\b/i;
var keywords2 = /^(call|j[pr]|ret[in]?)\b/i;
var keywords3 = /^b_?(call|jump)\b/i;
var variables1 = /^(af?|bc?|c|de?|e|hl?|l|i[xy]?|r|sp)\b/i;
var variables2 = /^(n?[zc]|p[oe]?|m)\b/i;
var errors = /^([hl][xy]|i[xy][hl]|slia|sll)\b/i;
var numbers = /^([\da-f]+h|[0-7]+o|[01]+b|\d+)\b/i;
return {
startState: function() {
return {context: 0};
},
token: function(stream, state) {
if (!stream.column())
state.context = 0;
if (stream.eatSpace())
return null;
var w;
if (stream.eatWhile(/\w/)) {
w = stream.current();
if (stream.indentation()) {
if (state.context == 1 && variables1.test(w))
return 'variable-2';
if (state.context == 2 && variables2.test(w))
return 'variable-3';
if (keywords1.test(w)) {
state.context = 1;
return 'keyword';
} else if (keywords2.test(w)) {
state.context = 2;
return 'keyword';
} else if (keywords3.test(w)) {
state.context = 3;
return 'keyword';
}
if (errors.test(w))
return 'error';
} else if (numbers.test(w)) {
return 'number';
} else {
return null;
}
} else if (stream.eat(';')) {
stream.skipToEnd();
return 'comment';
} else if (stream.eat('"')) {
while (w = stream.next()) {
if (w == '"')
break;
if (w == '\\')
stream.next();
}
return 'string';
} else if (stream.eat('\'')) {
if (stream.match(/\\?.'/))
return 'number';
} else if (stream.eat('.') || stream.sol() && stream.eat('#')) {
state.context = 4;
if (stream.eatWhile(/\w/))
return 'def';
} else if (stream.eat('$')) {
if (stream.eatWhile(/[\da-f]/i))
return 'number';
} else if (stream.eat('%')) {
if (stream.eatWhile(/[01]/))
return 'number';
} else {
stream.next();
}
return null;
}
};
});
CodeMirror.defineMIME("text/x-z80", "z80");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/z80/z80.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/z80/z80.js",
"repo_id": "Humsen",
"token_count": 1478
} | 46 |
/****************************************************************/
/* Based on mbonaci's Brackets mbo theme */
/* https://github.com/mbonaci/global/blob/master/Mbo.tmTheme */
/* Create your own: http://tmtheme-editor.herokuapp.com */
/****************************************************************/
.cm-s-mbo.CodeMirror {background: #2c2c2c; color: #ffffec;}
.cm-s-mbo div.CodeMirror-selected {background: #716C62 !important;}
.cm-s-mbo.CodeMirror ::selection { background: rgba(113, 108, 98, .99); }
.cm-s-mbo.CodeMirror ::-moz-selection { background: rgba(113, 108, 98, .99); }
.cm-s-mbo .CodeMirror-gutters {background: #4e4e4e; border-right: 0px;}
.cm-s-mbo .CodeMirror-guttermarker { color: white; }
.cm-s-mbo .CodeMirror-guttermarker-subtle { color: grey; }
.cm-s-mbo .CodeMirror-linenumber {color: #dadada;}
.cm-s-mbo .CodeMirror-cursor {border-left: 1px solid #ffffec !important;}
.cm-s-mbo span.cm-comment {color: #95958a;}
.cm-s-mbo span.cm-atom {color: #00a8c6;}
.cm-s-mbo span.cm-number {color: #00a8c6;}
.cm-s-mbo span.cm-property, .cm-s-mbo span.cm-attribute {color: #9ddfe9;}
.cm-s-mbo span.cm-keyword {color: #ffb928;}
.cm-s-mbo span.cm-string {color: #ffcf6c;}
.cm-s-mbo span.cm-string.cm-property {color: #ffffec;}
.cm-s-mbo span.cm-variable {color: #ffffec;}
.cm-s-mbo span.cm-variable-2 {color: #00a8c6;}
.cm-s-mbo span.cm-def {color: #ffffec;}
.cm-s-mbo span.cm-bracket {color: #fffffc; font-weight: bold;}
.cm-s-mbo span.cm-tag {color: #9ddfe9;}
.cm-s-mbo span.cm-link {color: #f54b07;}
.cm-s-mbo span.cm-error {border-bottom: #636363; color: #ffffec;}
.cm-s-mbo span.cm-qualifier {color: #ffffec;}
.cm-s-mbo .CodeMirror-activeline-background {background: #494b41 !important;}
.cm-s-mbo .CodeMirror-matchingbracket {color: #222 !important;}
.cm-s-mbo .CodeMirror-matchingtag {background: rgba(255, 255, 255, .37);}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/mbo.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/mbo.css",
"repo_id": "Humsen",
"token_count": 802
} | 47 |
/* Taken from the popular Visual Studio Vibrant Ink Schema */
.cm-s-vibrant-ink.CodeMirror { background: black; color: white; }
.cm-s-vibrant-ink .CodeMirror-selected { background: #35493c !important; }
.cm-s-vibrant-ink.CodeMirror ::selection { background: rgba(53, 73, 60, 0.99); }
.cm-s-vibrant-ink.CodeMirror ::-moz-selection { background: rgba(53, 73, 60, 0.99); }
.cm-s-vibrant-ink .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }
.cm-s-vibrant-ink .CodeMirror-guttermarker { color: white; }
.cm-s-vibrant-ink .CodeMirror-guttermarker-subtle { color: #d0d0d0; }
.cm-s-vibrant-ink .CodeMirror-linenumber { color: #d0d0d0; }
.cm-s-vibrant-ink .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-vibrant-ink .cm-keyword { color: #CC7832; }
.cm-s-vibrant-ink .cm-atom { color: #FC0; }
.cm-s-vibrant-ink .cm-number { color: #FFEE98; }
.cm-s-vibrant-ink .cm-def { color: #8DA6CE; }
.cm-s-vibrant-ink span.cm-variable-2, .cm-s-vibrant span.cm-tag { color: #FFC66D }
.cm-s-vibrant-ink span.cm-variable-3, .cm-s-vibrant span.cm-def { color: #FFC66D }
.cm-s-vibrant-ink .cm-operator { color: #888; }
.cm-s-vibrant-ink .cm-comment { color: gray; font-weight: bold; }
.cm-s-vibrant-ink .cm-string { color: #A5C25C }
.cm-s-vibrant-ink .cm-string-2 { color: red }
.cm-s-vibrant-ink .cm-meta { color: #D8FA3C; }
.cm-s-vibrant-ink .cm-builtin { color: #8DA6CE; }
.cm-s-vibrant-ink .cm-tag { color: #8DA6CE; }
.cm-s-vibrant-ink .cm-attribute { color: #8DA6CE; }
.cm-s-vibrant-ink .cm-header { color: #FF6400; }
.cm-s-vibrant-ink .cm-hr { color: #AEAEAE; }
.cm-s-vibrant-ink .cm-link { color: blue; }
.cm-s-vibrant-ink .cm-error { border-bottom: 1px solid red; }
.cm-s-vibrant-ink .CodeMirror-activeline-background {background: #27282E !important;}
.cm-s-vibrant-ink .CodeMirror-matchingbracket {outline:1px solid grey; color:white !important;}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/vibrant-ink.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/vibrant-ink.css",
"repo_id": "Humsen",
"token_count": 843
} | 48 |
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>留言区</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="欢迎来到何明胜的个人网站.本站主要用于记录和分享本人的学习心得和编程经验,并分享常见可复用代码、推荐书籍以及软件等资源.本站源码已托管github,欢迎访问:https://github.com/HelloHusen/web" />
<meta name="keywords" content="何明胜,何明胜的个人网站,何明胜的博客,一格的程序人生" />
<meta name="author" content="何明胜,一格">
<!-- 网站图标 -->
<link rel="shortcut icon" href="/images/favicon.ico">
<!-- jQuery -->
<script src="/plugins/jquery/js/jquery-3.2.1.min.js"></script>
<!-- 留言区css -->
<link rel="stylesheet" href="/css/message/message.css">
<!-- 分页器 -->
<link rel="stylesheet" href="/css/message/pager.css" />
<!-- 留言区js -->
<script src="/js/message/message.js"></script>
<!-- 分页器 -->
<script src="/js/message/pager.js"></script>
</head>
<body>
<input id="menuBarNo" type="hidden" value="3" />
<div id="fh5co-page">
<a href="#" class="js-fh5co-nav-toggle fh5co-nav-toggle"><i></i></a>
<input id="menuBarNo" type="hidden" value="3"/>
<!-- 左侧导航 -->
<!-- 中间内容 -->
<div id="fh5co-main">
<div id="message_box"></div>
</div>
<div id="pager"></div>
<!-- 右侧导航 -->
</div>
</body>
</html> | Humsen/web/web-mobile/WebContent/topic/message/message.html/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/topic/message/message.html",
"repo_id": "Humsen",
"token_count": 745
} | 49 |
@charset "UTF-8";
.forget-pwd {
margin-left: 12%;
}
.navbar-bottom {
text-align: center;
background-color: whitesmoke;
}
.login-title{
margin: 0;
} | Humsen/web/web-pc/WebContent/css/login/login.css/0 | {
"file_path": "Humsen/web/web-pc/WebContent/css/login/login.css",
"repo_id": "Humsen",
"token_count": 73
} | 50 |
/**
* 写新文章的js
*
* @author 何明胜
*
* 2017年9月28日
*/
/** 加载插件 * */
$.ajax({
url : '/plugins/plugins.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$($('head')[0]).find('script:first').after(data);
}
});
var article_id = -1;// 文章id,新文章默认为-1,编辑文章为相应的id
var article_type = -1; //文章类型,默认-1,博客=blog,代码=code
$(document).ready(function() {
// 判断是否超级管理员,否则不能访问
/*if ($.cookie('username') != 'husen') {
window.location.replace('/module/error/error.html');
return;
}*/
//初始化Markdown编辑区
initMarkdownEditor();
/** 判断是编辑还是新建文章,如果是编辑,加载内容 */
initInputBox();
//加载文章分类
loadCategory();
// 发布按钮点击事件
$('#btn_publish').click(btnPublishClick);
//清空编辑区按钮点击事件
$('#btn_clearEditor').click(btnClearClick);
//选择文章分类 点击事件
chooseCategory();
//添加文章分类 点击事件
addCategory();
});
/**
* 判断是编辑还是新建文章 如果是编辑,加载内容
*
* @returns
*/
function initInputBox() {
var username = $.cookie('username');
var url;
var jsonData;
if (article_id = $.getUrlParam('blogId')) {
url = '/blog.hms';
article_type = 'blog';
jsonData = 'blogId=' + article_id + '&type=json_return';
} else if ((article_id = $.getUrlParam('codeId'))) {
url = '/code.hms';
article_type = 'code';
jsonData = 'codeId=' + article_id + '&type=json_return';
}
if (article_id) {// 获取文章以供编辑
$.ajax({
type : 'POST',
async : false,
url : url,
dataType : 'json',
data : jsonData,
success : function(response) {
// 填充编辑界面
if ($.getUrlParam('blogId')) {
$('#txt_title').val(response.blogTitle);
$('#txt_summary').val(response.blogSummary);
$('#txt_editorMdContent').val(response.blogMdContent);
$('#txt_articleLabel').val(response.blogLabel);
$('input:radio[name="article"]:eq(0)').prop('checked',true);
$('#txt_curCategory').text(response.categoryName);
$('#txt_curCtegy').val(response.blogCategory);
username = response.blogAuthor;
} else {
$('#txt_title').val(response.codeTitle);
$('#txt_summary').val(response.codeSummary);
$('#txt_editorMdContent').val(response.codeMdContent);
$('#txt_articleLabel').val(response.codeLabel);
$('input:radio[name="article"]:eq(1)').prop('checked',true);
$('#txt_curCategory').text(response.categoryName);
$('#txt_curCtegy').val(response.codeCategory);
response.blogAuthor = response.codeAuthor;
}
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '查询出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
/** 填充作者信息 **/
$.ajax({
type : 'POST',
async : false,
url : '/userInfo.hms',
dataType : 'json',
data : {
type : 'query_user_info',
userName : username
},
success : function(response) {
$('#txt_author').val(response.userNickName);
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '查询出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
/**
* 初始化markdown编辑区
* @returns
*/
function initMarkdownEditor() {
editormd('div_editorMd', {
width : '100%',
height : 640,
// markdown : md,
codeFold : true,
syncScrolling : 'single',
path : '/plugins/editormd/lib/',// lib目录的路径
/*
* theme: 'dark',//工具栏主题 previewTheme: 'dark',//预览主题 editorTheme:
* 'pastel-on-dark',//编辑主题
*/
emoji : true,
taskList : true,
tocm : true, // Using [TOCM]
tex : true, // 开启科学公式TeX语言支持,默认关闭
flowChart : true, // 开启流程图支持,默认关闭
sequenceDiagram : true, // 开启时序/序列图支持,默认关闭,
saveHTMLToTextarea : true,//构造出来的HTML代码直接在第二个隐藏的textarea域中,方便post提交表单
imageUpload : true,// 启动本地图片上传功能
imageFormats : [ 'jpg', 'jpeg', 'gif', 'png', 'bmp', 'webp' ],
imageUploadURL : '/imageUpload.hms'
});
}
/**
* 校验编辑区合法性
* @returns
*/
function isEditorValid(){
var flag = true;
//标题不能为空
if($('#txt_title').val() == ""){
$('#txt_title').parent('div').parent('div').addClass('has-error');
flag = false;
}else{
$('#txt_title').parent('div').parent('div').removeClass('has-error');
}
//标签不能为空
if($('#txt_articleLabel').val() == ""){
$('#txt_articleLabel').parent('div').addClass('has-error');
flag = false;
}else{
$('#txt_articleLabel').parent('div').removeClass('has-error');
}
return flag;
}
/**
* 发布按钮点击事件
*
* @returns
*/
function btnPublishClick() {
//检验合法性
if(!isEditorValid()){
return;
}
//判断文章类型是否改变
if(article_type != -1 && article_type != isBlogOrCode()){
$.confirm({
title : '文章类型改变',
content : '您在编辑过程中改变了文章类型,是否确定?',
type : 'red',
buttons : {
ok : {
text : '确定',
btnClass : 'btn btn-danger',
keys : [ 'enter' ],
action : function() {
submitActInfo('create');
}
},
cancel : {
text : '返回修改',
btnClass : 'btn-success',
keys : [ 'ESC' ],
}
}
});
}else{
submitActInfo(article_id ? 'modify' : 'create');
}
}
/**
* 提交文章信息
* @param type
* @returns
*/
function submitActInfo(type){
// 获取文章细节
var articleData = JSON.stringify(articleDetail());
var jsonData;
$.ajax({
type : 'POST',
async : false,
url : (isBlogOrCode() == 'blog') ? '/blog/upload.hms' : '/code/upload.hms',
data : {
newArticle : articleData,
type : type ,
articleId : article_id
},
success : function(response) {
if (response != 0) {
$.confirm({
title : '上传成功',
content : '上传成功',
autoClose : 'ok|3000',
type : 'green',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
} else {
$.confirm({
title : '上传失败',
content : '上传失败',
autoClose : 'ok|3000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '上传出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
/**
* 判断是博客还是代码
* @returns
*/
function isBlogOrCode() {
return $('input:radio[name="article"]:checked').val();
}
/**
* 发布时获取文章内容详情
* @returns
*/
function articleDetail() {
var type = isBlogOrCode();
var newArticle = {};
// 获取第二个textarea的值,即生成的HTML代码 实际开发中此值存入后台数据库
var editorHtml = $('#txt_editorHtml').val();
// 获取第一个textarea的值,即md值 实际开发中此值存入后台数据库
var editormarkdown = $('#txt_editorMdContent').val();
if (type == 'blog') {
newArticle.blogTitle = $('#txt_title').val();
newArticle.blogAuthor = $.cookie('username') == '' ? 'husen' : $.cookie('username');
newArticle.blogSummary = $('#txt_summary').val() == '' ? '无摘要' : $('#txt_summary').val();
newArticle.blogRead = 0;
newArticle.blogDate = $.nowDateHMS();
newArticle.blogHtmlContent = editorHtml == '' ? '暂无内容' : editorHtml;
newArticle.blogMdContent = editormarkdown;
newArticle.blogLabel = $('#txt_articleLabel').val();
newArticle.blogCategory = $('#txt_curCtegy').val();
} else if (type == 'code') {
newArticle.codeTitle = $('#txt_title').val();
newArticle.codeAuthor = $.cookie('username') == '' ? 'husen' : $.cookie('username');
newArticle.codeSummary = $('#txt_summary').val() == '' ? '无摘要' : $('#txt_summary').val();
newArticle.codeRead = 0;
newArticle.codeDate = $.nowDateHMS();
newArticle.codeHtmlContent = editorHtml == '' ? '暂无内容' : editorHtml;
newArticle.codeMdContent = editormarkdown;
newArticle.codeLabel = $('#txt_articleLabel').val();
newArticle.codeCategory = $('#txt_curCtegy').val();
} else {
$.confirm({
title : '获取文章出错',
content : '无法获取文章类型',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
return newArticle;
}
/**
* 清空编辑区按钮点击事件
* @returns
*/
function btnClearClick(){
$('#txt_title').val('');
$('#txt_author').val('');
$('#txt_summary').val('');
$('#txt_articleLabel').val('');
$('input:radio[name="article"]:eq(0)').prop('checked',true);
//清空内容
$('.editormd-menu li a i[name="clear"]').click();
$('#txt_curCtegy').val('');
$('#txt_curCategory').text('所有文章');
}
/**
* 选择文章分类
* @returns
*/
function chooseCategory(){
$('.dropdown-menu.category-width').children('li').click(
function() {
if(typeof $(this).attr('value') != 'undefined'){
$('#txt_curCategory').text($(this).children('a').text());
$('#txt_curCtegy').val($(this).attr('value'));
}
});
}
/**
* 添加文章分类
* @returns
*/
function addCategory(){
$('#tbl_addCategory').find('button').click(function(){
var newCategory = $('#tbl_addCategory').find('input').val();
var value = 0;
if(newCategory != ''){
//插入数据库,返回id
$.ajax({
type : 'POST',
async : false,
url : '/category.hms',
dataType : 'json',
data : {
type : 'create',
cateName : newCategory,
},
success : function(response) {
value = response;
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '添加分类出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
$('.dropdown-menu.category-width').children('.divider').before('<li value="' + value + '"><a href="#">' + newCategory + '</a></li>');
//重新注册点击事件
chooseCategory();
}
});
}
/**
* 加载文章分类
* @returns
*/
function loadCategory(){
$.ajax({
type : 'POST',
async : false,
url : '/category.hms',
dataType : 'json',
data : {
type : 'query_all',
'class' : isBlogOrCode(),
},
success : function(response) {
for(x in response){
var curCategory = response[x];
$('.dropdown-menu.category-width').children('.divider').before('<li value="' + curCategory.categoryId + '"><a href="#">' + curCategory.categoryName + '</a></li>');
}
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '查询分类出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
} | Humsen/web/web-pc/WebContent/js/editor/editor.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/js/editor/editor.js",
"repo_id": "Humsen",
"token_count": 5791
} | 51 |
# Configuration for known file extensions
[*.{css,js,json,less,md,py,rst,sass,scss,xml,yaml,yml}]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.{json,yml,yaml,rst,md}]
indent_size = 2
# Do not configure editor for libs and autogenerated content
[{*/static/{lib,src/lib}/**,*/static/description/index.html,*/readme/../README.rst}]
charset = unset
end_of_line = unset
indent_size = unset
indent_style = unset
insert_final_newline = false
trim_trailing_whitespace = false
| OCA/web/.editorconfig/0 | {
"file_path": "OCA/web/.editorconfig",
"repo_id": "OCA",
"token_count": 225
} | 52 |
/** @odoo-module **/
import {X2ManyField} from "@web/views/fields/x2many/x2many_field";
import {XMLParser} from "@web/core/utils/xml";
import {evaluateExpr} from "@web/core/py_js/py";
import {patch} from "@web/core/utils/patch";
patch(X2ManyField.prototype, "web_action_conditionable_FieldOne2Many", {
get rendererProps() {
this.updateActiveActions();
return this._super(...arguments);
},
updateActiveActions() {
if (this.viewMode === "list" && this.activeActions.type === "one2many") {
const self = this;
const parser = new XMLParser();
const archInfo = this.activeField.views[this.viewMode];
const xmlDoc = parser.parseXML(archInfo.__rawArch);
["create", "delete"].forEach(function (item) {
if (self.activeActions[item] && _.has(xmlDoc.attributes, item)) {
const expr = xmlDoc.getAttribute(item);
try {
self.activeActions[item] = evaluateExpr(
expr,
self.props.record.data
);
} catch (ignored) {
console.log(
"[web_action_conditionable] unrecognized expr '" +
expr +
"', ignoring"
);
}
}
});
}
},
});
| OCA/web/web_action_conditionable/static/src/components/field_one2many.esm.js/0 | {
"file_path": "OCA/web/web_action_conditionable/static/src/components/field_one2many.esm.js",
"repo_id": "OCA",
"token_count": 802
} | 53 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_advanced_search
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 12.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2019-09-01 12:52+0000\n"
"Last-Translator: 黎伟杰 <674416404@qq.com>\n"
"Language-Team: none\n"
"Language: zh_CN\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Generator: Weblate 3.8\n"
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/js/utils.esm.js:0
#, python-format
msgid " and "
msgstr ""
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/js/utils.esm.js:0
#, python-format
msgid " is not "
msgstr ""
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/js/utils.esm.js:0
#, python-format
msgid " or "
msgstr ""
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/search/filter_menu/advanced_filter_item.xml:0
#, python-format
msgid "Add Advanced Filter"
msgstr "添加高级过滤器"
| OCA/web/web_advanced_search/i18n/zh_CN.po/0 | {
"file_path": "OCA/web/web_advanced_search/i18n/zh_CN.po",
"repo_id": "OCA",
"token_count": 502
} | 54 |
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Copyright 2017-2018 Jairo Llopis <jairo.llopis@tecnativa.com>
Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
-->
<templates>
<t t-name="web_advanced_search.AdvancedFilterItem" owl="1">
<a
role="menuitem"
t-on-click="onClick"
class=" dropdown-item o_add_advanced_search"
> Add Advanced Filter </a>
</t>
</templates>
| OCA/web/web_advanced_search/static/src/search/filter_menu/advanced_filter_item.xml/0 | {
"file_path": "OCA/web/web_advanced_search/static/src/search/filter_menu/advanced_filter_item.xml",
"repo_id": "OCA",
"token_count": 232
} | 55 |
* `Akretion <https://akretion.com>`_:
* David BEAL <david.beal@akretion.com>
| OCA/web/web_apply_field_style/readme/CONTRIBUTORS.rst/0 | {
"file_path": "OCA/web/web_apply_field_style/readme/CONTRIBUTORS.rst",
"repo_id": "OCA",
"token_count": 36
} | 56 |
This module extends the functionality of backend calendars to support custom
slot durations and to allow you to provide more specific UX regarding event
duration and snapping.
| OCA/web/web_calendar_slot_duration/readme/DESCRIPTION.rst/0 | {
"file_path": "OCA/web/web_calendar_slot_duration/readme/DESCRIPTION.rst",
"repo_id": "OCA",
"token_count": 32
} | 57 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_chatter_position
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2023-08-07 16:10+0000\n"
"Last-Translator: \"Jan Tapper [Onestein]\" <j.tapper@onestein.nl>\n"
"Language-Team: none\n"
"Language: nl\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 4.17\n"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__bottom
msgid "Bottom"
msgstr "Onderkant"
#. module: web_chatter_position
#: model:ir.model.fields,field_description:web_chatter_position.field_res_users__chatter_position
msgid "Chatter Position"
msgstr "Chatter-positie"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__auto
msgid "Responsive"
msgstr "Snel reagerend"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__sided
msgid "Sided"
msgstr "Zijdelings"
#. module: web_chatter_position
#: model:ir.model,name:web_chatter_position.model_res_users
msgid "User"
msgstr "Gebruiker"
| OCA/web/web_chatter_position/i18n/nl.po/0 | {
"file_path": "OCA/web/web_chatter_position/i18n/nl.po",
"repo_id": "OCA",
"token_count": 531
} | 58 |
# Odoo, Open Source Web Company Color
# Copyright (C) 2019 Alexandre Díaz <dev@redneboa.es>
#
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).#
{
"name": "Web Company Color",
"category": "web",
"version": "16.0.1.2.0",
"author": "Alexandre Díaz, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/web",
"depends": ["web", "base_sparse_field"],
"data": ["view/assets.xml", "view/res_company.xml"],
"uninstall_hook": "uninstall_hook",
"post_init_hook": "post_init_hook",
"license": "AGPL-3",
"auto_install": False,
"installable": True,
}
| OCA/web/web_company_color/__manifest__.py/0 | {
"file_path": "OCA/web/web_company_color/__manifest__.py",
"repo_id": "OCA",
"token_count": 256
} | 59 |
* Jordi Ballester Alomar <jordi.ballester@forgeflow.com> (ForgeFlow)
* Lois Rilo <lois.rilo@forgeflow.com> (ForgeFlow)
* Simone Orsi <simone.orsi@camptocamp.com>
* Iván Antón <ozono@ozonomultimedia.com>
* Bernat Puig <bernat.puig@forgeflow.com> (ForgeFlow)
* Dhara Solanki <dhara.solanki@initos.com>
* `Tecnativa <https://www.tecnativa.com>`_:
* Jairo Llopis
* Alexandre Díaz
* Carlos Roca
| OCA/web/web_company_color/readme/CONTRIBUTORS.rst/0 | {
"file_path": "OCA/web/web_company_color/readme/CONTRIBUTORS.rst",
"repo_id": "OCA",
"token_count": 167
} | 60 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_copy_confirm
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: \n"
#. module: web_copy_confirm
#. odoo-javascript
#: code:addons/web_copy_confirm/static/src/js/web_copy_confirm.esm.js:0
#, python-format
msgid "Are you sure that you would like to copy this record?"
msgstr ""
#. module: web_copy_confirm
#. odoo-javascript
#: code:addons/web_copy_confirm/static/src/js/web_copy_confirm.esm.js:0
#, python-format
msgid "Duplicate"
msgstr ""
| OCA/web/web_copy_confirm/i18n/web_copy_confirm.pot/0 | {
"file_path": "OCA/web/web_copy_confirm/i18n/web_copy_confirm.pot",
"repo_id": "OCA",
"token_count": 293
} | 61 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_dark_mode
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2023-03-06 20:08+0000\n"
"Last-Translator: Ediz Duman <neps1192@gmail.com>\n"
"Language-Team: none\n"
"Language: tr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 4.14.1\n"
#. module: web_dark_mode
#. odoo-javascript
#: code:addons/web_dark_mode/static/src/js/switch_item.esm.js:0
#: model:ir.model.fields,field_description:web_dark_mode.field_res_users__dark_mode
#, python-format
msgid "Dark Mode"
msgstr "Koyu Mod"
#. module: web_dark_mode
#: model:ir.model.fields,field_description:web_dark_mode.field_res_users__dark_mode_device_dependent
msgid "Device Dependent Dark Mode"
msgstr "Cihaza Bağlı Karanlık Mod"
#. module: web_dark_mode
#: model:ir.model,name:web_dark_mode.model_ir_http
msgid "HTTP Routing"
msgstr "HTTP Yönlendirme"
#. module: web_dark_mode
#: model:ir.model,name:web_dark_mode.model_res_users
msgid "User"
msgstr "Kullanıcı"
| OCA/web/web_dark_mode/i18n/tr.po/0 | {
"file_path": "OCA/web/web_dark_mode/i18n/tr.po",
"repo_id": "OCA",
"token_count": 497
} | 62 |
==========================
Overview Dashboard (Tiles)
==========================
..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:016842e127bc74b3f446e2ae087f66e14b91670c6e567c09e69b3fc1175667da
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fweb-lightgray.png?logo=github
:target: https://github.com/OCA/web/tree/16.0/web_dashboard_tile
:alt: OCA/web
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/web-16-0/web-16-0-web_dashboard_tile
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
:target: https://runboat.odoo-community.org/builds?repo=OCA/web&target_branch=16.0
:alt: Try me on Runboat
|badge1| |badge2| |badge3| |badge4| |badge5|
This module extends the web module to add new dashboard overview system.
By default, the tile displays items count of a given model restricted to a given domain.
Optionally, the tile can display the result of a function on a field.
- Function is one of ``sum``, ``avg``, ``min``, ``max`` or ``median``.
- Field must be integer or float.
Tile can be:
- Displayed only for a user.
- Global for all users.
- Restricted to some groups.
*Note: The tile will be hidden if the current user doesn't have access to the given model.*
**Table of contents**
.. contents::
:local:
Configuration
=============
First, you have to create tile categories.
* Go to "Dashboards > Configuration > Overview Settings > Dashboard Categories"
* Create categories
Odoo menu and action are automatically created in the "Dashboard > Overview" menu
You should refresh your browser to see new menu items.
.. image:: https://raw.githubusercontent.com/OCA/web/16.0/web_dashboard_tile/static/description/tile_category_form.png
Then you can create tiles.
* Go to "Dashboards > Configuration > Overview Settings > Dashboard Items"
* create a new tile, set a name, a category and a model.
* You can optionally define colors, domain and a specific action to use.
* Setting a user, or a group in "Security" tab will restrict the display of the tile.
.. image:: https://raw.githubusercontent.com/OCA/web/16.0/web_dashboard_tile/static/description/tile_tile_form.png
You can optionally define a secondary value, for that purpose :
* Select a field, a function to apply.
* You can define a specific format. (``.format()`` python syntax)
.. image:: https://raw.githubusercontent.com/OCA/web/16.0/web_dashboard_tile/static/description/tile_tile_form_secondary_value.png
Usage
=====
* Go to "Dashboard > Overview" and select a category
* The tile configured is displayed with the up to date count and average values of the selected domain.
.. image:: https://raw.githubusercontent.com/OCA/web/16.0/web_dashboard_tile/static/description/tile_tile_kanban.png
* By clicking on the item, you'll navigate to the tree view of the according model.
.. image:: https://raw.githubusercontent.com/OCA/web/16.0/web_dashboard_tile/static/description/tile_tile_2_tree_view.png
Known issues / Roadmap
======================
**Known issues**
* Can not edit color from dashboard
* Original context is ignored.
* Original domain and filter are not restored.
* To preserve a relative date domain, you have to manually edit the tile's domain from "Configuration > User Interface > Dashboard Tile". You can use the same variables available in filters (``uid``, ``context_today()``, ``current_date``, ``relativedelta``).
**Roadmap**
* Add icons.
* Support client side action (like inbox).
* Restore original Domain + Filter when an action is set.
* Posibility to hide the tile based on a field expression.
* Posibility to set the background color based on a field expression.
Bug Tracker
===========
Bugs are tracked on `GitHub Issues <https://github.com/OCA/web/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us to smash it by providing a detailed and welcomed
`feedback <https://github.com/OCA/web/issues/new?body=module:%20web_dashboard_tile%0Aversion:%2016.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
Do not contact contributors directly about support or help with technical issues.
Credits
=======
Authors
~~~~~~~
* initOS GmbH & Co. KG
* GRAP
* Iván Todorovich <ivan.todorovich@gmail.com>
Contributors
~~~~~~~~~~~~
* Markus Schneider <markus.schneider at initos.com>
* Sylvain Le Gal (https://twitter.com/legalsylvain)
* Iván Todorovich <ivan.todorovich@gmail.com>
Maintainers
~~~~~~~~~~~
This module is maintained by the OCA.
.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
.. |maintainer-legalsylvain| image:: https://github.com/legalsylvain.png?size=40px
:target: https://github.com/legalsylvain
:alt: legalsylvain
Current `maintainer <https://odoo-community.org/page/maintainer-role>`__:
|maintainer-legalsylvain|
This module is part of the `OCA/web <https://github.com/OCA/web/tree/16.0/web_dashboard_tile>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
| OCA/web/web_dashboard_tile/README.rst/0 | {
"file_path": "OCA/web/web_dashboard_tile/README.rst",
"repo_id": "OCA",
"token_count": 1942
} | 63 |
from . import models
| OCA/web/web_dialog_size/__init__.py/0 | {
"file_path": "OCA/web/web_dialog_size/__init__.py",
"repo_id": "OCA",
"token_count": 5
} | 64 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_disable_export_group
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 12.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2020-10-16 12:08+0000\n"
"Last-Translator: Pedro Castro Silva <pedrocs@exo.pt>\n"
"Language-Team: none\n"
"Language: pt\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n > 1;\n"
"X-Generator: Weblate 3.10\n"
#. module: web_disable_export_group
#: model:ir.model,name:web_disable_export_group.model_base
msgid "Base"
msgstr ""
#. module: web_disable_export_group
#: model:res.groups,name:web_disable_export_group.group_export_xlsx_data
msgid "Direct Export (xlsx)"
msgstr ""
#. module: web_disable_export_group
#: model:ir.model,name:web_disable_export_group.model_ir_http
msgid "HTTP Routing"
msgstr "Encaminhamento HTTP"
#. module: web_disable_export_group
#. openerp-web
#: code:addons/web_disable_export_group/static/src/xml/export_xls_views.xml:0
#, python-format
msgid "widget.is_action_enabled('export_xlsx') and widget.isExportXlsEnable"
msgstr ""
#, python-format
#~ msgid "Export"
#~ msgstr "Exportar"
#~ msgid "Export Data"
#~ msgstr "Exportar Dados"
| OCA/web/web_disable_export_group/i18n/pt.po/0 | {
"file_path": "OCA/web/web_disable_export_group/i18n/pt.po",
"repo_id": "OCA",
"token_count": 510
} | 65 |
<?xml version="1.0" encoding="utf-8" ?>
<templates>
<t
t-name="web.ListView.Buttons.disbaleExport"
t-inherit="web.ListView.Buttons"
t-inherit-mode="extension"
owl="1"
>
<xpath expr="//t[contains(@t-if, 'isExportEnable')]" position="attributes">
<attribute
name="t-if"
>nbTotal and !nbSelected and activeActions.exportXlsx and isExportXlsEnable and !env.isSmall</attribute>
</xpath>
</t>
</templates>
| OCA/web/web_disable_export_group/static/src/xml/export_xls_views.xml/0 | {
"file_path": "OCA/web/web_disable_export_group/static/src/xml/export_xls_views.xml",
"repo_id": "OCA",
"token_count": 234
} | 66 |
from . import test_qunit
| OCA/web/web_domain_field/tests/__init__.py/0 | {
"file_path": "OCA/web/web_domain_field/tests/__init__.py",
"repo_id": "OCA",
"token_count": 8
} | 67 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_environment_ribbon
#
# Translators:
# OCA Transbot <transbot@odoo-community.org>, 2017
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 10.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-07-13 16:06+0000\n"
"PO-Revision-Date: 2017-07-13 16:06+0000\n"
"Last-Translator: OCA Transbot <transbot@odoo-community.org>, 2017\n"
"Language-Team: Slovenian (https://www.transifex.com/oca/teams/23907/sl/)\n"
"Language: sl\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n"
"%100==4 ? 2 : 3);\n"
#. module: web_environment_ribbon
#: model:ir.model,name:web_environment_ribbon.model_web_environment_ribbon_backend
msgid "Web Environment Ribbon Backend"
msgstr ""
#~ msgid "ID"
#~ msgstr "ID"
| OCA/web/web_environment_ribbon/i18n/sl.po/0 | {
"file_path": "OCA/web/web_environment_ribbon/i18n/sl.po",
"repo_id": "OCA",
"token_count": 377
} | 68 |
# Copyright 2019 Eric Lembregts
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
class TestEnvironmentRibbonData(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestEnvironmentRibbonData, cls).setUpClass()
cls.env["ir.config_parameter"].set_param("ribbon.name", "Test Ribbon {db_name}")
cls.env["ir.config_parameter"].set_param("ribbon.color", "#000000")
cls.env["ir.config_parameter"].set_param("ribbon.background.color", "#FFFFFF")
def test_environment_ribbon(self):
"""This test confirms that the data that is fetched by the javascript
code is the right title and colors."""
ribbon = self.env["web.environment.ribbon.backend"].get_environment_ribbon()
expected_ribbon = {
"name": "Test Ribbon {db_name}".format(db_name=self.env.cr.dbname),
"color": "#000000",
"background_color": "#FFFFFF",
}
self.assertDictEqual(ribbon, expected_ribbon)
| OCA/web/web_environment_ribbon/tests/test_environment_ribbon_data.py/0 | {
"file_path": "OCA/web/web_environment_ribbon/tests/test_environment_ribbon_data.py",
"repo_id": "OCA",
"token_count": 422
} | 69 |
{
"name": "Group Expand Buttons",
"category": "Web",
"version": "16.0.1.0.0",
"license": "AGPL-3",
"author": "OpenERP SA, "
"AvanzOSC, "
"Serv. Tecnol. Avanzados - Pedro M. Baeza, "
"Therp BV, "
"Xtendoo, "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/web",
"depends": ["web"],
"assets": {
"web.assets_backend": [
"/web_group_expand/static/src/xml/list_controller.xml",
"/web_group_expand/static/src/js/list_controller.esm.js",
],
},
}
| OCA/web/web_group_expand/__manifest__.py/0 | {
"file_path": "OCA/web/web_group_expand/__manifest__.py",
"repo_id": "OCA",
"token_count": 278
} | 70 |
{
"name": "Help Framework",
"sumamry": "This module introduces a new way to guide users",
"author": "Onestein,Odoo Community Association (OCA)",
"category": "Technical",
"license": "AGPL-3",
"version": "16.0.2.0.0",
"website": "https://github.com/OCA/web",
"depends": [
"web",
],
"assets": {
"web.assets_backend": [
"web_help/static/src/components/highlighter/highlighter.esm.js",
"web_help/static/src/components/highlighter/highlighter.scss",
"web_help/static/src/components/highlighter/highlighter.xml",
"web_help/static/src/helpers.esm.js",
"web_help/static/src/trip.esm.js",
"web_help/static/src/user_trip.esm.js",
"web_help/static/src/change_password_trip.esm.js",
"web_help/static/src/components/help_button/help_button.esm.js",
"web_help/static/src/components/help_button/help_button.xml",
"web_help/static/src/trip.xml",
]
},
}
| OCA/web/web_help/__manifest__.py/0 | {
"file_path": "OCA/web/web_help/__manifest__.py",
"repo_id": "OCA",
"token_count": 496
} | 71 |
<?xml version="1.0" encoding="UTF-8" ?>
<templates>
<t t-name="web_help.HelpButton" owl="1">
<button
class="btn ml-2 js_web_help_btn"
t-att-class="props.btnClass || 'btn-light'"
t-on-click="onClick"
tabindex="-1"
t-if="state.TripClass"
>
<i class="fa fa-question" />
</button>
</t>
<t t-inherit="web.ControlPanel.Regular" t-inherit-mode="extension">
<xpath expr="//div[hasclass('o_cp_bottom_right')]" t-operation="inside">
<nav class="btn-group">
<HelpButton
resModel="env.searchModel.resModel"
viewType="env.config.viewType"
/>
</nav>
</xpath>
</t>
<t t-inherit="web.ControlPanel.Small" t-inherit-mode="extension">
<xpath expr="//div[hasclass('o_cp_bottom_right')]" t-operation="inside">
<nav class="btn-group">
<HelpButton
resModel="env.searchModel.resModel"
viewType="env.config.viewType"
/>
</nav>
</xpath>
</t>
<t t-inherit="web.ActionDialog.header" t-inherit-mode="extension">
<xpath expr="//h4[hasclass('modal-title')]" t-operation="after">
<HelpButton
resModel="props.actionProps.resModel"
viewType="props.actionProps.type"
btnClass="env.isSmall and 'btn-link p-1 text-white' or 'btn-link p-1'"
/>
</xpath>
</t>
</templates>
| OCA/web/web_help/static/src/components/help_button/help_button.xml/0 | {
"file_path": "OCA/web/web_help/static/src/components/help_button/help_button.xml",
"repo_id": "OCA",
"token_count": 864
} | 72 |
=====================================
Window actions for client side paging
=====================================
..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:07dae326aca4830ca73888e3107f5c46bf00000bbc6c5b32be9494b495c21719
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fweb-lightgray.png?logo=github
:target: https://github.com/OCA/web/tree/16.0/web_ir_actions_act_window_page
:alt: OCA/web
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/web-16-0/web-16-0-web_ir_actions_act_window_page
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
:target: https://runboat.odoo-community.org/builds?repo=OCA/web&target_branch=16.0
:alt: Try me on Runboat
|badge1| |badge2| |badge3| |badge4| |badge5|
This addon allows a developer to return the following action types::
{'type': 'ir.actions.act_window.page.next'}
or::
{'type': 'ir.actions.act_window.page.prev'}
which trigger the form's controller to page into the requested direction on the client
side.
A use case could be the case of a validation flow. As a developer, you set up a tree
view with a domain on records to be validated. The user opens the first record in a form
view and validates the record. The validation method returns the 'next' action type so
that the browser window of the user is presented with the next record in the form view.
**Table of contents**
.. contents::
:local:
Usage
=====
See the 'Previous Partner' and 'Next Partner' buttons that this module's demo data adds
to the partner form view.
Bug Tracker
===========
Bugs are tracked on `GitHub Issues <https://github.com/OCA/web/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us to smash it by providing a detailed and welcomed
`feedback <https://github.com/OCA/web/issues/new?body=module:%20web_ir_actions_act_window_page%0Aversion:%2016.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
Do not contact contributors directly about support or help with technical issues.
Credits
=======
Authors
~~~~~~~
* Hunki Enterprises BV
* Therp BV
Contributors
~~~~~~~~~~~~
* Holger Brunn <mail@hunki-enterprises.com> (https://hunki-enterprises.com)
* Stefan Rijnhart <stefan@opener.amsterdam> (https://opener.amsterdam)
Maintainers
~~~~~~~~~~~
This module is maintained by the OCA.
.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
This module is part of the `OCA/web <https://github.com/OCA/web/tree/16.0/web_ir_actions_act_window_page>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
| OCA/web/web_ir_actions_act_window_page/README.rst/0 | {
"file_path": "OCA/web/web_ir_actions_act_window_page/README.rst",
"repo_id": "OCA",
"token_count": 1234
} | 73 |
====================
List Range Selection
====================
..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:0cd77b1cd0e10283cbf40fbf8a67f9c5c5135d746e755cf13dddf44e0f034cdb
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fweb-lightgray.png?logo=github
:target: https://github.com/OCA/web/tree/15.0/web_listview_range_select
:alt: OCA/web
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/web-15-0/web-15-0-web_listview_range_select
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
:target: https://runboat.odoo-community.org/builds?repo=OCA/web&target_branch=15.0
:alt: Try me on Runboat
|badge1| |badge2| |badge3| |badge4| |badge5|
Enables selecting a range of records using the shift key.
**Table of contents**
.. contents::
:local:
Usage
=====
To use this module, you need to:
#. Go to some list view.
#. Click a record.
#. Hold shift and click another record.
#. You can repeat this operation as many times as you want.
Known issues / Roadmap
======================
* Allow to click on the whole line (not just the checkbox) to select a row.
* Enable the same behaviour with Ctrl button.
* Shift and drag to select rows.
Bug Tracker
===========
Bugs are tracked on `GitHub Issues <https://github.com/OCA/web/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us to smash it by providing a detailed and welcomed
`feedback <https://github.com/OCA/web/issues/new?body=module:%20web_listview_range_select%0Aversion:%2015.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
Do not contact contributors directly about support or help with technical issues.
Credits
=======
Authors
~~~~~~~
* Onestein
Contributors
~~~~~~~~~~~~
* Dennis Sluijk <d.sluijk@onestein.nl>
* Aldo Soares <soares_aldo@hotmail.com>
* `Tecnativa <https://www.tecnativa.com>`_:
* Ernesto Tejeda
* Nilesh Sheliya <nilesh@synodica.com>
Maintainers
~~~~~~~~~~~
This module is maintained by the OCA.
.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
This module is part of the `OCA/web <https://github.com/OCA/web/tree/15.0/web_listview_range_select>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
| OCA/web/web_listview_range_select/README.rst/0 | {
"file_path": "OCA/web/web_listview_range_select/README.rst",
"repo_id": "OCA",
"token_count": 1173
} | 74 |
===============
web_m2x_options
===============
..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:aa5a8282ea6887deca6eea92531e25779110c8fd20fbdfef82b68e6254704418
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fweb-lightgray.png?logo=github
:target: https://github.com/OCA/web/tree/16.0/web_m2x_options
:alt: OCA/web
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/web-16-0/web-16-0-web_m2x_options
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
:target: https://runboat.odoo-community.org/builds?repo=OCA/web&target_branch=16.0
:alt: Try me on Runboat
|badge1| |badge2| |badge3| |badge4| |badge5|
This modules modifies "many2one" and "many2manytags" form widgets so as to add some new display
control options.
Options provided includes possibility to remove "Create..." and/or "Create and
Edit..." entries from many2one drop down. You can also change default number of
proposition appearing in the drop-down. Or prevent the dialog box poping in
case of validation error.
If not specified, the module will avoid proposing any of the create options
if the current user has no permission rights to create the related object.
**Table of contents**
.. contents::
:local:
Usage
=====
in the field's options dict
~~~~~~~~~~~~~~~~~~~~~~~~~~~
``create`` *boolean* (Default: depends if user have create rights)
Whether to display the "Create..." entry in dropdown panel.
``create_edit`` *boolean* (Default: depends if user have create rights)
Whether to display "Create and Edit..." entry in dropdown panel
``m2o_dialog`` *boolean* (Default: depends if user have create rights)
Whether to display the many2one dialog in case of validation error.
``limit`` *int* (Default: openerp default value is ``7``)
Number of displayed record in drop-down panel
``search_more`` *boolean*
Used to force disable/enable search more button.
``field_color`` *string*
A string to define the field used to define color.
This option has to be used with colors.
``colors`` *dictionary*
A dictionary to link field value with a HTML color.
This option has to be used with field_color.
``no_open_edit`` *boolean* (Default: value of ``no_open`` which is ``False`` if not set)
Causes a many2one not to offer to click through in edit mode, but well in read mode
``open`` *boolean* (Default: ``False``)
Makes many2many_tags and one2many rows buttons that open the linked resource
``no_color_picker`` *boolean* (Default: ``False``)
Deactivates the color picker on many2many_tags buttons to do nothing (ignored if open is set)
ir.config_parameter options
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now you can disable "Create..." and "Create and Edit..." entry for all widgets in the odoo instance.
If you disable one option, you can enable it for particular field by setting "create: True" option directly on the field definition.
``web_m2x_options.create`` *boolean* (Default: depends if user have create rights)
Whether to display the "Create..." entry in dropdown panel for all fields in the odoo instance.
``web_m2x_options.create_edit`` *boolean* (Default: depends if user have create rights)
Whether to display "Create and Edit..." entry in dropdown panel for all fields in the odoo instance.
``web_m2x_options.m2o_dialog`` *boolean* (Default: depends if user have create rights)
Whether to display the many2one dialog in case of validation error for all fields in the odoo instance.
``web_m2x_options.limit`` *int* (Default: openerp default value is ``7``)
Number of displayed record in drop-down panel for all fields in the odoo instance
``web_m2x_options.search_more`` *boolean* (Default: default value is ``False``)
Whether the field should always show "Search more..." entry or not.
``web_m2x_options.field_limit_entries`` *int*
Number of displayed lines on all One2many fields
To add these parameters go to Configuration -> Technical -> Parameters -> System Parameters and add new parameters like:
- web_m2x_options.create: False
- web_m2x_options.create_edit: False
- web_m2x_options.m2o_dialog: False
- web_m2x_options.limit: 10
- web_m2x_options.search_more: True
- web_m2x_options.field_limit_entries: 5
Example
~~~~~~~
Your XML form view definition could contain::
...
<field name="partner_id" options="{'limit': 10, 'create': false, 'create_edit': false, 'search_more':true 'field_color':'state', 'colors':{'active':'green'}}"/>
...
Known issues / Roadmap
======================
Double check that you have no inherited view that remove ``options`` you set on a field !
If nothing works, add a debugger in the first line of ``_search method`` and enable debug mode in Odoo. When you write something in a many2one field, javascript debugger should pause. If not verify your installation.
- Instead of making the tags rectangle clickable, I think it's better to put the text as a clickable link, so we will get a consistent behaviour/aspect with other clickable elements (many2one...).
- In edit mode, it would be great to add an icon like the one on many2one fields to allow to open the many2many in a popup window.
- Include this feature as a configurable option via parameter to have this behaviour by default in all many2many tags.
Bug Tracker
===========
Bugs are tracked on `GitHub Issues <https://github.com/OCA/web/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us to smash it by providing a detailed and welcomed
`feedback <https://github.com/OCA/web/issues/new?body=module:%20web_m2x_options%0Aversion:%2016.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
Do not contact contributors directly about support or help with technical issues.
Credits
=======
Authors
~~~~~~~
* initOS GmbH
* ACSONE SA/NV
* 0k.io
* Tecnativa
Contributors
~~~~~~~~~~~~
* David Coninckx <davconinckx@gmail.com>
* Emanuel Cino <ecino@compassion.ch>
* Holger Brunn <hbrunn@therp.nl>
* Nicolas JEUDY <nicolas@sudokeys.com>
* Yannick Vaucher <yannick.vaucher@camptocamp.com>
* Zakaria Makrelouf <z.makrelouf@gmail.com>
* `Tecnativa <https://www.tecnativa.com>`_:
* Jairo Llopis <jairo.llopis@tecnativa.com>
* David Vidal <david.vidal@tecnativa.com>
* Ernesto Tejeda <ernesto.tejeda87@gmail.com>
* Carlos Roca
* Bhavesh Odedra <bodedra@opensourceintegrators.com>
* Dhara Solanki <dhara.solanki@initos.com> (http://www.initos.com)
* `Trobz <https://trobz.com>`_:
* Hoang Diep <hoang@trobz.com>
Other credits
~~~~~~~~~~~~~
The migration of this module from 15.0 to 16.0 was financially supported by Camptocamp
Maintainers
~~~~~~~~~~~
This module is maintained by the OCA.
.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
This module is part of the `OCA/web <https://github.com/OCA/web/tree/16.0/web_m2x_options>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
| OCA/web/web_m2x_options/README.rst/0 | {
"file_path": "OCA/web/web_m2x_options/README.rst",
"repo_id": "OCA",
"token_count": 2550
} | 75 |
# Copyright 2020 initOS GmbH.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
class TestIrConfigParameter(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestIrConfigParameter, cls).setUpClass()
cls.env["ir.config_parameter"].set_param("web_m2x_options.limit", 10)
cls.env["ir.config_parameter"].set_param("web_m2x_options.create_edit", "True")
cls.env["ir.config_parameter"].set_param("web_m2x_options.create", "True")
cls.env["ir.config_parameter"].set_param("web_m2x_options.search_more", "False")
cls.env["ir.config_parameter"].set_param("web_m2x_options.m2o_dialog", "True")
def test_web_m2x_options_key(self):
web_m2x_options = self.env["ir.config_parameter"].get_web_m2x_options()
self.assertIn("web_m2x_options.limit", web_m2x_options)
self.assertNotIn("web_m2x_options.m2o_dialog_test", web_m2x_options)
def test_web_m2x_options_value(self):
web_m2x_options = self.env["ir.config_parameter"].get_web_m2x_options()
self.assertEqual(web_m2x_options["web_m2x_options.limit"], "10")
self.assertTrue(bool(web_m2x_options["web_m2x_options.create_edit"]))
self.assertTrue(bool(web_m2x_options["web_m2x_options.create"]))
self.assertEqual(web_m2x_options["web_m2x_options.search_more"], "False")
self.assertTrue(bool(web_m2x_options["web_m2x_options.m2o_dialog"]))
| OCA/web/web_m2x_options/tests/test_ir_config_parameter.py/0 | {
"file_path": "OCA/web/web_m2x_options/tests/test_ir_config_parameter.py",
"repo_id": "OCA",
"token_count": 664
} | 76 |
# pylint: disable=missing-docstring
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from . import models
| OCA/web/web_notify/__init__.py/0 | {
"file_path": "OCA/web/web_notify/__init__.py",
"repo_id": "OCA",
"token_count": 44
} | 77 |
This module is based on the Instant Messaging Bus. To work properly, the server must be launched in gevent mode.
| OCA/web/web_notify/readme/INSTALL.rst/0 | {
"file_path": "OCA/web/web_notify/readme/INSTALL.rst",
"repo_id": "OCA",
"token_count": 26
} | 78 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_notify_channel_message
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2023-11-27 11:34+0000\n"
"Last-Translator: mymage <stefano.consolaro@mymage.it>\n"
"Language-Team: none\n"
"Language: it\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 4.17\n"
#. module: web_notify_channel_message
#: model:ir.model,name:web_notify_channel_message.model_mail_channel
msgid "Discussion Channel"
msgstr "Canale discussione"
#. module: web_notify_channel_message
#. odoo-python
#: code:addons/web_notify_channel_message/models/mail_channel.py:0
#, python-format
msgid "You have a new message in channel %s"
msgstr "C'è un nuovo messagio nel canale %s"
| OCA/web/web_notify_channel_message/i18n/it.po/0 | {
"file_path": "OCA/web/web_notify_channel_message/i18n/it.po",
"repo_id": "OCA",
"token_count": 367
} | 79 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_pivot_computed_measure
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: \n"
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Add"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Can be empty"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Computed Measure"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Custom"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Div (m1 / m2)"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Float"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Format"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Formula"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Integer"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Measure 1"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Measure 2"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Mult (m1 * m2)"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Name"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Operation"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Perc (m1 * 100 / m2)"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Percentage"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Sub (m1 - m2)"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/dropdown_item_custom_measure/dropdown_item_custom_measure.xml:0
#, python-format
msgid "Sum (m1 + m2)"
msgstr ""
#. module: web_pivot_computed_measure
#. odoo-javascript
#: code:addons/web_pivot_computed_measure/static/src/pivot/pivot_model.esm.js:0
#, python-format
msgid ""
"This measure is currently used by a 'computed measure'. Please, disable the "
"computed measure first."
msgstr ""
| OCA/web/web_pivot_computed_measure/i18n/web_pivot_computed_measure.pot/0 | {
"file_path": "OCA/web/web_pivot_computed_measure/i18n/web_pivot_computed_measure.pot",
"repo_id": "OCA",
"token_count": 1802
} | 80 |
<?xml version="1.0" encoding="UTF-8" ?>
<templates xml:space="preserve">
<t t-inherit="web.ReportViewMeasures" t-inherit-mode="extension" owl="1">
<xpath expr="//DropdownItem" position="attributes">
<attribute name="t-if">!measure.startsWith('__computed_')</attribute>
</xpath>
<xpath expr="//t[@t-foreach='measures']" position="after">
<div role="separator" class="dropdown-divider" t-if="add_computed_measures" />
<t t-foreach="measures" t-as="measure" t-key="measure_value.name">
<DropdownItem
class="{ o_menu_item: true, selected: activeMeasures.includes(measure) }"
t-if="add_computed_measures and measure.startsWith('__computed_')"
t-esc="measures[measure].string"
parentClosingMode="'none'"
onSelected="() => this.onMeasureSelected({ measure: measure_value.name })"
/>
</t>
<DropdownItemCustomMeasure
measures="measures"
model="model"
t-if="add_computed_measures"
/>
</xpath>
</t>
</templates>
| OCA/web/web_pivot_computed_measure/static/src/view.xml/0 | {
"file_path": "OCA/web/web_pivot_computed_measure/static/src/view.xml",
"repo_id": "OCA",
"token_count": 566
} | 81 |
# Copyright 2020 Tecnativa - João Marques
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
import base64
import io
import sys
from PIL import Image
from odoo import _, api, exceptions, fields, models
from odoo.tools.mimetypes import guess_mimetype
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
_pwa_icon_url_base = "/web_pwa_oca/icon"
pwa_name = fields.Char(
"Progressive Web App Name", help="Name of the Progressive Web Application"
)
pwa_short_name = fields.Char(
"Progressive Web App Short Name",
help="Short Name of the Progressive Web Application",
)
pwa_icon = fields.Binary("Icon", readonly=False)
pwa_background_color = fields.Char("Background Color")
pwa_theme_color = fields.Char("Theme Color")
@api.model
def get_values(self):
config_parameter_obj_sudo = self.env["ir.config_parameter"].sudo()
res = super(ResConfigSettings, self).get_values()
res["pwa_name"] = config_parameter_obj_sudo.get_param(
"pwa.manifest.name", default="Odoo PWA"
)
res["pwa_short_name"] = config_parameter_obj_sudo.get_param(
"pwa.manifest.short_name", default="Odoo"
)
pwa_icon_ir_attachment = (
self.env["ir.attachment"]
.sudo()
.search([("url", "like", self._pwa_icon_url_base + ".")])
)
res["pwa_icon"] = (
pwa_icon_ir_attachment.datas if pwa_icon_ir_attachment else False
)
res["pwa_background_color"] = config_parameter_obj_sudo.get_param(
"pwa.manifest.background_color", default="#2E69B5"
)
res["pwa_theme_color"] = config_parameter_obj_sudo.get_param(
"pwa.manifest.theme_color", default="#2E69B5"
)
return res
def _unpack_icon(self, icon):
# Wrap decoded_icon in BytesIO object
decoded_icon = base64.b64decode(icon)
icon_bytes = io.BytesIO(decoded_icon)
return Image.open(icon_bytes)
def _write_icon_to_attachment(self, extension, mimetype, size=None):
url = self._pwa_icon_url_base + extension
icon = self.pwa_icon
# Resize image
if size:
image = self._unpack_icon(icon)
resized_image = image.resize(size)
icon_bytes_output = io.BytesIO()
resized_image.save(icon_bytes_output, format=extension.lstrip(".").upper())
icon = base64.b64encode(icon_bytes_output.getvalue())
url = "{}{}x{}{}".format(
self._pwa_icon_url_base,
str(size[0]),
str(size[1]),
extension,
)
# Retreive existing attachment
existing_attachment = (
self.env["ir.attachment"].sudo().search([("url", "like", url)])
)
# Write values to ir_attachment
values = {
"datas": icon,
"db_datas": icon,
"url": url,
"name": url,
"type": "binary",
"mimetype": mimetype,
}
# Rewrite if exists, else create
if existing_attachment:
existing_attachment.sudo().write(values)
else:
self.env["ir.attachment"].sudo().create(values)
@api.model
def set_values(self):
config_parameter_obj_sudo = self.env["ir.config_parameter"].sudo()
res = super(ResConfigSettings, self).set_values()
config_parameter_obj_sudo.set_param("pwa.manifest.name", self.pwa_name)
config_parameter_obj_sudo.set_param(
"pwa.manifest.short_name", self.pwa_short_name
)
config_parameter_obj_sudo.set_param(
"pwa.manifest.background_color", self.pwa_background_color
)
config_parameter_obj_sudo.set_param(
"pwa.manifest.theme_color", self.pwa_theme_color
)
# Retrieve previous value for pwa_icon from ir_attachment
pwa_icon_ir_attachments = (
self.env["ir.attachment"]
.sudo()
.search([("url", "like", self._pwa_icon_url_base)])
)
# Delete or ignore if no icon provided
if not self.pwa_icon:
if pwa_icon_ir_attachments:
pwa_icon_ir_attachments.unlink()
return res
# Fail if icon provided is larger than 2mb
if sys.getsizeof(self.pwa_icon) > 2196608:
raise exceptions.UserError(
_("You can't upload a file with more than 2 MB.")
)
# Confirm if the pwa_icon binary content is an SVG or PNG
# and process accordingly
decoded_pwa_icon = base64.b64decode(self.pwa_icon)
# Full mimetype detection
pwa_icon_mimetype = guess_mimetype(decoded_pwa_icon)
pwa_icon_extension = "." + pwa_icon_mimetype.split("/")[-1].split("+")[0]
if not pwa_icon_mimetype.startswith(
"image/svg"
) and not pwa_icon_mimetype.startswith("image/png"):
raise exceptions.UserError(
_("You can only upload SVG or PNG files. Found: %s.")
% pwa_icon_mimetype
)
# Delete all previous records if we are writting new ones
if pwa_icon_ir_attachments:
pwa_icon_ir_attachments.unlink()
self._write_icon_to_attachment(pwa_icon_extension, pwa_icon_mimetype)
# write multiple sizes if not SVG
if pwa_icon_extension != ".svg":
# Fail if provided PNG is smaller than 512x512
if self._unpack_icon(self.pwa_icon).size < (512, 512):
raise exceptions.UserError(
_("You can only upload PNG files bigger than 512x512")
)
for size in [
(128, 128),
(144, 144),
(152, 152),
(192, 192),
(256, 256),
(512, 512),
]:
self._write_icon_to_attachment(
pwa_icon_extension, pwa_icon_mimetype, size=size
)
| OCA/web/web_pwa_oca/models/res_config_settings.py/0 | {
"file_path": "OCA/web/web_pwa_oca/models/res_config_settings.py",
"repo_id": "OCA",
"token_count": 3018
} | 82 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg:svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="919"
height="495"
viewBox="0 0 919 495"
version="1.1"
id="svg8"
sodipodi:docname="odoo_logo.svg"
inkscape:version="0.92.5 (2060ec1f9f, 2020-04-08)">
<svg:metadata
id="metadata14">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</svg:metadata>
<svg:defs
id="defs12" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="2488"
inkscape:window-height="1025"
id="namedview10"
showgrid="false"
inkscape:zoom="0.46245919"
inkscape:cx="463.82471"
inkscape:cy="247.5"
inkscape:window-x="72"
inkscape:window-y="27"
inkscape:window-maximized="1"
inkscape:current-layer="svg8" />
<svg:g
fill="none"
id="g6">
<svg:path
fill="#8F8F8F"
d="M695 346c-41.421 0-75-33.579-75-75s33.579-75 75-75 75 33.579 75 75-33.579 75-75 75zm0-31c24.3 0 44-19.7 44-44s-19.7-44-44-44-44 19.7-44 44 19.7 44 44 44zm-157 31c-41.421 0-75-33.579-75-75s33.579-75 75-75 75 33.579 75 75-33.579 75-75 75zm0-31c24.3 0 44-19.7 44-44s-19.7-44-44-44-44 19.7-44 44 19.7 44 44 44zm-82-45c0 41.935-33.592 76-75.009 76C339.575 346 306 312.005 306 270.07c0-41.936 30.5-74.07 74.991-74.07 16.442 0 31.647 3.496 44.007 12.58l.002-43.49c0-8.334 7.27-15.09 15.5-15.09 8.228 0 15.5 6.762 15.5 15.09V270zm-75 45c24.3 0 44-19.7 44-44s-19.7-44-44-44-44 19.7-44 44 19.7 44 44 44z"
id="path2" />
<svg:path
fill="#875A7B"
d="M224 346c-41.421 0-75-33.579-75-75s33.579-75 75-75 75 33.579 75 75-33.579 75-75 75zm0-31c24.3 0 44-19.7 44-44s-19.7-44-44-44-44 19.7-44 44 19.7 44 44 44z"
id="path4" />
</svg:g>
<script />
<script
type="text/javascript" />
<script
type="text/javascript" />
</svg:svg>
| OCA/web/web_pwa_oca/static/img/icons/odoo_logo.svg/0 | {
"file_path": "OCA/web/web_pwa_oca/static/img/icons/odoo_logo.svg",
"repo_id": "OCA",
"token_count": 1343
} | 83 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_responsive
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 11.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2018-09-02 05:11+0000\n"
"Last-Translator: Hans Henrik Gabelgaard <hhg@gabelgaard.org>\n"
"Language-Team: none\n"
"Language: da\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 3.1.1\n"
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/chatter_topbar/chatter_topbar.xml:0
#, python-format
msgid "Activities"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/search_panel/search_panel.xml:0
#, python-format
msgid "All"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/chatter_topbar/chatter_topbar.xml:0
#, python-format
msgid "Attachment counter loading..."
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/chatter_topbar/chatter_topbar.xml:0
#, python-format
msgid "Attachments"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/control_panel/control_panel.xml:0
#, python-format
msgid "CLEAR"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/legacy/xml/form_buttons.xml:0
#, python-format
msgid "Discard"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/control_panel/control_panel.xml:0
#: code:addons/web_responsive/static/src/components/search_panel/search_panel.xml:0
#, python-format
msgid "FILTER"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/apps_menu/apps_menu.xml:0
#, python-format
msgid "Home Menu"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/chatter_topbar/chatter_topbar.xml:0
#, python-format
msgid "Log note"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/attachment_viewer/attachment_viewer.xml:0
#, python-format
msgid "Maximize"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/attachment_viewer/attachment_viewer.xml:0
#, python-format
msgid "Minimize"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/legacy/xml/form_buttons.xml:0
#, python-format
msgid "New"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/control_panel/control_panel.xml:0
#: code:addons/web_responsive/static/src/components/search_panel/search_panel.xml:0
#, python-format
msgid "SEE RESULT"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/legacy/xml/form_buttons.xml:0
#, python-format
msgid "Save"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/apps_menu/apps_menu.xml:0
#, python-format
msgid "Search menus..."
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/control_panel/control_panel.xml:0
#, python-format
msgid "Search..."
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/chatter_topbar/chatter_topbar.xml:0
#, python-format
msgid "Send message"
msgstr ""
#. module: web_responsive
#. odoo-javascript
#: code:addons/web_responsive/static/src/components/control_panel/control_panel.xml:0
#, python-format
msgid "View switcher"
msgstr ""
#~ msgid "Chatter Position"
#~ msgstr "Log position"
#~ msgid "Sided"
#~ msgstr "Side"
#~ msgid "Users"
#~ msgstr "Brugere"
#~ msgid "<span class=\"sr-only\">Toggle App Drawer</span>"
#~ msgstr "<span class=\"sr-only\">Skift App skuffe</span>"
#~ msgid "<span class=\"sr-only\">Toggle Navigation</span>"
#~ msgstr "<span class=\"sr-only\">Skift navigation</span>"
#~ msgid "Apps"
#~ msgstr "Applikationer"
#~ msgid "More"
#~ msgstr "Mere"
#~ msgid "More <b class=\"caret\"/>"
#~ msgstr "Mere <b class=\"caret\"/>"
#~ msgid "Task"
#~ msgstr "Opgave"
| OCA/web/web_responsive/i18n/da.po/0 | {
"file_path": "OCA/web/web_responsive/i18n/da.po",
"repo_id": "OCA",
"token_count": 1653
} | 84 |
This module adds responsiveness to web backend.
**Features for all devices**:
* New navigation with the fullscreen app menu
.. image:: ../static/img/appmenu.gif
* Quick menu search inside the app menu
.. image:: ../static/img/appsearch.gif
* Sticky header & footer in list view
.. image:: ../static/img/listview.gif
* Sticky statusbar in form view
.. image:: ../static/img/formview.gif
* Bigger checkboxes in list view
.. image:: ../static/img/listview.gif
**Features for mobile**:
* View type picker dropdown displays comfortably
.. image:: ../static/img/viewtype.gif
* Control panel buttons use icons to save space.
.. image:: ../static/img/form_buttons.gif
* Search panel is collapsed to mobile version on small screens.
.. image:: ../static/img/search_panel.gif
* Followers and send button is displayed on mobile. Avatar is hidden.
.. image:: ../static/img/chatter.gif
* Big inputs on form in edit mode
**Features for desktop computers**:
* Keyboard shortcuts for easier navigation,
**using `Alt + Shift + [NUM]`** combination instead of
just `Alt + [NUM]` to avoid conflict with Firefox Tab switching.
Standard Odoo keyboard hotkeys changed to be more intuitive or
accessible by fingers of one hand.
F.x. `Alt + S` for `Save`
.. image:: ../static/img/shortcuts.gif
* Autofocus on search menu box when opening the app menu
.. image:: ../static/img/appsearch.gif
* Full width form sheets
.. image:: ../static/img/formview.gif
* When the chatter is on the side part, the document viewer fills that
part for side-by-side reading instead of full screen. You can still put it on full
width preview clicking on the new maximize button.
.. image:: ../static/img/document_viewer.gif
* When the user chooses to send a public message the color of the composer is different
from the one when the message is an internal log.
.. image:: ../static/img/chatter-colors.gif
| OCA/web/web_responsive/readme/DESCRIPTION.rst/0 | {
"file_path": "OCA/web/web_responsive/readme/DESCRIPTION.rst",
"repo_id": "OCA",
"token_count": 555
} | 85 |
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Copyright 2018 Tecnativa - Jairo Llopis
Copyright 2021 ITerra - Sergey Shebanin
Copyright 2023 Onestein - Anjeel Haria
License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). -->
<templates>
<t t-inherit="web.NavBar.AppsMenu" t-inherit-mode="extension" owl="1">
<xpath expr="//Dropdown" position="replace">
<!-- Same hotkey as in EE -->
<AppsMenu>
<AppsMenuSearchBar />
<DropdownItem
t-foreach="apps"
t-as="app"
t-key="app.id"
class="'o_app'"
dataset="{ menuXmlid: app.xmlid, section: app.id }"
href="getMenuItemHref(app)"
onSelected="() => this.onNavBarDropdownItemSelection(app)"
>
<img
class="o-app-icon"
draggable="false"
t-att-src="getWebIconData(app)"
/>
<div t-esc="app.name" />
</DropdownItem>
</AppsMenu>
</xpath>
</t>
<!-- Apps menu -->
<t t-name="web_responsive.AppsMenu" owl="1">
<div class="o-dropdown dropdown o-dropdown--no-caret o_navbar_apps_menu">
<button
class="dropdown-toggle"
title="Home Menu"
data-hotkey="a"
t-on-click.stop="() => this.setOpenState(!state.open,true)"
>
<i class="oi oi-apps" />
</button>
<div t-if="state.open" class="dropdown-menu-custom">
<t t-slot="default" />
</div>
</div>
</t>
<!-- Search bar -->
<t t-name="web_responsive.AppsMenuSearchResults" owl="1">
<div
class="search-container"
t-att-class="state.hasResults ? 'has-results' : ''"
>
<div class="search-input">
<span class="fa fa-search search-icon" />
<input
type="search"
t-ref="SearchBarInput"
t-on-input="_searchMenus"
t-on-keydown="_onKeyDown"
autocomplete="off"
placeholder="Search menus..."
class="form-control"
data-allow-hotkeys="true"
/>
</div>
<div t-if="state.results.length" class="search-results">
<t t-foreach="state.results" t-as="result" t-key="result">
<t t-set="menu" t-value="_menuInfo(result)" />
<a
t-attf-class="search-result {{result_index == state.offset ? 'highlight' : ''}}"
t-att-style="menu.webIconData ? "background-image:url(" + menu.webIconData + ");background-size:4%" : ''"
t-attf-href="#menu_id={{menu.id}}&action={{menu.actionID}}"
t-att-data-menu-id="menu.id"
t-att-data-action-id="menu.actionID"
draggable="false"
>
<span class="text-ellipsis" t-att-title="result.name">
<t
t-foreach="_splitName(result)"
t-as="name"
t-key="name_index"
>
<b
t-if="name_index % 2"
t-out="name"
style="text-primary"
/>
<t t-else="" t-out="name" />
</t>
</span>
</a>
</t>
</div>
</div>
</t>
</templates>
| OCA/web/web_responsive/static/src/components/apps_menu/apps_menu.xml/0 | {
"file_path": "OCA/web/web_responsive/static/src/components/apps_menu/apps_menu.xml",
"repo_id": "OCA",
"token_count": 2479
} | 86 |
/* Copyright 2018 Tecnativa - Jairo Llopis
* Copyright 2021 ITerra - Sergey Shebanin
* Copyright 2023 Onestein - Anjeel Haria
* License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). */
odoo.define("web_responsive", function () {
"use strict";
// Fix for iOS Safari to set correct viewport height
// https://github.com/Faisal-Manzer/postcss-viewport-height-correction
function setViewportProperty(doc) {
function handleResize() {
requestAnimationFrame(function updateViewportHeight() {
doc.style.setProperty("--vh100", doc.clientHeight + "px");
});
}
handleResize();
return handleResize;
}
window.addEventListener(
"resize",
_.debounce(setViewportProperty(document.documentElement), 100)
);
});
| OCA/web/web_responsive/static/src/legacy/js/web_responsive.js/0 | {
"file_path": "OCA/web/web_responsive/static/src/legacy/js/web_responsive.js",
"repo_id": "OCA",
"token_count": 323
} | 87 |
# Copyright (C) 2023-TODAY Synconics Technologies Pvt. Ltd. (<http://www.synconics.com>).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class IrHttp(models.AbstractModel):
_inherit = "ir.http"
@classmethod
def _get_translation_frontend_modules_name(cls):
modules = super()._get_translation_frontend_modules_name()
return modules + ["web_save_discard_button"]
| OCA/web/web_save_discard_button/models/ir_http.py/0 | {
"file_path": "OCA/web/web_save_discard_button/models/ir_http.py",
"repo_id": "OCA",
"token_count": 163
} | 88 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.