text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
Feature: Notifications
As a user
I want to be notified
So that I can stay updated about the information
Scenario: User should be able to read and dismiss notifications
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Admin" creates following groups using API
| id |
| sales |
And "Admin" adds user to the group using API
| user | group |
| Alice | sales |
| Brian | sales |
And "Alice" logs in
And "Alice" creates the following folder in personal space using API
| name |
| folder_to_shared |
| share_to_group |
And "Alice" creates the following project space using API
| name | id |
| team | team.1 |
And "Alice" opens the "files" app
When "Alice" shares the following resource using the sidebar panel
| resource | recipient | type | role | resourceType |
| folder_to_shared | Brian | user | Can edit | folder |
| share_to_group | sales | group | Can edit | folder |
And "Brian" logs in
Then "Brian" should see the following notifications
| message |
| Alice Hansen shared folder_to_shared with you |
| Alice Hansen shared share_to_group with you |
And "Brian" marks all notifications as read
When "Alice" removes following sharee
| resource | recipient |
| folder_to_shared | Brian |
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "team.1"
And "Alice" adds following users to the project space
| user | role | kind |
| Brian | Can edit | user |
| Carol | Can edit | user |
Then "Alice" should see no notifications
And "Brian" should see the following notifications
| message |
| Alice Hansen unshared folder_to_shared with you |
| Alice Hansen added you to Space team |
And "Brian" marks all notifications as read
When "Alice" removes access to following users from the project space
| user | role | kind |
| Carol | Can edit | user |
And "Carol" logs in
Then "Carol" should see the following notifications
| message |
| Alice Hansen added you to Space team |
| Alice Hansen removed you from Space team |
And "Carol" logs out
When "Alice" opens the "admin-settings" app
And "Alice" navigates to the project spaces management page
And "Alice" disables the space "team.1" using the context-menu
Then "Brian" should see the following notifications
| message |
| Alice Hansen disabled Space team |
When "Alice" deletes the space "team.1" using the context-menu
Then "Brian" should see the following notifications
| message |
| Alice Hansen deleted Space team |
And "Brian" logs out
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/smoke/notifications.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/notifications.feature",
"repo_id": "owncloud",
"token_count": 1247
} | 861 |
Feature: spaces public link
Scenario: public link for space
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
| David |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
When "Alice" logs in
And "Alice" creates the following project space using API
| name | id |
| team | team.1 |
And "Alice" creates the following folder in space "team" using API
| name |
| spaceFolder/subFolder |
And "Alice" creates the following file in space "team" using API
| name | content |
| spaceFolder/shareToBrian.txt | some text |
| spaceFolder/subFolder/shareToBrian.md | readme |
And "Alice" adds the following members to the space "team" using API
| user | role | shareType |
| Brian | Can edit | space |
| Carol | Can view | space |
| David | Can manage | space |
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "team.1"
And "Alice" uploads the following resources via drag-n-drop
| resource |
| simple.pdf |
| testavatar.jpg |
And "Alice" creates a public link for the space with password "%public%" using the sidebar panel
And "Alice" renames the most recently created public link of space to "spaceLink"
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | password |
| spaceFolder | %public% |
And "Alice" renames the most recently created public link of resource "spaceFolder" to "folderLink"
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | password |
| spaceFolder/shareToBrian.txt | %public% |
And "Alice" renames the most recently created public link of resource "spaceFolder/shareToBrian.txt" to "textLink"
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | password |
| spaceFolder/subFolder/shareToBrian.md | %public% |
And "Alice" renames the most recently created public link of resource "spaceFolder/subFolder/shareToBrian.md" to "markdownLink"
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | password |
| simple.pdf | %public% |
And "Alice" renames the most recently created public link of resource "simple.pdf" to "pdfLink"
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | password |
| testavatar.jpg | %public% |
And "Alice" renames the most recently created public link of resource "testavatar.jpg" to "imageLink"
And "Alice" logs out
When "Brian" logs in
And "Brian" opens the public link "spaceLink"
And "Brian" unlocks the public link with password "%public%"
Then "Brian" should not be able to edit the public link named "spaceLink"
And "Brian" should not be able to edit the public link named "folderLink"
When "Brian" opens the public link "textLink"
And "Brian" unlocks the public link with password "%public%"
Then "Brian" is in a text-editor
And "Brian" closes the file viewer
When "Brian" opens the public link "markdownLink"
And "Brian" unlocks the public link with password "%public%"
Then "Brian" is in a text-editor
And "Brian" closes the file viewer
And "Brian" logs out
When "Carol" logs in
And "Carol" opens the public link "spaceLink"
And "Carol" unlocks the public link with password "%public%"
But "Carol" should not be able to edit the public link named "spaceLink"
And "Carol" should not be able to edit the public link named "folderLink"
When "Carol" opens the public link "folderLink"
And "Carol" unlocks the public link with password "%public%"
Then "Carol" should see folder "subFolder" but should not be able to edit
When "Carol" opens the public link "pdfLink"
And "Carol" unlocks the public link with password "%public%"
Then "Carol" is in a pdf-viewer
And "Carol" closes the file viewer
And "Carol" logs out
When "David" logs in
And "David" opens the public link "spaceLink"
And "David" unlocks the public link with password "%public%"
And "David" edits the public link named "spaceLink" of the space changing role to "Can edit"
And "David" edits the public link named "folderLink" of resource "spaceFolder" changing role to "Can edit"
When "David" opens the public link "imageLink"
And "David" unlocks the public link with password "%public%"
Then "David" is in a image-viewer
And "David" closes the file viewer
And "David" logs out
Scenario: Quick link
Given "Admin" creates following users using API
| id |
| Alice |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
When "Alice" logs in
And "Alice" creates the following project space using API
| name | id |
| team | team.1 |
And "Alice" creates the following file in space "team" using API
| name | content |
| file.txt | some text |
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "team.1"
When "Alice" creates quick link of the resource "file.txt" with password "%public%" from the context menu
And "Anonymous" opens the public link "Link"
And "Anonymous" unlocks the public link with password "%public%"
Then "Anonymous" is in a text-editor
And "Anonymous" closes the file viewer
And "Alice" logs out
Scenario: crud operation to public link for space
Given "Admin" creates following users using API
| id |
| Alice |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
When "Alice" logs in
And "Alice" creates the following project space using API
| name | id |
| team | team.1 |
And "Alice" creates the following file in space "team" using API
| name | content |
| example.txt | some text |
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "team.1"
And "Alice" creates a public link for the space with password "%public%" using the sidebar panel
And "Alice" renames the most recently created public link of space to "spaceLink"
And "Alice" edits the public link named "spaceLink" of the space changing role to "Can edit"
And "Alice" logs out
And "Anonymous" opens the public link "spaceLink"
And "Anonymous" unlocks the public link with password "%public%"
And "Anonymous" downloads the following public link resources using the sidebar panel
| resource | type |
| example.txt | file |
And "Anonymous" uploads the following resources in public link page
| resource |
| new-lorem.txt |
And "Anonymous" renames the following public link resources
| resource | as |
| example.txt | renamed.txt |
And "Anonymous" edits the following resources
| resource | content |
| renamed.txt | new content |
When "Anonymous" deletes the following resources using the sidebar panel
| resource |
| renamed.txt |
| new-lorem.txt |
| owncloud/web/tests/e2e/cucumber/features/spaces/publicLink.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/spaces/publicLink.feature",
"repo_id": "owncloud",
"token_count": 2614
} | 862 |
{
"extends": "@ownclouders/tsconfig",
"compilerOptions": {
"module": "CommonJS"
}
}
| owncloud/web/tests/e2e/cucumber/tsconfig.json/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/tsconfig.json",
"repo_id": "owncloud",
"token_count": 40
} | 863 |
export * as http from './http'
export * as graph from './graph'
export * as dav from './davSpaces'
export * as share from './share'
export * as keycloak from './keycloak'
export * as provision from './provision'
export * as settings from './userSettings'
| owncloud/web/tests/e2e/support/api/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/index.ts",
"repo_id": "owncloud",
"token_count": 80
} | 864 |
import { Link } from '../types'
import { createdLinkStore } from '../store'
export class LinksEnvironment {
getLink({ name }: { name: string }): Link {
if (!createdLinkStore.has(name)) {
throw new Error(`link with name '${name}' not found`)
}
return createdLinkStore.get(name)
}
updateLinkName({ key, link }: { key: string; link: Link }): any {
if (!createdLinkStore.has(key)) {
throw new Error(`link with name '${key}' not found`)
}
createdLinkStore.set(link.name, link)
createdLinkStore.delete(key)
}
createLink({ key, link }: { key: string; link: Link }): Link {
if (createdLinkStore.has(key)) {
throw new Error(`link with key '${key}' already exists`)
}
createdLinkStore.set(key, link)
return link
}
deleteLink({ key }: { key: string }): boolean {
if (createdLinkStore.has(key)) {
return createdLinkStore.delete(key)
}
throw new Error(`link with key '${key}' doesn't exist`)
}
}
| owncloud/web/tests/e2e/support/environment/link.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/environment/link.ts",
"repo_id": "owncloud",
"token_count": 367
} | 865 |
import { Page } from '@playwright/test'
const usersNavSelector = '//a[@data-nav-name="admin-settings-users"]'
const appLoadingSpinnerSelector = '#app-loading-spinner'
export class Users {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
async navigate(): Promise<void> {
await this.#page.locator(usersNavSelector).click()
await this.#page.locator(appLoadingSpinnerSelector).waitFor({ state: 'detached' })
}
}
| owncloud/web/tests/e2e/support/objects/app-admin-settings/page/users.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/page/users.ts",
"repo_id": "owncloud",
"token_count": 156
} | 866 |
import { Download, Locator, Page } from '@playwright/test'
import * as po from './actions'
import { Space } from '../../../types'
export class Resource {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
async create(args: Omit<po.createResourceArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.createResources({ ...args, page: this.#page })
await this.#page.goto(startUrl)
await this.#page.locator('#files-view').waitFor()
}
async upload(args: Omit<po.uploadResourceArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.uploadResource({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async tryToUpload(args: Omit<po.uploadResourceArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.tryToUploadResource({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async uploadLargeNumberOfResources(args: Omit<po.uploadResourceArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.uploadLargeNumberOfResources({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async dropUpload(args: Omit<po.uploadResourceArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.dropUploadFiles({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
// uploads the file but does check if the upload was successful
// and does not navigate back to the startUrl
startUpload(args: Omit<po.uploadResourceArgs, 'page'>): Promise<void> {
return po.startResourceUpload({ ...args, page: this.#page })
}
pauseUpload(): Promise<void> {
return po.pauseResourceUpload(this.#page)
}
async resumeUpload(): Promise<void> {
const startUrl = this.#page.url()
await po.resumeResourceUpload(this.#page)
await this.#page.goto(startUrl)
}
cancelUpload(): Promise<void> {
return po.cancelResourceUpload(this.#page)
}
async download(args: Omit<po.downloadResourcesArgs, 'page'>): Promise<Download[]> {
const startUrl = this.#page.url()
const downloads = await po.downloadResources({ ...args, page: this.#page })
await this.#page.goto(startUrl)
return downloads
}
async rename(args: Omit<po.renameResourceArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.renameResource({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async copy(args: Omit<po.moveOrCopyResourceArgs, 'page' | 'action'>): Promise<void> {
const startUrl = this.#page.url()
await po.moveOrCopyResource({ ...args, page: this.#page, action: 'copy' })
await this.#page.goto(startUrl)
}
async move(args: Omit<po.moveOrCopyResourceArgs, 'page' | 'action'>): Promise<void> {
const startUrl = this.#page.url()
await po.moveOrCopyResource({ ...args, page: this.#page, action: 'move' })
await this.#page.goto(startUrl)
}
async copyMultipleResources(args: Omit<po.moveOrCopyMultipleResourceArgs, 'page' | 'action'>) {
const startUrl = this.#page.url()
await po.moveOrCopyMultipleResources({ ...args, page: this.#page, action: 'copy' })
await this.#page.goto(startUrl)
}
async moveMultipleResources(args: Omit<po.moveOrCopyMultipleResourceArgs, 'page' | 'action'>) {
const startUrl = this.#page.url()
await po.moveOrCopyMultipleResources({ ...args, page: this.#page, action: 'move' })
await this.#page.goto(startUrl)
}
async delete(args: Omit<po.deleteResourceArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.deleteResource({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
async open(): Promise<void> {}
async restoreVersion(args: Omit<po.resourceVersionArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.restoreResourceVersion({ ...args, page: this.#page })
// Files details page does not update after restore button is clicked
// This is the issue: https://github.com/owncloud/web/issues/6361
await this.#page.reload()
await this.#page.goto(startUrl)
}
async downloadVersion(args: Omit<po.downloadResourceVersionArgs, 'page'>): Promise<Download[]> {
const startUrl = this.#page.url()
const downloads = await po.downloadResourceVersion({ ...args, page: this.#page })
await this.#page.goto(startUrl)
return downloads
}
async deleteTrashBin(args: Omit<po.deleteResourceTrashbinArgs, 'page'>): Promise<string> {
const startUrl = this.#page.url()
const message = await po.deleteResourceTrashbin({ ...args, page: this.#page })
await this.#page.goto(startUrl)
return message
}
async deleteTrashbinMultipleResources(
args: Omit<po.deleteTrashbinMultipleResourcesArgs, 'page'>
): Promise<void> {
const startUrl = this.#page.url()
await po.deleteTrashbinMultipleResources({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async emptyTrashbin({ page }): Promise<void> {
const startUrl = this.#page.url()
await po.emptyTrashbin({ page })
await this.#page.goto(startUrl)
}
async expectThatDeleteTrashBinButtonIsNotVisible(
args: Omit<po.deleteResourceTrashbinArgs, 'page'>
): Promise<void> {
return await po.expectThatDeleteButtonIsNotVisible({ ...args, page: this.#page })
}
async restoreTrashBin(args: Omit<po.restoreResourceTrashbinArgs, 'page'>): Promise<string> {
const startUrl = this.#page.url()
const message = await po.restoreResourceTrashbin({ ...args, page: this.#page })
await this.#page.goto(startUrl)
return message
}
async expectThatRestoreTrashBinButtonIsNotVisible(
args: Omit<po.restoreResourceTrashbinArgs, 'page'>
): Promise<void> {
return await po.expectThatRestoreResourceButtonVisibility({ ...args, page: this.#page })
}
async areTagsVisibleForResourceInFilesTable(
args: Omit<po.resourceTagsArgs, 'page'>
): Promise<boolean> {
return await po.getTagsForResourceVisibilityInFilesTable({ ...args, page: this.#page })
}
async areTagsVisibleForResourceInDetailsPanel(
args: Omit<po.resourceTagsArgs, 'page'>
): Promise<boolean> {
return await po.getTagsForResourceVisibilityInDetailsPanel({
...args,
page: this.#page
})
}
async searchResource(args: Omit<po.searchResourceGlobalSearchArgs, 'page'>): Promise<void> {
await po.searchResourceGlobalSearch({ ...args, page: this.#page })
}
getDisplayedResources(args: Omit<po.getDisplayedResourcesArgs, 'page'>): Promise<string[]> {
switch (args.keyword) {
case 'files list':
return po.getDisplayedResourcesFromFilesList(this.#page)
case 'search list':
return po.getDisplayedResourcesFromSearch(this.#page)
case 'Shares':
return po.getDisplayedResourcesFromShares(this.#page)
case 'trashbin':
return po.getDisplayedResourcesFromTrashbin(this.#page)
default:
throw new Error('Unknown keyword')
}
}
async openFolder(resource): Promise<void> {
await po.clickResource({ page: this.#page, path: resource })
}
async openFolderViaBreadcrumb(resource): Promise<void> {
await po.clickResourceFromBreadcrumb({ page: this.#page, resource })
}
async switchToTilesViewMode(): Promise<void> {
await po.clickViewModeToggle({ page: this.#page, target: 'resource-tiles' })
}
async expectThatResourcesAreTiles(): Promise<void> {
await po.expectThatResourcesAreTiles({ page: this.#page })
}
async showHiddenFiles(): Promise<void> {
await po.showHiddenResources(this.#page)
}
async editResource(args: Omit<po.editResourcesArgs, 'page'>): Promise<void> {
await po.editResources({ ...args, page: this.#page })
}
async openFileInViewer(args: Omit<po.openFileInViewerArgs, 'page'>): Promise<void> {
await po.openFileInViewer({ ...args, page: this.#page })
}
async addTags(args: Omit<po.resourceTagsArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.addTagsToResource({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async removeTags(args: Omit<po.resourceTagsArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.removeTagsFromResource({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async clickTag(args: Omit<po.clickTagArgs, 'page'>): Promise<void> {
return await po.clickResourceTag({ ...args, page: this.#page })
}
createSpaceFromFolder(args: Omit<po.createSpaceFromFolderArgs, 'page'>): Promise<Space> {
return po.createSpaceFromFolder({ ...args, page: this.#page })
}
createSpaceFromSelection(args: Omit<po.createSpaceFromSelectionArgs, 'page'>): Promise<Space> {
return po.createSpaceFromSelection({ ...args, page: this.#page })
}
async checkThatFileVersionIsNotAvailable(
args: Omit<po.resourceVersionArgs, 'page'>
): Promise<void> {
const startUrl = this.#page.url()
await po.checkThatFileVersionIsNotAvailable({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async changePage(args: Omit<po.changePageArgs, 'page'>): Promise<void> {
await po.changePage({ ...args, page: this.#page })
}
async changeItemsPerPage(args: Omit<po.changeItemsPerPageArgs, 'page'>): Promise<void> {
await po.changeItemsPerPage({ ...args, page: this.#page })
}
getFileListFooterText(): Promise<string> {
return po.getFileListFooterText({ page: this.#page })
}
countNumberOfResourcesInThePage(): Promise<number> {
return po.countNumberOfResourcesInThePage({ page: this.#page })
}
async expectPageNumberNotToBeVisible(): Promise<void> {
await po.expectPageNumberNotToBeVisible({ page: this.#page })
}
async expectFileToBeSelected(args: Omit<po.expectFileToBeSelectedArgs, 'page'>): Promise<void> {
await po.expectFileToBeSelected({ ...args, page: this.#page })
}
async createShotcut(args: Omit<po.shortcutArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.createShotcut({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async openShotcut({ name, url }: { name: string; url?: string }): Promise<void> {
await po.openShotcut({ page: this.#page, name: name, url: url })
}
getLockLocator(args: Omit<po.expectFileToBeLockedArgs, 'page'>): Locator {
return po.getLockLocator({ ...args, page: this.#page })
}
}
| owncloud/web/tests/e2e/support/objects/app-files/resource/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/resource/index.ts",
"repo_id": "owncloud",
"token_count": 3638
} | 867 |
export * as applicationFiles from './app-files'
export * as applicationAdminSettings from './app-admin-settings'
export * as runtime from './runtime'
export * as account from './account'
export * as urlNavigation from './url-navigation'
| owncloud/web/tests/e2e/support/objects/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/index.ts",
"repo_id": "owncloud",
"token_count": 64
} | 868 |
const addDays = (days: number): Date => {
const date = new Date()
date.setDate(date.getDate() + days)
return date
}
const addMonth = (noOfMonths: number): Date => {
const date = new Date()
date.setMonth(date.getMonth() + noOfMonths)
return date
}
export const getActualExpiryDate = (
dateType: 'day' | 'week' | 'month' | 'year',
dateOfExpiration: string
): Date => {
switch (dateType) {
case 'day':
return addDays(parseInt(dateOfExpiration))
case 'week':
return addDays(parseInt(dateOfExpiration) * 7)
case 'month':
return addMonth(parseInt(dateOfExpiration))
case 'year':
return new Date(new Date().setFullYear(new Date().getFullYear() + parseInt(dateOfExpiration)))
}
}
| owncloud/web/tests/e2e/support/utils/datePicker.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/utils/datePicker.ts",
"repo_id": "owncloud",
"token_count": 272
} | 869 |
// This file must not export or import anything on top-level
declare module '*.vue' {
import { defineComponent } from 'vue'
const component: ReturnType<typeof defineComponent>
export default component
}
| owncloud/web/web.jest.d.ts/0 | {
"file_path": "owncloud/web/web.jest.d.ts",
"repo_id": "owncloud",
"token_count": 57
} | 870 |
<?php
//全局session_start
session_start();
//全局居设置时区
date_default_timezone_set('Asia/Shanghai');
//全局设置默认字符
header('Content-type:text/html;charset=utf-8');
//定义数据库连接参数
define('DBHOST', '127.0.0.1');//将localhost或者127.0.0.1修改为数据库服务器的地址
define('DBUSER', 'root');//将root修改为连接mysql的用户名
define('DBPW', '');//将root修改为连接mysql的密码,如果改了还是连接不上,请先手动连接下你的数据库,确保数据库服务没问题在说!
define('DBNAME', 'pikachu');//自定义,建议不修改
define('DBPORT', '3306');//将3306修改为mysql的连接端口,默认tcp3306
?>
| zhuifengshaonianhanlu/pikachu/inc/config.inc.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/inc/config.inc.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 407
} | 871 |
<?php
include_once '../inc/config.inc.php';
include_once '../inc/mysql.inc.php';
$link=connect();
//这个是获取cookie的api页面
if(isset($_GET['cookie'])){
$time=date('Y-m-d g:i:s');
$ipaddress=getenv ('REMOTE_ADDR');
$cookie=$_GET['cookie'];
$referer=$_SERVER['HTTP_REFERER'];
$useragent=$_SERVER['HTTP_USER_AGENT'];
$query="insert cookies(time,ipaddress,cookie,referer,useragent)
values('$time','$ipaddress','$cookie','$referer','$useragent')";
$result=mysqli_query($link, $query);
}
header("Location:http://192.168.1.4/pikachu/index.php");//重定向到一个可信的网站
?> | zhuifengshaonianhanlu/pikachu/pkxss/xcookie/cookie.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/pkxss/xcookie/cookie.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 280
} | 872 |
<?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 = "csrf.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','active open','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR.'header.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="#">CSRF</a>
</li>
<li class="active">CSRF概述</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<div id="vul_info">
<dl>
<dt class="vul_title">CSRF(跨站请求伪造)概述</dt>
<dd class="vul_detail">
Cross-site request forgery 简称为“CSRF”,在CSRF的攻击场景中攻击者会伪造一个请求(这个请求一般是一个链接),然后欺骗目标用户进行点击,用户一旦点击了这个请求,整个攻击就完成了。所以CSRF攻击也成为"one click"攻击。
很多人搞不清楚CSRF的概念,甚至有时候会将其和XSS混淆,更有甚者会将其和越权问题混为一谈,这都是对原理没搞清楚导致的。<br/>
这里列举一个场景解释一下,希望能够帮助你理解。<br />
<b>场景需求:</b><br />小黑想要修改大白在购物网站tianxiewww.xx.com上填写的会员地址。<br />
<b>先看下大白是如何修改自己的密码的:</b><br />登录---修改会员信息,提交请求---修改成功。<br />
所以小黑想要修改大白的信息,他需要拥有:1,登录权限 2,修改个人信息的请求。<br />
<dd class="vul_detail">
但是大白又不会把自己xxx网站的账号密码告诉小黑,那小黑怎么办?<br />
于是他自己跑到www.xx.com上注册了一个自己的账号,然后修改了一下自己的个人信息(比如:E-mail地址),他发现修改的请求是:<br />
【http://www.xxx.com/edit.php?email=xiaohei@88.com&Change=Change】<br />
于是,他实施了这样一个操作:把这个链接伪装一下,在小白登录xxx网站后,欺骗他进行点击,小白点击这个链接后,个人信息就被修改了,小黑就完成了攻击目的。<br />
</dd>
<dd class="vul_detail">
<b>为啥小黑的操作能够实现呢。有如下几个关键点:</b><br />
1.www.xxx.com这个网站在用户修改个人的信息时没有过多的校验,导致这个请求容易被伪造;<br />
---因此,我们判断一个网站是否存在CSRF漏洞,其实就是判断其对关键信息(比如密码等敏感信息)的操作(增删改)是否容易被伪造。<br />
2.小白点击了小黑发给的链接,并且这个时候小白刚好登录在购物网上;<br />
---如果小白安全意识高,不点击不明链接,则攻击不会成功,又或者即使小白点击了链接,但小白此时并没有登录购物网站,也不会成功。<br />
---因此,要成功实施一次CSRF攻击,需要“天时,地利,人和”的条件。<br />
当然,如果小黑事先在xxx网的首页如果发现了一个XSS漏洞,则小黑可能会这样做:
欺骗小白访问埋伏了XSS脚本(盗取cookie的脚本)的页面,小白中招,小黑拿到小白的cookie,然后小黑顺利登录到小白的后台,小黑自己修改小白的相关信息。<br />
---所以跟上面比一下,就可以看出CSRF与XSS的区别:CSRF是借用户的权限完成攻击,攻击者并没有拿到用户的权限,而XSS是直接盗取到了用户的权限,然后实施破坏。
</dd>
<dd class="vul_detail">
因此,网站如果要防止CSRF攻击,则需要对敏感信息的操作实施对应的安全措施,防止这些操作出现被伪造的情况,从而导致CSRF。比如:<br />
--对敏感信息的操作增加安全的token;<br />
--对敏感信息的操作增加安全的验证码;<br />
--对敏感信息的操作实施安全的逻辑流程,比如修改密码时,需要先校验旧密码等。<br />
<br />
<p>如果你没有读太明白,不要犹豫,请再读一遍啦</p>
</dd>
<dd class="vul_detail">
你可以通过“Cross-site request forgery”对应的测试栏目,来进一步的了解该漏洞。
</dd>
</dl>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR.'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/csrf/csrf.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/csrf/csrf.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 3958
} | 873 |
<?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 = "fileinclude.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.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="fileinclude.php">file include</a>
</li>
<li class="active">概述</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<div id="vul_info">
<dl>
<dt class="vul_title">File Inclusion(文件包含漏洞)概述</dt>
<dd class="vul_detail">
文件包含,是一个功能。在各种开发语言中都提供了内置的文件包含函数,其可以使开发人员在一个代码文件中直接包含(引入)另外一个代码文件。
比如 在PHP中,提供了:<br />
include(),include_once()<br />
require(),require_once()<br />
这些文件包含函数,这些函数在代码设计中被经常使用到。<br />
</dd>
<dd class="vul_detail">
大多数情况下,文件包含函数中包含的代码文件是固定的,因此也不会出现安全问题。
但是,有些时候,文件包含的代码文件被写成了一个变量,且这个变量可以由前端用户传进来,这种情况下,如果没有做足够的安全考虑,则可能会引发文件包含漏洞。
攻击着会指定一个“意想不到”的文件让包含函数去执行,从而造成恶意操作。
根据不同的配置环境,文件包含漏洞分为如下两种情况:<br />
<b>1.本地文件包含漏洞:</b>仅能够对服务器本地的文件进行包含,由于服务器上的文件并不是攻击者所能够控制的,因此该情况下,攻击着更多的会包含一些
固定的系统配置文件,从而读取系统敏感信息。很多时候本地文件包含漏洞会结合一些特殊的文件上传漏洞,从而形成更大的威力。<br />
<b>2.远程文件包含漏洞:</b>能够通过url地址对远程的文件进行包含,这意味着攻击者可以传入任意的代码,这种情况没啥好说的,准备挂彩。
</dd>
<dd class="vul_detail">
因此,在web应用系统的功能设计上尽量不要让前端用户直接传变量给包含函数,如果非要这么做,也一定要做严格的白名单策略进行过滤。
</dd>
<dd class="vul_detail_1">
你可以通过“File Inclusion”对应的测试栏目,来进一步的了解该漏洞。
</dd>
</dl>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/fileinclude/fileinclude.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/fileinclude/fileinclude.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2504
} | 874 |
<?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 = "op1_login.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../../";
include_once $PIKA_ROOT_DIR . 'header.php';
include_once $PIKA_ROOT_DIR.'inc/mysql.inc.php';
include_once $PIKA_ROOT_DIR.'inc/function.php';
include_once $PIKA_ROOT_DIR.'inc/config.inc.php';
$link=connect();
//判断是是否登录,如果已经登录,点击时,直接进入会员中心
if(check_op_login($link)){
header("location:op1_mem.php");
}
$html='';
if(isset($_POST['submit'])){
if($_POST['username']!=null && $_POST['password']!=null){
$username=escape($link, $_POST['username']);
$password=escape($link, $_POST['password']);//转义,防注入
$query="select * from member where username='$username' and pw=md5('$password')";
$result=execute($link, $query);
if(mysqli_num_rows($result)==1){
$data=mysqli_fetch_assoc($result);
$_SESSION['op']['username']=$username;
$_SESSION['op']['password']=sha1(md5($password));
header("location:op1_mem.php");
}else{
$html.="<p>登录失败,请重新登录</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="../op.php">Over Permission</a>
</li>
<li class="active">op1 login</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="lucy/123456,lili/123456,kobe/123456">
点一下提示~
</a>
</div>
<div class="page-content">
<div class="op_form">
<div class="op_form_main">
<h4 class="header blue lighter bigger">
<i class="ace-icon fa fa-coffee green"></i>
Please Enter Your Information
</h4>
<form method="post">
<!-- <fieldset>-->
<label>
<span>
<input type="text" name="username" placeholder="Username" />
<i class="ace-icon fa fa-user"></i>
</span>
</label>
</br>
<label>
<span>
<input type="password" name="password" placeholder="Password" />
<i class="ace-icon fa fa-lock"></i>
</span>
</label>
<div class="space"></div>
<div class="clearfix">
<label><input class="submit" name="submit" type="submit" value="Login" /></label>
</div>
</form>
<?php echo $html;?>
</div><!-- /.widget-main -->
</div><!-- /.widget-body -->
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/overpermission/op1/op1_login.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/overpermission/op1/op1_login.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2085
} | 875 |
<?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_insert.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();
// 判断是否登录,没有登录不能访问
if(!check_sqli_session($link)){
echo "<script>alert('登录后才能进入会员中心哦')</script>";
header("location:sqli_login.php");
}
$html1='';
if(isset($_POST['submit'])){
if($_POST['sex']!=null && $_POST['phonenum']!=null && $_POST['add']!=null && $_POST['email']!=null){
// $getdata=escape($link, $_POST);
//未转义,形成注入,sql操作类型为update
$getdata=$_POST;
$query="update member set sex='{$getdata['sex']}',phonenum='{$getdata['phonenum']}',address='{$getdata['add']}',email='{$getdata['email']}' where username='{$_SESSION['sqli']['username']}'";
$result=execute($link, $query);
if(mysqli_affected_rows($link)==1 || mysqli_affected_rows($link)==0){
header("location:sqli_mem.php");
}else {
$html1.='修改失败,请重试';
}
}
}
?>
<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">edit</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">
<?php
//通过当前session-name到数据库查询,并显示其对应信息
$username=$_SESSION['sqli']['username'];
$query="select * from member where username='$username'";
$result=execute($link, $query);
$data=mysqli_fetch_array($result, MYSQL_ASSOC);
$name=$data['username'];
$sex=$data['sex'];
$phonenum=$data['phonenum'];
$add=$data['address'];
$email=$data['email'];
$html=<<<A
<div id="per_info">
<form method="post">
<h1 class="per_title">hello,{$name},欢迎来到个人会员中心 | <a style="color:bule;" href="sqli_mem.php?logout=1">退出登录</a></h1>
<p class="per_name">姓名:{$name}</p>
<p class="per_sex">性别:<input type="text" name="sex" value="{$sex}"/></p>
<p class="per_phone">手机:<input class="phonenum" type="text" name="phonenum" value="{$phonenum}"/></p>
<p class="per_add">住址:<input class="add" type="text" name="add" value="{$add}"/></p>
<p class="per_email">邮箱:<input class="email" type="text" name="email" value="{$email}"/></p>
<input class="sub" type="submit" name="submit" value="submit"/>
</form>
</div>
A;
echo $html;
echo $html1;
?>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_iu/sqli_edit.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_iu/sqli_edit.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1984
} | 876 |
<?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 = "unser.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR.'header.php';
class S{
var $test = "pikachu";
function __construct(){
echo $this->test;
}
}
//O:1:"S":1:{s:4:"test";s:29:"<script>alert('xss')</script>";}
$html='';
if(isset($_POST['o'])){
$s = $_POST['o'];
if(!@$unser = unserialize($s)){
$html.="<p>大兄弟,来点劲爆点儿的!</p>";
}else{
$html.="<p>{$unser->test}</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="unserilization.php">PHP反序列化</a>
</li>
<li class="active">概述</li>
</ul>
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="先把PHP序列化和反序列化搞懂了在来玩">
点一下提示~
</a>
</div>
<div class="page-content">
<form method="post">
<p>这是一个接受序列化数据的api:
<input type="text" name="o" />
<input type="submit" value="提交">
</form>
<?php echo $html;?>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?> | zhuifengshaonianhanlu/pikachu/vul/unserilization/unser.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/unserilization/unser.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1169
} | 877 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$PIKA_ROOT_DIR = "../../../";
include_once $PIKA_ROOT_DIR.'inc/config.inc.php';
include_once $PIKA_ROOT_DIR.'inc/mysql.inc.php';
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "xss_blind.php"){
$ACTIVE = array('','','','','','','','active open','','','','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
include_once $PIKA_ROOT_DIR.'header.php';
$link=connect();
$html='';
if(array_key_exists("content",$_POST) && $_POST['content']!=null){
$content=escape($link, $_POST['content']);
$name=escape($link, $_POST['name']);
$time=$time=date('Y-m-d g:i:s');
$query="insert into xssblind(time,content,name) values('$time','$content','$name')";
$result=execute($link, $query);
if(mysqli_affected_rows($link)==1){
$html.="<p>谢谢参与,阁下的看法我们已经收到!</p>";
}else {
$html.="<p>ooo.提交出现异常,请重新提交</p>";
}
}
?>
<div class="main-content" xmlns="http://www.w3.org/1999/html">
<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="登录后台,看会发生啥?后台登录地址是/xssblind/admin_login.php">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="xss_blind">
<p class="blindxss_tip">请在下面输入你对"锅盖头"这种发型的看法:</p>
<p class="blindxss_tip">我们将会随机抽出一名送出麻港一日游</p>
<form method="post">
<textarea class="content" name="content"></textarea><br />
<label>你的大名:</label><br />
<input class="name" type="text" name="name"/><br />
<input 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/xss/xssblind/xss_blind.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/xss/xssblind/xss_blind.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1520
} | 878 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>8th Wall Web: Portal</title>
<!-- We've included a slightly modified version of A-Frame, which fixes some polish concerns -->
<script src="//cdn.8thwall.com/web/aframe/8frame-1.3.0.min.js"></script>
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<!-- Landing Pages - see https://www.8thwall.com/docs/web/#landing-pages -->
<script src='//cdn.8thwall.com/web/landing-page/landing-page.js'></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXX"></script>
<script src="cubemap-static.js"></script>
<script src="portal-components.js"></script>
</head>
<body>
<a-scene
portal
landing-page
xrextras-loading
xrextras-runtime-error
xrextras-tap-recenter
xrweb>
<!-- We can define assets here to be loaded when A-Frame initializes -->
<a-assets>
<!-- Credit to Poly by Google for the model: https://poly.google.com/view/0fVRHo65E-j -->
<a-asset-item id="ballModel" src="jini-ball.glb"></a-asset-item>
<img id="pines" src="misty-pines.jpg">
<img id="posx" src="cubemap/posx.png">
<img id="posy" src="cubemap/posy.png">
<img id="posz" src="cubemap/posz.png">
<img id="negx" src="cubemap/negx.png">
<img id="negy" src="cubemap/negy.png">
<img id="negz" src="cubemap/negz.png">
</a-assets>
<a-camera id="camera" position="0 5 8"></a-camera>
<!-- Doorway -->
<a-box scale="1 6 1" position="-2.5 3 0" color="#8083A2"></a-box>
<a-box scale="1 6 1" position="2.5 3 0" color="#8083A2"></a-box>
<a-box scale="6 1 1" position="0 6.5 0" color="#8083A2"></a-box>
<!-- Hider walls -->
<a-entity id="hider-walls">
<a-box scale="6 100 1" position="0 57 0" xrextras-hider-material></a-box>
<a-box scale="94 100 1" position="-50 50 0" xrextras-hider-material></a-box>
<a-box scale="94 100 1" position="50 50 0" xrextras-hider-material></a-box>
<a-box scale="200 100 1" position="0 50 200" xrextras-hider-material></a-box>
<a-box scale="200 1 201" position="0 100 100" xrextras-hider-material></a-box>
<a-box scale="200 1 199" position="0 -0.5 100" xrextras-hider-material></a-box>
<a-box scale="1 100 200" position="-100 50 100" xrextras-hider-material></a-box>
<a-box scale="1 100 200" position="100 50 100" xrextras-hider-material></a-box>
</a-entity>
<a-entity id="portal-wall">
<a-plane scale="4 6 1" rotation="180 0 0" position="0 3 0.5" xrextras-hider-material></a-plane>
</a-entity>
<a-entity
light="
type: directional;
intensity: 0.8;
castShadow: true;
shadowMapHeight:2048;
shadowMapWidth:2048;
shadowCameraTop: 10;
target: #ball;"
position="1 4.3 2.5"
xrextras-attach="target: ball; offset: 0 15 0;"
shadow>
</a-entity>
<a-entity light="type: ambient; intensity: 0.65;"></a-entity>
<a-entity id="portal-contents">
<a-entity
id="ball"
scale="5 5 5"
position="0 1.5 -7"
gltf-model="#ballModel"
cubemap-static
bob
shadow>
</a-entity>
<a-sky src="#pines"></a-sky>
<a-box scale="5 1 10" position="0 -0.5 -4.5" color="#8083A2" shadow></a-box>
</a-entity>
</a-scene>
</body>
</html>
| 8thwall/web/examples/aframe/portal/index.html/0 | {
"file_path": "8thwall/web/examples/aframe/portal/index.html",
"repo_id": "8thwall",
"token_count": 1758
} | 0 |
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
| 8thwall/web/examples/aframe/reactapp/src/index.css/0 | {
"file_path": "8thwall/web/examples/aframe/reactapp/src/index.css",
"repo_id": "8thwall",
"token_count": 155
} | 1 |
// Copyright (c) 2021 8th Wall, Inc.
/* globals AFRAME */
AFRAME.registerComponent('shoot-tomato', {
init() {
const camera = document.getElementById('camera')
const splatSnd = document.querySelector('#splat').components.sound
this.el.sceneEl.addEventListener('touchstart', (event) => {
// Create element to be thrown, setting position, scale, and model
const tomato = document.createElement('a-entity')
tomato.setAttribute('position', camera.object3D.position)
tomato.setAttribute('scale', '1 1 1')
tomato.setAttribute('gltf-model', '#tomatoModel')
// Choose a random rotation offset for some variation
const randomRotation = {x: -90 + Math.random() * 30, y: Math.random() * 360, z: 0}
tomato.setAttribute('rotation', randomRotation)
// Set velocity, rotated with camera direction
const velocity = new THREE.Vector3(0, 0, -10)
velocity.applyQuaternion(camera.object3D.quaternion)
tomato.setAttribute('velocity', velocity)
// Add physics body
tomato.setAttribute('body', {
type: 'dynamic',
sphereRadius: 0.35,
shape: 'sphere',
})
tomato.setAttribute('shadow', {
receive: false,
})
// Add tomato to scene
this.el.sceneEl.appendChild(tomato)
// The splat is created at the same time as the thrown tomato so
// there is time to load the model before it hits the ground
const splatBase = document.createElement('a-entity')
splatBase.setAttribute('visible', 'false')
// The splat consists of a model wrapped in an empty
// parent so we can apply the correct scaling animation
const splat = document.createElement('a-entity')
splat.setAttribute('gltf-model', '#tomatoModel')
splat.setAttribute('scale', '1 1 1')
splatBase.appendChild(splat)
this.el.sceneEl.appendChild(splatBase)
let didCollide = false
tomato.addEventListener('collide', (e) => {
// Only want to do the splat once, and with the ground only
if (didCollide || e.detail.body.el.id !== 'ground') {
return
}
didCollide = true
// Stop previous splat sound
splatSnd.stopSound()
// Play splat sound
splatSnd.playSound()
// Copy positioning of thrown tomato to splat
splatBase.object3D.position.copy(tomato.object3D.position)
splat.object3D.rotation.copy(tomato.object3D.rotation)
splatBase.object3D.visible = true
tomato.setAttribute('visible', 'false')
// We can't remove the thrown tomato until the physics step is over
setTimeout(() => {
tomato.parentNode.removeChild(tomato)
}, 0)
// Using animation component to show flattening
splatBase.setAttribute('animation__scale', {
property: 'scale',
from: '1 1 1',
to: '3 0.1 3',
dur: 500,
easing: 'easeOutQuad',
})
// After 2.5 seconds, shrink the splat away and delete it
setTimeout(() => {
splatBase.setAttribute('animation__scale', {
property: 'scale',
from: '3 0.1 3',
to: '0.001 0.001 0.001',
dur: 1500,
easing: 'easeInQuad',
})
setTimeout(() => splatBase.parentNode.removeChild(splatBase), 1500)
}, 2500)
})
})
},
})
| 8thwall/web/examples/aframe/tossobject/toss-object.js/0 | {
"file_path": "8thwall/web/examples/aframe/tossobject/toss-object.js",
"repo_id": "8thwall",
"token_count": 1413
} | 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 AlignmentPattern(posX, posY, estimatedModuleSize)
{
this.x=posX;
this.y=posY;
this.count = 1;
this.estimatedModuleSize = estimatedModuleSize;
this.__defineGetter__("EstimatedModuleSize", function()
{
return this.estimatedModuleSize;
});
this.__defineGetter__("Count", function()
{
return this.count;
});
this.__defineGetter__("X", function()
{
return Math.floor(this.x);
});
this.__defineGetter__("Y", function()
{
return Math.floor(this.y);
});
this.incrementCount = function()
{
this.count++;
}
this.aboutEquals=function( moduleSize, i, j)
{
if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize)
{
var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);
return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0;
}
return false;
}
}
function AlignmentPatternFinder( image, startX, startY, width, height, moduleSize, resultPointCallback)
{
this.image = image;
this.possibleCenters = new Array();
this.startX = startX;
this.startY = startY;
this.width = width;
this.height = height;
this.moduleSize = moduleSize;
this.crossCheckStateCount = new Array(0,0,0);
this.resultPointCallback = resultPointCallback;
this.centerFromEnd=function(stateCount, end)
{
return (end - stateCount[2]) - stateCount[1] / 2.0;
}
this.foundPatternCross = function(stateCount)
{
var moduleSize = this.moduleSize;
var maxVariance = moduleSize / 2.0;
for (var i = 0; i < 3; i++)
{
if (Math.abs(moduleSize - stateCount[i]) >= maxVariance)
{
return false;
}
}
return true;
}
this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal)
{
var image = this.image;
var maxI = qrcode.height;
var stateCount = this.crossCheckStateCount;
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
// Start counting up from center
var i = startI;
while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount)
{
stateCount[1]++;
i--;
}
// If already too many modules in this state or ran off the edge:
if (i < 0 || stateCount[1] > maxCount)
{
return NaN;
}
while (i >= 0 && !image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount)
{
stateCount[0]++;
i--;
}
if (stateCount[0] > maxCount)
{
return NaN;
}
// Now also count down from center
i = startI + 1;
while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount)
{
stateCount[1]++;
i++;
}
if (i == maxI || stateCount[1] > maxCount)
{
return NaN;
}
while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[2] <= maxCount)
{
stateCount[2]++;
i++;
}
if (stateCount[2] > maxCount)
{
return NaN;
}
var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
{
return NaN;
}
return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN;
}
this.handlePossibleCenter=function( stateCount, i, j)
{
var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
var centerJ = this.centerFromEnd(stateCount, j);
var centerI = this.crossCheckVertical(i, Math.floor (centerJ), 2 * stateCount[1], stateCountTotal);
if (!isNaN(centerI))
{
var estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0;
var max = this.possibleCenters.length;
for (var index = 0; index < max; index++)
{
var center = this.possibleCenters[index];
// Look for about the same center and module size:
if (center.aboutEquals(estimatedModuleSize, centerI, centerJ))
{
return new AlignmentPattern(centerJ, centerI, estimatedModuleSize);
}
}
// Hadn't found this before; save it
var point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize);
this.possibleCenters.push(point);
if (this.resultPointCallback != null)
{
this.resultPointCallback.foundPossibleResultPoint(point);
}
}
return null;
}
this.find = function()
{
var startX = this.startX;
var height = this.height;
var maxJ = startX + width;
var middleI = startY + (height >> 1);
// We are looking for black/white/black modules in 1:1:1 ratio;
// this tracks the number of black/white/black modules seen so far
var stateCount = new Array(0,0,0);
for (var iGen = 0; iGen < height; iGen++)
{
// Search from middle outwards
var i = middleI + ((iGen & 0x01) == 0?((iGen + 1) >> 1):- ((iGen + 1) >> 1));
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
var j = startX;
// Burn off leading white pixels before anything else; if we start in the middle of
// a white run, it doesn't make sense to count its length, since we don't know if the
// white run continued to the left of the start point
while (j < maxJ && !image[j + qrcode.width* i])
{
j++;
}
var currentState = 0;
while (j < maxJ)
{
if (image[j + i*qrcode.width])
{
// Black pixel
if (currentState == 1)
{
// Counting black pixels
stateCount[currentState]++;
}
else
{
// Counting white pixels
if (currentState == 2)
{
// A winner?
if (this.foundPatternCross(stateCount))
{
// Yes
var confirmed = this.handlePossibleCenter(stateCount, i, j);
if (confirmed != null)
{
return confirmed;
}
}
stateCount[0] = stateCount[2];
stateCount[1] = 1;
stateCount[2] = 0;
currentState = 1;
}
else
{
stateCount[++currentState]++;
}
}
}
else
{
// White pixel
if (currentState == 1)
{
// Counting black pixels
currentState++;
}
stateCount[currentState]++;
}
j++;
}
if (this.foundPatternCross(stateCount))
{
var confirmed = this.handlePossibleCenter(stateCount, i, maxJ);
if (confirmed != null)
{
return confirmed;
}
}
}
// Hmm, nothing we saw was observed and confirmed twice. If we had
// any guess at all, return it.
if (!(this.possibleCenters.length == 0))
{
return this.possibleCenters[0];
}
throw "Couldn't find enough alignment patterns";
}
} | 8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/alignpat.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/alignpat.js",
"repo_id": "8thwall",
"token_count": 3098
} | 3 |
/*
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 ECB(count, dataCodewords)
{
this.count = count;
this.dataCodewords = dataCodewords;
this.__defineGetter__("Count", function()
{
return this.count;
});
this.__defineGetter__("DataCodewords", function()
{
return this.dataCodewords;
});
}
function ECBlocks( ecCodewordsPerBlock, ecBlocks1, ecBlocks2)
{
this.ecCodewordsPerBlock = ecCodewordsPerBlock;
if(ecBlocks2)
this.ecBlocks = new Array(ecBlocks1, ecBlocks2);
else
this.ecBlocks = new Array(ecBlocks1);
this.__defineGetter__("ECCodewordsPerBlock", function()
{
return this.ecCodewordsPerBlock;
});
this.__defineGetter__("TotalECCodewords", function()
{
return this.ecCodewordsPerBlock * this.NumBlocks;
});
this.__defineGetter__("NumBlocks", function()
{
var total = 0;
for (var i = 0; i < this.ecBlocks.length; i++)
{
total += this.ecBlocks[i].length;
}
return total;
});
this.getECBlocks=function()
{
return this.ecBlocks;
}
}
function Version( versionNumber, alignmentPatternCenters, ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4)
{
this.versionNumber = versionNumber;
this.alignmentPatternCenters = alignmentPatternCenters;
this.ecBlocks = new Array(ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4);
var total = 0;
var ecCodewords = ecBlocks1.ECCodewordsPerBlock;
var ecbArray = ecBlocks1.getECBlocks();
for (var i = 0; i < ecbArray.length; i++)
{
var ecBlock = ecbArray[i];
total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords);
}
this.totalCodewords = total;
this.__defineGetter__("VersionNumber", function()
{
return this.versionNumber;
});
this.__defineGetter__("AlignmentPatternCenters", function()
{
return this.alignmentPatternCenters;
});
this.__defineGetter__("TotalCodewords", function()
{
return this.totalCodewords;
});
this.__defineGetter__("DimensionForVersion", function()
{
return 17 + 4 * this.versionNumber;
});
this.buildFunctionPattern=function()
{
var dimension = this.DimensionForVersion;
var bitMatrix = new BitMatrix(dimension);
// Top left finder pattern + separator + format
bitMatrix.setRegion(0, 0, 9, 9);
// Top right finder pattern + separator + format
bitMatrix.setRegion(dimension - 8, 0, 8, 9);
// Bottom left finder pattern + separator + format
bitMatrix.setRegion(0, dimension - 8, 9, 8);
// Alignment patterns
var max = this.alignmentPatternCenters.length;
for (var x = 0; x < max; x++)
{
var i = this.alignmentPatternCenters[x] - 2;
for (var y = 0; y < max; y++)
{
if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0))
{
// No alignment patterns near the three finder paterns
continue;
}
bitMatrix.setRegion(this.alignmentPatternCenters[y] - 2, i, 5, 5);
}
}
// Vertical timing pattern
bitMatrix.setRegion(6, 9, 1, dimension - 17);
// Horizontal timing pattern
bitMatrix.setRegion(9, 6, dimension - 17, 1);
if (this.versionNumber > 6)
{
// Version info, top right
bitMatrix.setRegion(dimension - 11, 0, 3, 6);
// Version info, bottom left
bitMatrix.setRegion(0, dimension - 11, 6, 3);
}
return bitMatrix;
}
this.getECBlocksForLevel=function( ecLevel)
{
return this.ecBlocks[ecLevel.ordinal()];
}
}
Version.VERSION_DECODE_INFO = new Array(0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69);
Version.VERSIONS = buildVersions();
Version.getVersionForNumber=function( versionNumber)
{
if (versionNumber < 1 || versionNumber > 40)
{
throw "ArgumentException";
}
return Version.VERSIONS[versionNumber - 1];
}
Version.getProvisionalVersionForDimension=function(dimension)
{
if (dimension % 4 != 1)
{
throw "Error getProvisionalVersionForDimension";
}
try
{
return Version.getVersionForNumber((dimension - 17) >> 2);
}
catch ( iae)
{
throw "Error getVersionForNumber";
}
}
Version.decodeVersionInformation=function( versionBits)
{
var bestDifference = 0xffffffff;
var bestVersion = 0;
for (var i = 0; i < Version.VERSION_DECODE_INFO.length; i++)
{
var targetVersion = Version.VERSION_DECODE_INFO[i];
// Do the version info bits match exactly? done.
if (targetVersion == versionBits)
{
return this.getVersionForNumber(i + 7);
}
// Otherwise see if this is the closest to a real version info bit string
// we have seen so far
var bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion);
if (bitsDifference < bestDifference)
{
bestVersion = i + 7;
bestDifference = bitsDifference;
}
}
// We can tolerate up to 3 bits of error since no two version info codewords will
// differ in less than 4 bits.
if (bestDifference <= 3)
{
return this.getVersionForNumber(bestVersion);
}
// If we didn't find a close enough match, fail
return null;
}
function buildVersions()
{
return new Array(new Version(1, new Array(), new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))),
new Version(2, new Array(6, 18), new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))),
new Version(3, new Array(6, 22), new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))),
new Version(4, new Array(6, 26), new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))),
new Version(5, new Array(6, 30), new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))),
new Version(6, new Array(6, 34), new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))),
new Version(7, new Array(6, 22, 38), new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))),
new Version(8, new Array(6, 24, 42), new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))),
new Version(9, new Array(6, 26, 46), new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))),
new Version(10, new Array(6, 28, 50), new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))),
new Version(11, new Array(6, 30, 54), new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))),
new Version(12, new Array(6, 32, 58), new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))),
new Version(13, new Array(6, 34, 62), new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))),
new Version(14, new Array(6, 26, 46, 66), new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))),
new Version(15, new Array(6, 26, 48, 70), new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))),
new Version(16, new Array(6, 26, 50, 74), new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))),
new Version(17, new Array(6, 30, 54, 78), new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))),
new Version(18, new Array(6, 30, 56, 82), new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))),
new Version(19, new Array(6, 30, 58, 86), new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))),
new Version(20, new Array(6, 34, 62, 90), new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))),
new Version(21, new Array(6, 28, 50, 72, 94), new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))),
new Version(22, new Array(6, 26, 50, 74, 98), new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))),
new Version(23, new Array(6, 30, 54, 74, 102), new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))),
new Version(24, new Array(6, 28, 54, 80, 106), new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))),
new Version(25, new Array(6, 32, 58, 84, 110), new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))),
new Version(26, new Array(6, 30, 58, 86, 114), new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))),
new Version(27, new Array(6, 34, 62, 90, 118), new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), new ECB(28, 16))),
new Version(28, new Array(6, 26, 50, 74, 98, 122), new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))),
new Version(29, new Array(6, 30, 54, 78, 102, 126), new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))),
new Version(30, new Array(6, 26, 52, 78, 104, 130), new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))),
new Version(31, new Array(6, 30, 56, 82, 108, 134), new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))),
new Version(32, new Array(6, 34, 60, 86, 112, 138), new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))),
new Version(33, new Array(6, 30, 58, 86, 114, 142), new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))),
new Version(34, new Array(6, 34, 62, 90, 118, 146), new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))),
new Version(35, new Array(6, 30, 54, 78, 102, 126, 150), new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)),new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))),
new Version(36, new Array(6, 24, 50, 76, 102, 128, 154), new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))),
new Version(37, new Array(6, 28, 54, 80, 106, 132, 158), new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))),
new Version(38, new Array(6, 32, 58, 84, 110, 136, 162), new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))),
new Version(39, new Array(6, 26, 54, 82, 110, 138, 166), new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))),
new Version(40, new Array(6, 30, 58, 86, 114, 142, 170), new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16))));
} | 8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/version.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/version.js",
"repo_id": "8thwall",
"token_count": 6046
} | 4 |
// Copyright (c) 2018 8th Wall, Inc.
// A pipeline module that throws an error after 300 frames -- illustrates the error handling in
// RuntimeError.pipelineModule().
const throwerrorPipelineModule = () => {
let frame = 0
return {
name: 'throwerror',
onUpdate: () => { if (++frame > 300) { throw Error('Too many frames!') } },
}
}
const onxrloaded = () => {
XR8.addCameraPipelineModules([ // Add camera pipeline modules.
// Existing pipeline modules.
XR8.GlTextureRenderer.pipelineModule(), // Draws the camera feed.
XRExtras.AlmostThere.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.
throwerrorPipelineModule(), // Throw an error after 300 frames.
])
XR8.run({canvas: document.getElementById('camerafeed')}) // Request permissions and run camera.
}
// Show loading screen before the full XR library has been loaded.
const load = () => { XRExtras.Loading.showLoading({onxrloaded}) }
window.onload = () => { window.XRExtras ? load() : window.addEventListener('xrextrasloaded', load) }
| 8thwall/web/xrextras/index.js/0 | {
"file_path": "8thwall/web/xrextras/index.js",
"repo_id": "8thwall",
"token_count": 446
} | 5 |
#almostthereContainer {
z-index: 820;
background-color: #101118;
}
.xrextras-old-style #almostthereContainer {
background-color: #FFFFFF;
}
#qrcode {
background-color: white;
margin: 0 auto;
width: 250px;
height: 250px;
padding: 8px;
border-radius: 20px;
box-sizing: content-box;
}
#qrcode>svg {
width: 100%;
display: block;
}
.arrow-top-corner {
position: fixed;
top: 3%;
right: 1.5%;
height: 36px;
}
.arrow-top-close {
position: fixed;
top: 3%;
right: 12.5%;
height: 36px;
}
.arrow-bottom-close {
position: fixed;
bottom: 3%;
right: 15%;
height: 36px;
-moz-transform: scale(-1, -1);
-o-transform: scale(-1, -1);
-webkit-transform: scale(-1, -1);
transform: scale(-1, -1);
}
.arrow-bottom-corner {
position: fixed;
bottom: 3%;
right: 2%;
height: 36px;
-moz-transform: scale(-1, -1);
-o-transform: scale(-1, -1);
-webkit-transform: scale(-1, -1);
transform: scale(-1, -1);
}
.app-header-img {
position: fixed;
width: 100vw;
max-width: 500px;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
.app-header-img.unknown {
position: fixed;
width: 100vw;
max-width: 500px;
left: 50%;
top: 43%;
transform: translateX(-50%) translateY(-57%);
}
.poweredby-img {
width: 35vw;
max-width: 200px;
position: fixed;
bottom: 2%;
left: 50%;
transform: translateX(-50%);
}
.poweredby-img.desktop {
width: 200px;
bottom: 5%;
}
.bottombarbump .poweredby-img{
bottom: 15%;
}
#error_msg_open_in_safari {
background-color: #101118;
}
.xrextras-old-style #error_msg_open_in_safari {
background-color: white;
}
.open-header-top {
font-family: 'Nunito-SemiBold', sans-serif;
color: white;
letter-spacing: .37;
font-size: 1em;
position: fixed;
top: 0%;
left: 50%;
transform: translateX(-50%);
}
.xrextras-old-style .open-header-top {
color: #323232;
}
.open-header-bottom {
font-family: 'Nunito-SemiBold', sans-serif;
color: white;
letter-spacing: .37;
font-size: 1em;
position: fixed;
top: 10%;
left: 50%;
transform: translateX(-50%);
}
.xrextras-old-style .open-header-bottom {
color: #323232;
}
.open-header-unknown {
font-family: 'Nunito-SemiBold', sans-serif;
color: white;
letter-spacing: .37;
font-size: 1em;
position: fixed;
top: 5%;
left: 50%;
transform: translateX(-50%);
}
.xrextras-old-style .open-header-unknown {
color: #323232;
}
.desktop-message {
font-family: 'Nunito-SemiBold', sans-serif;
margin: 0 auto;
margin-top: 1vh;
width: 500px;
color: white;
font-size: 24pt;
line-height: 1em;
}
.xrextras-old-style .desktop-message {
color: #323232;
}
.desktop-hint {
font-family: 'Nunito', sans-serif;
font-size: 14pt;
color: #fff;
line-height: 2em;
margin-top: 2vh;
letter-spacing: .37;
}
.xrextras-old-style .desktop-hint {
color: #323232;
}
.copy-link-btn {
position: fixed;
bottom: 20%;
left: 50%;
transform: translateX(-50%);
font-family: 'Nunito-SemiBold', sans-serif;
font-weight: 800;
font-size: 1.1em;
text-align: center;
color: white;
text-decoration: none;
border: none;
background-color: #AD50FF;
padding: 6px 13px;
border-radius: 10px;
}
.xrextras-old-style .copy-link-btn {
background-color: #7611B7;
}
.error-copy-link-copied {
background-color: #8083A2 !important;
}
.safari-hero-image {
max-height: 30vmin;
}
| 8thwall/web/xrextras/src/almosttheremodule/almost-there-module.css/0 | {
"file_path": "8thwall/web/xrextras/src/almosttheremodule/almost-there-module.css",
"repo_id": "8thwall",
"token_count": 1438
} | 6 |
import htmlContent from './media-preview.html'
import './media-preview.css'
import {configure, getConfig} from './capture-config'
const IOS_DOWNLOAD_LOCATION = 'shareddocuments:///private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/Downloads/'
const getFileNamePrefix = () => getConfig().fileNamePrefix || 'my-capture-'
const clickAnchor = (properties) => {
const anchor = document.createElement('a')
Object.assign(anchor, properties)
document.body.appendChild(anchor)
anchor.click()
document.body.removeChild(anchor)
}
// Is Web Share API Level 2 being used?
let webShareAPILevel2 = false
let currentBlob = null
let currentUrl = null
let currentFilename = null
let previewIsImage = false
let previewInteractableTimeout = null
let videoPending = false
let visibleObjectUrl = null
let afterFinalizeAction = null // Can be 'share' or 'download'
let closedWhileFinalizing = false
let currentDownloadUrl = null
let previewContainer
let imagePreview
let videoPreview
let muteButtonImg
let finalizeProgressBar
const clearState = () => {
currentBlob = null
if (currentUrl) {
URL.revokeObjectURL(currentUrl)
}
if (visibleObjectUrl) {
URL.revokeObjectURL(visibleObjectUrl)
}
clearTimeout(previewInteractableTimeout)
previewContainer.style.removeProperty('pointer-events')
finalizeProgressBar.value = 0
currentUrl = null
currentDownloadUrl = null
visibleObjectUrl = null
previewIsImage = false
videoPending = false
afterFinalizeAction = null
closedWhileFinalizing = false
previewContainer.classList.remove('fade-in')
previewContainer.classList.remove('image-preview')
previewContainer.classList.remove('video-preview')
previewContainer.classList.remove('downloaded')
previewContainer.classList.remove('finalize-waiting')
}
const setMuted = (muted) => {
videoPreview.muted = muted
if (muted) {
muteButtonImg.src = '//cdn.8thwall.com/web/img/mediarecorder/sound-off-v1.svg'
} else {
muteButtonImg.src = '//cdn.8thwall.com/web/img/mediarecorder/sound-on-v1.svg'
}
}
const closePreview = () => {
const wasPending = videoPending
clearState()
imagePreview.removeAttribute('src')
videoPreview.pause()
videoPreview.removeAttribute('src')
window.dispatchEvent(new CustomEvent('mediarecorder-previewclosed'))
closedWhileFinalizing = wasPending
}
const downloadFile = () => {
if (videoPending) {
previewContainer.classList.add('finalize-waiting')
afterFinalizeAction = 'download'
return
}
clickAnchor({
href: currentDownloadUrl || currentUrl,
download: currentFilename,
})
previewContainer.classList.add('downloaded')
}
const openIosDownload = () => {
clickAnchor({
href: IOS_DOWNLOAD_LOCATION + currentFilename,
target: '_blank',
})
}
const share = () => {
if (videoPending) {
previewContainer.classList.add('finalize-waiting')
afterFinalizeAction = 'share'
return
}
const fileToInclude = new File([currentBlob], currentFilename, {
type: previewIsImage ? 'image/jpeg' : 'video/mp4',
lastModified: Date.now(),
})
const shareObject = {
title: '',
text: '',
files: [fileToInclude],
}
navigator.share(shareObject)
}
const getTimestamp = () => {
const now = new Date()
return [now.getHours(), now.getMinutes(), now.getSeconds()]
.map(n => n.toString().padStart(2, '0')).join('')
}
const showPreview = () => {
previewContainer.classList.add('fade-in')
window.dispatchEvent(new CustomEvent('mediarecorder-previewopened'))
// This prevents a click on the capture button from also causing a click on the download button
clearTimeout(previewInteractableTimeout)
previewInteractableTimeout = setTimeout(() => {
previewContainer.style.pointerEvents = 'auto'
}, 100)
}
const showImagePreview = ({blob}) => {
clearState()
currentBlob = blob
currentUrl = URL.createObjectURL(blob)
currentFilename = `${getFileNamePrefix()}${getTimestamp()}.jpg`
previewIsImage = true
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onloadend = () => {
imagePreview.src = reader.result
previewContainer.classList.add('image-preview')
showPreview()
}
}
const showVideoPreview = ({videoBlob}) => {
clearState()
currentBlob = videoBlob
currentUrl = URL.createObjectURL(videoBlob)
currentFilename = `${getFileNamePrefix()}${getTimestamp()}.mp4`
previewContainer.classList.add('video-preview')
let waitingOnVideo = true
let waitingOnDataUrl = true
const maybeFinishLoading = () => {
if (waitingOnVideo || waitingOnDataUrl) {
return
}
showPreview()
setMuted(false)
videoPreview.play().then(() => {
// On iOS, this fixes the audio playback issue with volume being very low
if (window.XR8.XrDevice.deviceEstimate().os === 'iOS') {
videoPreview.pause()
videoPreview.play()
}
}).catch(() => {
// If the play command failed, retry with the video muted
setMuted(true)
videoPreview.play()
})
}
// On iOS, if we use the blob URL as the download href for a video, the user has the option to
// "View" the file instead of downloading, but that doesn't play properly. Instead, if we use
// the base 64 data URL, that doesn't display a broken video player when a user clicks "View".
if (window.XR8.XrDevice.deviceEstimate().os === 'iOS' && !webShareAPILevel2) {
const reader = new FileReader()
reader.readAsDataURL(currentBlob)
reader.onloadend = () => {
waitingOnDataUrl = false
currentDownloadUrl = reader.result
maybeFinishLoading()
}
} else {
waitingOnDataUrl = false
}
videoPreview.oncanplaythrough = () => {
videoPreview.oncanplaythrough = null
waitingOnVideo = false
maybeFinishLoading()
}
videoPreview.src = currentUrl
videoPreview.load()
}
const showVideoHandler = (event) => {
if (closedWhileFinalizing) {
closedWhileFinalizing = false
return
}
if (!videoPending) {
showVideoPreview(event.detail)
return
}
previewContainer.classList.remove('finalize-waiting')
videoPending = false
const {videoBlob} = event.detail
// Keep a reference to the preview URL so we can revoke it on close
visibleObjectUrl = currentUrl
currentBlob = videoBlob
currentUrl = URL.createObjectURL(videoBlob)
currentFilename = `${getFileNamePrefix()}${getTimestamp()}.mp4`
switch (afterFinalizeAction) {
case 'share':
share()
break
case 'download':
downloadFile()
break
default:
// Nothing
}
afterFinalizeAction = null
}
const previewVideoHandler = (event) => {
showVideoPreview(event.detail)
videoPending = true
}
const showImageHandler = event => showImagePreview(event.detail)
const progressHandler = (event) => {
finalizeProgressBar.value = event.detail.progress
finalizeProgressBar.max = event.detail.total
}
const initMediaPreview = (options = {}) => {
document.body.insertAdjacentHTML('beforeend', htmlContent)
previewContainer = document.getElementById('previewContainer')
imagePreview = document.getElementById('imagePreview')
videoPreview = document.getElementById('videoPreview')
muteButtonImg = document.getElementById('muteButtonImg')
finalizeProgressBar = document.getElementById('finalizeProgressBar')
const downloadButton = document.getElementById('downloadButton')
const actionButton = document.getElementById('actionButton')
const actionButtonText = document.getElementById('actionButtonText')
const actionButtonImg = document.getElementById('actionButtonImg')
// Checks for WKWebView's that can't download: https://github.com/eligrey/FileSaver.js/issues/686
const browser = window.XR8.XrDevice.deviceEstimate().browser.inAppBrowser ||
window.XR8.XrDevice.deviceEstimate().browser.name
const isWKWebViewiOS = ['Microsoft Edge', 'Google Chrome', 'Mozilla Firefox Focus', 'Firefox',
'Opera Touch', 'Pinterest', 'Snapchat', 'Instagram', 'Facebook', 'Facebook Messenger', 'Line',
'LinkedIn', 'Naver', 'Baidu', 'Brave'].includes(browser)
const tmpFile = new File([new Blob()], 'tmp.mp4', {
type: 'video/mp4',
lastModified: Date.now(),
})
const shareTestObj = {
files: [tmpFile],
}
// Check if Web Share API Level 2 is supported
if (navigator.canShare && navigator.canShare(shareTestObj)) {
webShareAPILevel2 = true
actionButtonText.textContent = options.actionButtonShareText || 'Share'
actionButtonImg.src = '//cdn.8thwall.com/web/img/mediarecorder/share-v1.svg'
actionButton.addEventListener('click', share)
if (window.XR8.XrDevice.deviceEstimate().os === 'iOS') {
// Hide the download button on iOS and only allow sharing.
actionButton.classList.remove('show-with-download-button')
actionButton.classList.add('show-alone')
downloadButton.parentNode.removeChild(downloadButton)
}
} else if (window.XR8.XrDevice.deviceEstimate().os === 'iOS' && isWKWebViewiOS) {
previewContainer.classList.add('disabled-download')
actionButton.parentNode.removeChild(actionButton)
downloadButton.parentNode.removeChild(downloadButton)
} else if (window.XR8.XrDevice.deviceEstimate().os === 'iOS') {
actionButtonText.textContent = options.actionButtonViewText || 'View'
actionButtonImg.src = '//cdn.8thwall.com/web/img/mediarecorder/view-v1.svg'
actionButton.addEventListener('click', openIosDownload)
actionButton.classList.add('show-after-download')
} else {
actionButton.parentNode.removeChild(actionButton)
}
document.getElementById('finalizeText').textContent = options.finalizeText || 'Preparing...'
document.getElementById('toggleMuteButton').addEventListener('click', () => {
setMuted(!videoPreview.muted)
})
window.addEventListener('mediarecorder-recordcomplete', showVideoHandler)
window.addEventListener('mediarecorder-photocomplete', showImageHandler)
window.addEventListener('mediarecorder-previewready', previewVideoHandler)
window.addEventListener('mediarecorder-finalizeprogress', progressHandler)
document.getElementById('closePreviewButton').addEventListener('click', closePreview)
if (document.getElementById('downloadButton')) {
downloadButton.addEventListener('click', downloadFile)
}
// Initialize with default configuration
configure()
}
const removeMediaPreview = () => {
previewContainer.parentNode.removeChild(previewContainer)
clearState()
currentFilename = null
previewContainer = null
imagePreview = null
videoPreview = null
muteButtonImg = null
finalizeProgressBar = null
window.removeEventListener('mediarecorder-recordcomplete', showVideoHandler)
window.removeEventListener('mediarecorder-photocomplete', showImageHandler)
window.removeEventListener('mediarecorder-previewready', previewVideoHandler)
window.removeEventListener('mediarecorder-finalizeprogress', progressHandler)
}
export {
initMediaPreview,
removeMediaPreview,
}
| 8thwall/web/xrextras/src/mediarecorder/media-preview.js/0 | {
"file_path": "8thwall/web/xrextras/src/mediarecorder/media-preview.js",
"repo_id": "8thwall",
"token_count": 3564
} | 7 |
<div id="runtimeErrorContainer" class="absolute-fill">
<div id="error_msg_unknown" class="hidden">
<div class="error-text-outer-container">
<div class="error-text-container error-margin-top-5">
<p><img height="75px" src="//cdn.8thwall.com/web/img/runtimeerror/v1/computer-voxel.png" class="floater"></p>
<div class="error-text-header">Oops, something went wrong!</div>
<div class="error-text-hint">
<p id="error_unknown_detail" />
</div>
</div>
</div>
</div>
</div>
| 8thwall/web/xrextras/src/runtimeerrormodule/runtime-error-module.html/0 | {
"file_path": "8thwall/web/xrextras/src/runtimeerrormodule/runtime-error-module.html",
"repo_id": "8thwall",
"token_count": 227
} | 8 |
## 新增获取/操作元素
### 1、新增获取元素
```js
document.querySelector("选择器");
document.querySelectorAll("选择器");
```
### 2、新增操作元素类样式
```js
document.querySelector("选择器").classList.add("类样式"); // 添加类样式
document.querySelector("选择器").classList.remove("类样式"); // 移除类样式
document.querySelector("选择器").classList.toggle("类样式"); // 反转类样式(有则删除,无则添加)
document.querySelector("选择器").classList.contains("类样式"); //是否包含类样式
document.querySelector("选择器").classList.item(索引); // 获取类样式
```
> PS:classList 的方式与 document.querySelector("选择器").className 的方法对比:
>
> **classList 的方法添加和删除不会清除原来的 class 类样式,只是在其基础上添加和删除。而 className的方式直接对源类样式操作,容易遗漏和误操作。**
示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.red {
color: red;
}
.green {
color: green;
}
.blue {
color: blue;
}
.underline {
text-decoration: underline;
}
</style>
</head>
<body>
<ul>
<li>第一个li标签</li>
<li class="green">第二个li标签</li>
<li>第三个li标签</li>
<li>第四个li标签</li>
</ul>
<input type="button" value="添加样式" id="btn1">
<input type="button" value="删除样式" id="btn2">
<input type="button" value="反转样式" id="btn3">
<input type="button" value="判断样式" id="btn4">
<script>
// 点击第一个按钮给第一个标签添加样式
document.querySelector("#btn1").onclick = function () {
document.querySelector("li").classList.add("red");
document.querySelector("li").classList.add("underline");
// 获取样式:获取元素的样式,索引代表样式的位置
var class1 = document.querySelector("li").classList.item(0);
var class2 = document.querySelector("li").classList.item(1);
console.log(class1 + "=====" + class2); // red=====underline
};
// 点击第二个按钮给第二个标签删除样式
document.querySelector("#btn2").onclick = function () {
document.querySelectorAll("li")[1].classList.remove("green");
};
// 点击第三个按钮给第三个标签反转样式
document.querySelector("#btn3").onclick = function () {
document.querySelectorAll("li")[2].classList.toggle("blue");
};
// 点击第四个按钮判断第四个标签是否包含某样式
document.querySelector("#btn4").onclick = function () {
var flag = document.querySelectorAll("li")[3].classList.contains("red");
console.log(flag);
};
</script>
</body>
</html>
```
## 自定义属性
定义:以 “**data-**” 开头,后面必须有至少一个字符,多个单词间用 “-” 连接。
建议:
1、名称中应该都是用小写字符;
2、名称中不要包含任何特殊符号;
3、名称中不要由纯数字组成。
```html
<p data-user-name="Daotin"></p>
```
获取自定义属性的值
```html
<script>
var pObj = document.querySelector("p");
var value = p.dataset["userName"];
console.log(value); // Daotin
</script>
```
> 使用 "**元素.dataset[]**" 的方式获取自定义属性的值。其中自定义属性的名称要使用**驼峰命名法**填写。
| Daotin/Web/01-HTML/02-HTML5/02-新增获取操作元素,自定义属性.md/0 | {
"file_path": "Daotin/Web/01-HTML/02-HTML5/02-新增获取操作元素,自定义属性.md",
"repo_id": "Daotin",
"token_count": 1970
} | 9 |
## 一、CSS可见性
```css
overflow: hidden; /*溢出隐藏 */
visibility: hidden; /* 隐藏元素 隐藏之后还保留原来的位置。*/
display: none; /* 隐藏元素 隐藏之后不保留原来的位置。*/
display: block; /* 元素可见 */
```
> `display:none` 和`display:block` 常配合js使用(如:鼠标经过时出现,鼠标离开时消失)。
## 二、css之内容移除(logo优化)
### 1、方法一
```css
text-indent: -5000em;
```
> text-indent 属性规定文本块中首行文本的缩进。注意: 负值是允许的。如果值是负数,将向左缩进。


> 之所以要写着两个字是为了 SEO,因为背景图片 SEO 看不懂.
### 2、方法二
**将元素高度设置为0, 使用内边距将盒子撑开,给盒子使用 overflow:hidden; 将文字隐藏。**
```css
.box{
width:300px;
height:0;
padding-top:100px;
overflow:hidden;
background:red;
}
```
## 三、CSS精灵图

上图所示为网页的请求原理图,当用户访问一个网站时,需要向服务器发送请求,网页上的每张图像都要经过一次请求才能展现给用户。
然而,一个网页中往往会应用很多小的背景图像作为修饰,当网页中的图像过多时,服务器就会频繁地接受和发送请求,这将大大降低页面的加载速度。为了有效地减少服务器接受和发送请求的次数,提高页面的加载速度,出现了CSS精灵技术(也称CSS Sprites)。
简单地说,CSS精灵是一种处理网页背景图像的方式。它将一个页面涉及到的所有零星背景图像都集中到一张大图中去,然后将大图应用于网页,这样,当用户访问该页面时,只需向服务发送一次请求,网页中的背景图像即可全部展示出来。
通常情况下,这个由很多小的背景图像合成的大图被称为精灵图,如下图所示为淘宝网站中的一个精灵图。

**工作原理:**
CSS 精灵其实是将网页中的一些背景图像整合到一张大图中(精灵图)。然而,各个网页元素通常只需要精灵图中不同位置的某个小图,要想精确定位到精灵图中的某个小图,就需要使用CSS的background-image、background-repeat和background-position属性进行背景定位,其中最关键的是使用`background-position`属性精确地定位。
**举例:**

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
body,ul,li{
margin: 0;
padding: 0;
}
ul, li{
list-style: none;
}
.box{
height: 48px;
background: #222;
margin-top: 50px;
}
.con{
width: 1182px;
height: 48px;
margin: 0 auto;
position: relative;
}
.con ul li{
float: left;
}
.con ul li a{
text-decoration: none;
color: #fff;
display: inline-block;
height: 48px;
font: 16px/48px microsoft yahei;
padding: 0 18px;
}
.con ul li a:hover{
background: #2774A2;
}
.con .hot{
position: absolute;
width: 31px;
height: 21px;
background: url("spirit.png") -58px 0;
left:221px;
bottom:35px;
}
.con .new{
position: absolute;
width: 31px;
height: 21px;
background: url("spirit.png") -135px 0;
left:90px;
bottom:35px;
}
</style>
</head>
<body>
<div class="box">
<div class="con">
<ul>
<li><a href="#">首页</a></li>
<li><a href="#">Java</a></li>
<li><a href="#">IOS</a></li>
<li><a href="#">PHP</a></li>
<li><a href="#">C/C++</a></li>
<li><a href="#">UI设计</a></li>
<li><a href="#">前端与移动开发</a></li>
<li><a href="#">问答专区</a></li>
<li><a href="#">Python</a></li>
<li><a href="#">网络营销</a></li>
<li><a href="#">活动专区</a></li>
</ul>
<div class="hot"></div>
<div class="new"></div>
</div>
</div>
</body>
</html>
```

> PS:之所以选择con作为父盒子而不是box作为父盒子,是因为box的宽度不定,不同的显示器宽度不同,那么new和hot的定位就有问题。
## 四、属性选择器
```css
input[type="text"][class] {
width: 20px;
height: 20px;
}
```
> 选择有 type 属性为 text,并且有 class 属性的标签。
```css
input[type="text"][class="id"] {
width: 20px;
height: 20px;
}
```
> 选择有 type 属性为 text,并且有 class 属性,并且class属性为 id 的标签。
**自定义属性:**
```html
<style>
p[bb="aa"] {
font-size:100px;
}
</style>
<body>
<p bb="aa"></p>
</body>
```
## 五、CSS滑动门

特点:边上是这种圆弧型的或者其他形状的,可以变换长度的样式。
> PS:浮动之后宽度不是父盒子的宽度,而是内容撑开的宽度。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
body,ul,li{
margin: 0;
padding: 0;
}
ul,li{
list-style: none;
}
ul li{
float: left;
}
ul li a{
display: inline-block;
height: 35px;
background: url("bg_r1_c1.png") no-repeat;
padding-left: 7px;
}
ul li a span{
display: inline-block;
height: 35px;
background: url("bg_r1_c2.png") right;
padding-right: 25px;
color: #fff;
line-height: 35px;
}
ul li a:hover{
background: url("bbg_r1_c1.png");
}
ul li a:hover span{
background: url("bbg_r1_c2.png") right;
}
</style>
</head>
<body>
<ul>
<li><a href="#"><span>网易云音乐</span></a></li>
<li><a href="#"><span>微信</span></a></li>
<li><a href="#"><span>蚂蚁花呗</span></a></li>
</ul>
</body>
</html>
```
**微信案例:**

> 现象:鼠标经过时,背景凸起。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
body,ul,li,a,span{
margin: 0;
padding: 0;
}
ul,li{
list-style: none;
}
.nav{
height: 74px;
background: url("weixin_bg.jpg");
}
.nav-con{
width: 600px;
margin: 0 auto;
}
li{
float: left;
height: 74px;
line-height: 74px;
margin-right: 60px;
}
li a{
display: inline-block;
text-decoration: none;
color: #fff;
height: 33px;
line-height: 33px;
background: url("bg.png") no-repeat 0 -144px;
padding-left: 13px;
}
a span{
display: inline-block;
height: 33px;
background: url("bg.png") no-repeat right -144px;
padding-right: 13px;
}
a:hover{
background: url("bg.png") no-repeat 0 -192px;
}
a:hover span{
background: url("bg.png") no-repeat right -192px;
}
</style>
</head>
<body>
<div class="nav">
<div class="nav-con">
<ul>
<li><a href="#"><span>首页</span></a></li>
<li><a href="#"><span>下载文章</span></a></li>
<li><a href="#"><span>微信公众公众公众助手</span></a></li>
</ul>
</div>
</div>
</body>
</html>
```
> 注意:CSS滑动门仅适用于span的内容不会超过给定的精灵图的宽度,否则就有破绽。
| Daotin/Web/02-CSS/01-CSS基础/05-可见性、内容移除、精灵图、属性选择器、滑动门.md/0 | {
"file_path": "Daotin/Web/02-CSS/01-CSS基础/05-可见性、内容移除、精灵图、属性选择器、滑动门.md",
"repo_id": "Daotin",
"token_count": 4192
} | 10 |
# 块元素水平垂直居中(完整版)
内联元素(inline)和行内块元素(inline-block)的水平垂直居中很简单,设置line-height和text-align: center就可以了。
这里主要说块级元素(block)的水平垂直居中方式。
## 水平居中
整体示例代码:
```html
<style>
.center{
border:1px solid red;
/* 填入下列样式代码 */
}
</style>
<div class="center">水平居中</div>
```
### 1、有固定的宽度
- 方法1:只需给需要居中的块级元素加`margin:0 auto`即可
- 方法2:absolute + 负margin
> 原理:由于left偏移了父对象的50%宽度,所以需要利用margin反向偏移居中块的50%宽度。
```css
position: absolute;
left: 50%;
margin-left: -xxpx;
```
- 方法3:absolute + margin: auto
> 原理:利用css定位规则,设置左右、上下方向定位为0,margin为auto,让css根据定位自动计算margin值,用hack的方式实现居中。
```css
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
```
### 2、无固定的宽度
> 注意:无固定的宽度能做到的,肯定是可以作用在“有固定的宽度”上的,所以就不在“有固定的宽度”中列出。
- 方法1:absolute + transform反向偏移
> 实现原理:与采用负margin的方式原理类似,不同点是使用了transform来代替margin做反向偏移,由于transform的计算基准是元素本身,所以这里可以用50%来做反向偏移。
```css
position: absolute;
left: 50%;
transform: translateX(-50%);
```
- 方法2:使用display: table
```css
display: table;
margin:0 auto;
```
- 方法3:flex布局
```css
父元素设置:
display:flex;
justify-content:center;
```
## 垂直居中
### 1、有固定的宽度
方法1:absolute + 负margin
方法2:absolute + margin: auto
### 2、无固定的宽度
方法1:absolute + transform反向偏移
方法2:flex布局
## 水平垂直居中
综合以上水平居中和垂直居中方式可以得到:
### 1、有固定的宽度
#### 方法1:absolute + 负margin
#### 方法2:absolute + margin: auto
### 2、无固定的宽度
#### 方法1:absolute + transform反向偏移
#### 方法2:flex布局
| Daotin/Web/02-CSS/01-CSS基础/块元素水平垂直居中(完整版).md/0 | {
"file_path": "Daotin/Web/02-CSS/01-CSS基础/块元素水平垂直居中(完整版).md",
"repo_id": "Daotin",
"token_count": 1335
} | 11 |
## 1、JavaScript简介
**JavaScript历史**
要了解JavaScript,我们首先要回顾一下JavaScript的诞生。在上个世纪的1995年,当时的网景公司正凭借其Navigator浏览器成为Web时代开启时最著名的第一代互联网公司。由于网景公司希望能在静态HTML页面上添加一些动态效果,于是叫Brendan Eich这哥们在两周之内设计出了JavaScript语言。你没看错,这哥们只用了10天时间。
为什么起名叫 JavaScript?原因是当时Java语言非常红火,所以网景公司希望借Java的名气来推广,但事实上JavaScript除了语法上有点像 Java,其他部分基本上没啥关系。
**ECMAScript**
因为网景开发了JavaScript,一年后微软又模仿JavaScript开发了JScript,为了让JavaScript成为全球标准,几个公司联合ECMA(European Computer Manufacturers Association)组织定制了JavaScript语言的标准,被称为ECMAScript标准。所以简单说来就是,ECMAScript是一种语言标准,而JavaScript是网景公司对ECMAScript标准的一种实现。
那为什么不直接把JavaScript定为标准呢?因为JavaScript是网景的注册商标。不过大多数时候,我们还是用JavaScript这个词。如果你遇到ECMAScript这个词,简单把它替换为JavaScript就行了。
**JavaScript版本**
JavaScript语言是在10天时间内设计出来的,虽然语言的设计者水平非常NB,但谁也架不住“时间紧,任务重”,所以,JavaScript有很多设计缺陷。
此外,由于JavaScript的标准——ECMAScript在不断发展,最新版ECMAScript 6标准(简称ES6)已经在2015年6月正式发布了,所以,讲到JavaScript的版本,实际上就是说它实现了ECMAScript标准的哪个版本。
由于浏览器在发布时就确定了JavaScript的版本,加上很多用户还在使用IE8这种古老的浏览器,这就导致你在写JavaScript的时候,要照顾一下老用户,不能一上来就用最新的ES6标准写,否则,老用户的浏览器是无法运行新版本的JavaScript代码的。
以上简介来自:[廖雪峰的官方网站](https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/0014344991049250a2c80ec84cb4861bbd1d9b2c0c2850e000)
## 2、JS作用
- 验证表单(以前的网速慢)
- 页面特效(PC端的网页效果)
- 移动端(移动web和app)
- 异步和服务器交互(AJAX)
- 服务端开发(nodejs)
## 3、语言类型
js是一种**脚本语言**,不仅是脚本语言还是弱类型的脚本语言。
脚本语言是一种解释性语言,解释性语言是相对于编译性语言而言的。
**编译型语言:**编译代码,把代码编译成CPU认识的语言(文件),然后整体的执行。
**解释型语言:**一行一行解析,解析一行执行一行。
**弱类型语言:**简单理解定义一个变量,可以有多种数据类型。(如:var)
## 4、前端组成
**HTML**:提供网页上显示的内容(结构)
**CSS**:美化网页(样式)
**JavaScript**:控制网页行为(行为)
## 5、js组成
> **js = ECMAScript + DOM + BOM + 高级**
**ECMAScript**(前身为欧洲计算机制造商协会):JavaScript的语法规范
**DOM**(Document Object Model 的文档对象模型简称):JavaScript操作网页上元素的API
**BOM**(Browser Object Model 的浏览器对象模型简称):JavaScript操作浏览器部分功能的API
## 6、js书写位置
**内嵌式:**
一般放在body里面的最后,有时放在head标签中(需要写页面加载函数)。
因为代码的顺序都是从上往下加载,在body中的元素,如果在js中获取body中元素的时候,会报错找不到。
**外链式:**
src=”外部js文件路径”
## 7、JS基础知识
**输出语句**
```javascript
console.log("内容"); // 在控制台打印输出内容
alert("内容"); // 弹窗显示内容
document.write("内容"); // 在页面书写内容,其内容可以识别标签,比如:document.write("<h1>你好</h1>")
```
**其他语句**
```js
alert("内容"); // 弹出对话框
prompt("提示信息"); // 可以在弹出的对话框输入内容给后台
confirm("") // 弹出对话框,有是否按钮
```
**js代码的注意问题:**
1. 在一对script的标签中有错误的js代码,那么该错误的代码后面的js代码不会执行。
2. 如果第一对的script标签中有错误,不会影响后面的script标签中的js代码执行。
3. script标签里面可以写的内容:`type="text/javascript"` 标准写法,或者` language="JavaScript"`,都是可以省略的,原因是在html开头写了遵循h5标准。
4. script标签可以出现多对。
5. 如果使用引入外部js文件的方式,那么不要在script标签里面写任何js代码,如果想写,就新开一对script标签。
| Daotin/Web/03-JavaScript/01-JavaScript基础知识/01-JavaScript概述.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/01-JavaScript基础知识/01-JavaScript概述.md",
"repo_id": "Daotin",
"token_count": 3193
} | 12 |
## 一、事件冒泡
### 1、事件冒泡
事件冒泡:当有多个元素嵌套,并且这些元素绑定了相同的事件,这时候如果里面的元素事件触发了,那么外面的事件会自动触发。
示例:
```html
<body>
<div id="dv1">
<div id="dv2">
<div id="dv3"></div>
</div>
</div>
<script src="common.js"></script>
<script>
my$("dv1").onclick = function() {
console.log(this.id);
}
my$("dv2").onclick = function() {
console.log(this.id);
}
my$("dv3").onclick = function() {
console.log(this.id);
}
</script>
</body>
```
### 2、阻止事件传递(不止冒泡)
#### 2.1、方式一
`window.event.cancelBubble = true; `
注意: Chrome,IE8 支持,firefox 不支持
#### 2.2、方式二
在事件处理函数中传一个参数 e,然后调用 `e.stopPropagation(); `
注意:Chrome,firefox 支持, IE8 不支持。
> window.event 和 e 都是事件处理参数对象,一个是 IE 标准,一个是 firefox 标准。
```html
<body>
<div id="dv1">
<div id="dv2">
<div id="dv3"></div>
</div>
</div>
<script src="common.js"></script>
<script>
my$("dv1").onclick = function() {
console.log(this.id);
}
my$("dv2").onclick = function() {
console.log(this.id);
window.event.cancelBubble = true;
}
my$("dv3").onclick = function(e) {
console.log(this.id);
e.stopPropagation();
}
</script>
</body>
```
> 这时候可以写兼容代码的,由于用到 window ,但是没学到 BOM,所以先不写。
### 3、事件的三个阶段
1. 事件捕获阶段(从外向内) ===> 阶段 1
2. 事件目标阶段(最开始触发事件的目标)===> 阶段 2
3. 事件冒泡阶段(从里向外) ===> 阶段 3
- 通过事件处理参数对象 `e.eventPhase` 属性可以查看当前事件所处的阶段。
若为1:捕获阶段
若为2:目标阶段
若为3:冒泡阶段
- addEventListener 绑定事件处理方法中第三个参数:控制事件的阶段
true: 控制事件为捕获阶段
false: 控制事件为冒泡阶段
- 一般默认使用冒泡阶段,很少使用捕获阶段。
```html
<body>
<div id="dv1">
<div id="dv2">
<div id="dv3"></div>
</div>
</div>
<script src="common.js"></script>
<script>
my$("dv1").addEventListener("click", function(e) {
console.log(this.id +" --- "+ e.eventPhase);
}, false);
my$("dv2").addEventListener("click", function(e) {
console.log(this.id +" --- "+ e.eventPhase);
}, false);
my$("dv3").addEventListener("click", function(e) {
console.log(this.id +" --- "+ e.eventPhase);
}, false);
// -------------------------------------------------------
// addEventListener 的第三个参数为 false
// 点击最里面的 dv3
//dv3 --- 2 : 因为是冒泡阶段,从里向外,从 dv3开始,dv3是目标,所以为2
//dv2 --- 3:冒泡阶段,所以为3
//dv1 --- 3:冒泡阶段,所以为3
// 如果将 false 都改为 true 的话:
// 点击最里面的 dv3
//dv1 --- 1:捕获阶段,从外向里,从dv1开始捕获,所以dv1为1
//dv2 --- 1:捕获阶段,从外向里
//dv3 --- 2:捕获阶段,从外向里,到达dv3目标,随意dv3为目标阶段。
</script>
</body>
```
**案例:为同一个元素绑定多个不同的事件指向相同的事件处理函数。**
```html
<body>
<input type="button" value="按钮" id="btn" >
<script src="common.js"></script>
<script>
my$("btn").onclick = func;
my$("btn").onmouseover = func;
my$("btn").onmouseout = func;
function func(e) {
switch(e.type) {
case "click" :
console.log("onclick");
break;
case "mouseover" :
console.log("onmouseover");
break;
case "mouseout" :
console.log("onmouseout");
break;
default:
break;
}
}
</script>
</body>
```
> 使用事件处理参数对象的 type 属性可以判断事件触发时候,事件的类型,从而做出相应的事件处理。
## 二、百度搜索案例
目标:在搜索框输入关键字,自动在搜索框下方显示相关内容。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
#dv1 {
width: 500px;
margin-top: 100px;
margin-left: 200px;
font: 400 18px/30px "Microsoft Yahei";
color: #595959;
}
input {
width: 500px;
height: 30px;
}
.dvv {
width: 500px;
/*height: 10px;*/
border: 1px solid green;
}
.ps {
padding: 2px 0 2px 5px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="dv1">
<input type="text" placeholder="日向雏田" id="txt">
</div>
<script src="common.js"></script>
<script>
var KeyWords = [
"旋涡鸣人", "旋涡辛久奈", "旋风小子", "旋风少女",
"日向雏田", "日向花火", "日向本家",
"奈良鹿丸", "奈良大佐",
"旗木卡卡西"
];
my$("txt").onkeyup = function () {
while(my$("dv2")) {
my$("dv1").removeChild(my$("dv2"));
}
// console.log(this.value);
var findArr = []; // 每次输入文字的时候都先清除临时数组
for (var i = 0; i < KeyWords.length; i++) {
if (KeyWords[i].indexOf(this.value) === 0) {
// console.log("yes");
findArr.push(KeyWords[i]);
}
}
// 文本框输入了内容,并且临时数组不为空
if ((findArr.length !== 0) && (this.value.length !== 0)) {
var dvObj = document.createElement("div");
dvObj.className = "dvv";
dvObj.id = "dv2";
my$("dv1").appendChild(dvObj);
for (var i = 0; i < findArr.length; i++) {
var pObj = document.createElement("p");
pObj.className = "ps";
setInnerText(pObj, findArr[i]);
my$("dv2").appendChild(pObj);
pObj.onmouseover = f1; // 循环里面不要使用匿名函数
pObj.onmouseout = f2;
}
}
};
function f1() {
this.style.backgroundColor = "greenyellow";
}
function f2() {
this.style.backgroundColor = "";
}
</script>
</body>
</html>
```
> 1、这里的候选数据本来应该来自服务器,这里用数组来模拟。
>
> 2、这里使用的是鼠标输入文字后的鼠标抬起事件:onkeyup。
>
> 3、 需要准备个临时数组存储于文本框输入文字匹配的字符串。
>
> 4、当搜索框的文本为空或者临时数组的内容为空时,循环删除下拉列表。
>
> 5、之所以输入多个文字,但是只创建了一个下拉列表的原因是因为在输入第二个文字的时候,先输入的其实是字母,这个时候不匹配,而我们在每次鼠标抬起的时候会清空临时数组,所以这个时候会先删除下拉列表,当我们输入第二个文字的时候,再重新创建相匹配的下拉列表。
>
> 6、每次进入鼠标抬起按键时,如果有下拉列表就循环删除。
>
> 7、注意在循环里面不要使用匿名函数。
## 三、阻止默认事件
**阻止超链接默认跳转**
```html
<body>
<!--行内方式一-->
<a href="http://www.baidu.com" onclick="alert('------'); return false;">百度</a>
<!--行内方式二-->
<a href="http://www.baidu.com" onclick="return f1()">百度</a>
<script>
function f1() {
alert("---------");
return false;
}
</script>
<!--外部方式一(函数方式)-->
<a href="http://www.baidu.com" id="ah">百度</a>
<script>
document.getElementById("ah").onclick = function () {
alert("------");
return false;
};
</script>
<!--外部方式二(事件方式)-->
<a href="http://www.baidu.com" id="ah">百度</a>
<script>
document.getElementById("ah").onclick = function (e) {
alert("------");
e.preventDefault();
};
</script>
</body>
```
> 1、阻止超链接的跳转:返回给 onclick 事件一个` return false`,而不单单是 false。
>
> 2、方式二:当使用内联 js 的时候,onclick 里面是 f1() 而不是 f1。是函数的执行,而不是函数体本身。但是在外面写 js 的时候,赋值给 onclick 的是函数体本身,认不是函数的执行。
>
> 3、方式二中之所以加 return,是因为 f1() 执行后返回的是 false,而不是 return false,所以要加一个 return。
>
> 4、方式四:调用事件参数对象的 preventDefault() 方法:`e.preventDefault();` 可以阻止超链接跳转。注意 IE8 不支持。
| Daotin/Web/03-JavaScript/02-DOM/08-事件冒泡.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/02-DOM/08-事件冒泡.md",
"repo_id": "Daotin",
"token_count": 5707
} | 13 |
## 1、滑动解锁
要求:滑动滑块到末尾跳转页面,不成功,滑块回到起点。
```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>
<style>
* {
margin: 0;
padding: 0;
position: relative;
}
html,
body {
background-color: #ddd;
}
#box1 {
width: 300px;
height: 500px;
margin: 50px auto;
background-color: #aaa;
overflow: hidden;
}
#box2 {
width: 300px;
height: 30px;
margin-top: 400px;
background-color: #eee;
position: relative;
}
#box3 {
width: 50px;
height: 30px;
background-color: red;
/* border-radius: 15px; */
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="box1">
<div id="box2">
<div id="box3"></div>
</div>
</div>
</body>
<script src="../js/daotin.js"></script>
<script>
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var box3 = document.getElementById("box3");
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
box3.onmousedown = function (e) {
var evt = window.event || e;
box3.style.transition = "none";
var mouseLeft = evt.clientX + scrollLeft;
var mouseTop = evt.clientY + scrollTop;
// var box1Left = box1.offsetLeft;
var box1Left = parseInt(getStyle(box1, "margin-left"));
// var relaLeft = mouseLeft - parseInt(getStyle(box3, "left"));
var relaLeft = mouseLeft - box1Left;
// console.log(box1Left);
document.onmousemove = function (e) {
var evt = window.event || e;
mouseLeft = evt.clientX + scrollLeft;
box3.style.left = mouseLeft - relaLeft - box1Left + "px";
var box3Left = parseInt(getStyle(box3, "left"));
var dis = parseInt(getStyle(box1, "width")) - parseInt(getStyle(box3, "width"))
if (box3Left >= dis) {
console.log("OK");
document.onmousemove = null;
box1.style.backgroundColor = "red";
box2.style.display = "none";
box3.style.display = "none";
}
};
document.onmouseup = function (e) {
var evt = window.event || e;
document.onmousemove = null;
box3.style.left = 0;
box3.style.transition = "1s";
};
};
</script>
</html>
```

## 2、滑动验证
要求:滑动图标到指定的位置完成验证。
```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>
<style>
* {
margin: 0;
padding: 0;
position: relative;
}
html,
body {
background-color: #ddd;
}
#box1 {
width: 300px;
height: 500px;
margin: 50px auto;
background-color: #aaa;
overflow: hidden;
}
#box2 {
width: 300px;
height: 30px;
margin-top: 300px;
background-color: #000;
position: relative;
}
#box3 {
width: 30px;
height: 30px;
background-color: yellow;
border-radius: 50%;
position: absolute;
left: 0;
}
#box4 {
width: 30px;
height: 30px;
background-color: #fff;
border-radius: 50%;
position: absolute;
left: 200px;
}
#box5 {
width: 30px;
height: 30px;
background-color: red;
border-radius: 50%;
position: absolute;
left: 0;
}
</style>
</head>
<body>
<div id="box1">
<div id="box2">
<div id="box3"></div>
<div id="box4"></div>
</div>
<div id="box5">
</div>
</div>
</body>
<script src="../js/daotin.js"></script>
<script>
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var box3 = document.getElementById("box3");
var box4 = document.getElementById("box4");
var box5 = document.getElementById("box5");
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
box5.onmousedown = function (e) {
var evt = window.event || e;
box3.style.transition = "none";
box5.style.transition = "none";
var mouseLeft = evt.clientX + scrollLeft;
var mouseTop = evt.clientY + scrollTop;
var box1Left = parseInt(getStyle(box1, "margin-left"));
var relaLeft = mouseLeft - box1Left; // 点击后的相对距离
document.onmousemove = function (e) {
var evt = window.event || e;
mouseLeft = evt.clientX + scrollLeft;
var moveLeft = mouseLeft - relaLeft - box1Left;
var dis = parseInt(getStyle(box2, "width")) - parseInt(getStyle(box3, "width"))
if (moveLeft >= 0 && moveLeft <= dis) {
box5.style.left = mouseLeft - relaLeft - box1Left + "px";
box3.style.left = mouseLeft - relaLeft - box1Left + "px";
}
};
};
document.onmouseup = function (e) {
var evt = window.event || e;
document.onmousemove = null;
var box5Left = parseInt(getStyle(box3, "left"));
var disBox4 = parseInt(getStyle(box4, "left"));
if (Math.abs(box5Left - disBox4) <= 1) {
alert("OK");
}
box3.style.left = 0;
box3.style.transition = "1s";
box5.style.left = 0;
box5.style.transition = "1s";
};
</script>
</html>
```

## 3、顺序点击验证码
要求:按顺序点击验证码才可以验证成功。
代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>dom操作</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
#box {
width: 200px;
margin: 50px auto;
position: relative;
}
#showrand {
width: 200px;
height: 30px;
text-align: center;
line-height: 30px;
background-color: #0b333f;
color: #ffffff;
}
#tip {
position: absolute;
height: 200px;
width: 200px;
left: 0;
top: 35px;
background-color: #0b333f;
}
#tip span {
position: absolute;
display: block;
height: 30px;
width: 30px;
border-radius: 50%;
text-align: center;
line-height: 30px;
background-color: #ff3333;
color: #ffffff;
}
#tip span .num {
position: absolute;
left: 0;
top: 0;
display: block;
height: 14px;
width: 14px;
background-color: #00FF00;
text-align: center;
line-height: 14px;
font-size: 12px;
color: red;
}
</style>
</head>
<body>
<div id="box">
<div id="showrand">点击显示验证码
</div>
<div id="tip">
</div>
</div>
</body>
<script src="../js/daotin.js"></script>
<script>
var box = document.getElementById("box");
var showRand = document.getElementById("showrand");
var tip = document.getElementById("tip");
var source = "我喜欢敲代码学习是我快乐";
var NUM = 4;
function resetCode(e) {
showRand.innerHTML = getSecurityCode(source, NUM);
for (let i = 0; i < NUM; i++) {
if (tip.children[0]) {
tip.removeChild(tip.children[0]);
i--;
}
}
for (let i = 0; i < NUM; i++) {
var span = document.createElement("span");
span.style.left = Math.floor(Math.random() * 170) + "px";
span.style.top = Math.floor(Math.random() * 170) + "px";
span.innerHTML = showRand.innerHTML[i];
span.setAttribute("index", i);
tip.appendChild(span);
}
};
showRand.onclick = function (e) {
resetCode();
spanTap();
};
function spanTap() {
var spanList = document.querySelectorAll("#tip span");
var count = 0;
var tmp = "";
for (let j = 0; j < NUM; j++) {
spanList[j].onclick = function (e) {
tmp += this.innerHTML;
var littleSpan = document.createElement("span");
littleSpan.className = "num";
littleSpan.innerHTML = count;
this.appendChild(littleSpan);
this.style.backgroundColor = "gray";
count++;
if (count == NUM) {
if (tmp == showRand.innerHTML) {
alert("success");
} else {
resetCode();
spanTap();
}
}
};
}
};
</script>
</html>
```
 | Daotin/Web/03-JavaScript/02-DOM/案例01:几种常见的验证码.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/02-DOM/案例01:几种常见的验证码.md",
"repo_id": "Daotin",
"token_count": 5459
} | 14 |
对象的深拷贝
```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>
</body>
<script src="js/objectDepthCopy.js"></script>
<script>
var obj = {
a: 1,
b: 2,
c: function () {
},
set d(value) {
},
get d() {
},
e: {
a: 3,
b: {
a: 10,
b: 20
},
c: function () {
},
set d(value) {
},
get d() {
},
e: {
a: 5,
b: [1, 2, 3, 4],
c: function () {
},
set d(value) {
},
get d() {
}
}
}
}
var copyObj = {};
objectDepthCopy(copyObj, obj);
console.log(copyObj);
</script>
</html>
```
objectDepthCopy.js
```js
function objectDepthCopy(target, source) {
// 获取source属性列表
var names = Object.getOwnPropertyNames(source);
for (var i = 0; i < names.length; i++) {
// 每个属性的属性描述符
var desc = Object.getOwnPropertyDescriptor(source, names[i]);
// 如果names[i]属性的值是个对象
if (typeof desc.value === "object" && desc.value !== null) {
var obj = Array.isArray(desc.value) ? [] : {};
Object.defineProperty(target, names[i], {
writable: desc.writable,
enumerable: desc.enumerable,
configurable: desc.configurable,
value: obj
});
// names[i]属性的值是个对象,对象的value值单独赋值
objectDepthCopy(obj, desc.value);
} else {
// 如果names[i]属性的值不是对象,那么desc仍然是对象,只是writable,enumerable,configurable均为true。
Object.defineProperty(target, names[i], desc);
}
};
}
```
> 注意:递归的效率极其低下,因为都是函数的副本。并且递归不能超过 30000,否则会报错。
| Daotin/Web/03-JavaScript/04-JavaScript高级知识/案例01:对象深拷贝.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/04-JavaScript高级知识/案例01:对象深拷贝.md",
"repo_id": "Daotin",
"token_count": 1357
} | 15 |
## 一、服务器和客户端
服务器和客户端都是电脑,在硬件层面上没有明显的划分,配置很差的个人电脑任然可以作为服务器。
服务器如果想对外提供服务,必须安装相应的软件,所以不是服务器这台电脑可以提供服务,而是其安装的软件提供的服务。比如:
HTTP网页服务:Apache,Tomcat,IIS等
文件上传下载服务:VsFtp等
邮箱服务:SendMail 等
数据存储服务:MySql,Oracle 等
### 1、网路相关概念
**IP 地址:**
地址是为了标注某个地点,方便查找。
互联网上有很多公司,每家公司都有自己的服务器。通过 IP 地址就可以找到特定的服务器,使用这台服务器提供的服务。比如百度服务器的地址为:123.125.114.144。
可以通过:`ipconfig` 查看本机 IP 地址。
**域名:**
由于 IP 地址是一串数字,很难记忆,为了便于人们记忆,就把域名代替 IP 地址。
比如:www.baidu.com 就是百度的域名。
通过 `ping www.baidu.com` 可以查看域名对应的 IP 地址。
**DNS 域名解析器**
DNS 又叫做域名解析服务器,提供域名和 ip 地址的映射关系。
**一台电脑访问服务器的过程如下:**
比如访问百度服务器:当在地址栏输入 www.baidu.com 点击回车的时候,浏览器会将域名发送到 DNS 域名解析器,解析出 www.baidu.com 对应的 ip 为:123.125.114.144,然后再将这个域名返回给浏览器,浏览器再从这个 ip 访问百度服务器。
然而,一般我们电脑上有一个 hosts 文件,里面保存的是域名和 ip 地址的映射关系。其实在地址栏输入 www.baidu.com 点击回车的时候,会先从 hosts 文件中读取是否有对应域名的 ip 地址,如果有直接返回浏览器访问 ip 地址,如果找不到再从 DNS 域名解析器解析出 ip 地址访问。
本机 hosts 文件的路径:C:\Windows\System32\drivers\etc\hosts
**端口**
当我们电脑找到一台服务器时,这台服务器可能会提供很多服务,如何区分客户端需要哪种服务就需要端口来区分。
比如:我们在访问百度提供的网页服务时,完整的写法为:`www.baidu.com:80`,80 这个端口就是百度提供网页服务的,但是80这个端口比较特殊,可以省略不写。
再比如我们在设置邮箱客户端的时候,也需要指定端口号。
### 2、通信协议
通信协议就是事先商量好的规则。而计算机之间的通信也需要规则。
常见的协议有:
HTTP、HTTPS:超文本传输协议
FTP:文件传输协议
SMTP:简单邮件传输协议
## 二、WAMP 的安装配置
**什么是Wamp?**
Wamp指的是:Windows、Apache、MySQL、PHP 几个服务器软件的缩写,类似的还有 LAMP,只不过把 Windows 换成了 Linux。
**为什么要安装 Wamp?**
以前我们写的 html 文件都是在本地执行的,现在我们想把我们的电脑变成一台服务器,然后将我们的 html 界面以服务的方式提供给别的客户机访问。
**Wamp的安装配置**
安装很简单,略。
**Wamp 的简单配置:**
**配置访问权限**
默认情况下,apache 提供的网页服务只允许 localhost 和 127.0.0.1 (其实这两个是一个映射关系,在 hosts 里面有写)访问,如果我们想让别的客户机访问,就需要对配置文件进行修改。配置文件位于:C:\wamp\bin\apache\Apache2.4.4\conf\httpd.conf 将 268 行的 Deny from all 改成 Allow from all。
注意:在修改所有配置文件之前,都应该先做备份。
**网站根路径的配置**
默认情况下,网站的根路径为 c:\wamp\www ,在此目录下的文件才可以以服务的方式提供给别人访问,如果想更改这个路径,也需要修改 C:\wamp\bin\apache\Apache2.4.4\conf\httpd.conf 文件,将 DocumentRoot 修改为自己想要的目录。
```
DocumentRoot "I:/Web/Demo/php"
<Directory "I:/Web/Demo/php">
```
注意:修改之后,原路径 c:\wamp\www 将不可访问。
## 三、静态网站和动态网站
**静态网站**
所有的 HTML 代码全部都已经写好,任何人访问都是相同的。每次网页的改变,都需要修改 HTML 源码,而且如果有1000个 HTML 文件,就需要修改 1000 个 HTML代码,工作量巨大。
**动态网站**
一般动态网站通过数据库进行架构,动态网站的内容可以根据不同用户的不同需求展示不同的页面。一般是以 asp、jsp、php、aspx 等结尾。
| Daotin/Web/05-PHP&数据库/01-服务器相关概念.md/0 | {
"file_path": "Daotin/Web/05-PHP&数据库/01-服务器相关概念.md",
"repo_id": "Daotin",
"token_count": 3145
} | 16 |
跨域这个概念来自一个叫 “同源策略” 的东西。同源策略是浏览器上为了安全考虑实施的非常重要的安全机制。
Ajax 默认只能获取到同源的数据,对于非同源的数据,Ajax是获取不到的。
**什么是同源?**
协议、域名、端口全部相同。
比如一个界面地址为:http://www.example.com/dir/page.html 这个网址,在这个地址中要去访问下面服务器的数据,那么会发生什么情况呢?
| URL | 结果 | 原因 |
| ---------------------------------------- | ---- | ----------------- |
| https://www.example.com/dir/other.html | 不同源 | 协议不同,https 和 http |
| http://en.example.com/dir/other.html | 不同源 | 域名不同 |
| http://www.example.com:81/dir/other.html | 不同源 | 端口不同 |
| http://www.example.com/dir/page2.html | 同源 | 协议,域名,端口都相同 |
| http://www.example.com/dir2/page.html | 同源 | 协议,域名,端口都相同 |
如果使用 Ajax 获取非同源的数据,会报错,报错信息如下:
```
Failed to load http://hr.pcebg.efoxconn.com/checkUsername.php?uname=176: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.
```
那么。想要获取非同源地址的数据,就要使用跨域。不论是 Ajax 还是跨域,都是为了访问服务器的数据。简单的来说, **Ajax 是为了访问自己服务器的数据,跨域是为了访问别人服务器的数据(比如获取天气信息,航班信息等)。**
## 1、跨域的实现
### 1.1、引入外部 js 文件
我们可以通过 script 标签,用 script 标签的属性引入一个外部文件,这个外部文件是不涉及到同源策略的影响的。
```html
<script src="http://www.example.com/dir/xxx.js"></script>
```
然后,这个外部文件中有一个或几个方法的调用,这些方法的定义在自己的界面文件中,而我们想要的是方法的参数,可以在自己定义的方法中拿到。**这就是跨域的本质。**
### 1.2、引入外部 PHP 文件
script 引入的应该是 js 文件,如果我们想要引入 php 文件的话,就需要在 php 代码中,返回 js 格式的代码。
```php
<?php
echo "var str = 'hello'";
echo "func('123')";
?>
```
在我们 html 文件中:
```html
<script>
function func(data) { // 就为了获取参数
console.log(data);
}
</script>
<script src="http://www.example.com/xxx.php"></script>
```
再进一步,如果我们在 PHP 地址中传入了参数:
```php
<?php
$city = $_GET["city"];
if($city == "beijing") {
echo "func('获取到北京天气')";
} else {
echo "func('为获取到天气信息')";
}
?>
```
html 文件:
```html
<script>
function func(data) { // 就为了获取参数
console.log(data);
}
</script>
<script src="http://www.example.com/xxx.php?city=beijing"></script>
```
### 1.3、动态创建 script 标签
当然,如果只是手动的在php文件后面传入参数,就太固定了,那么我们可不可以根据用户的输入来获取不同城市天气信息呢?
答案是肯定的。**我们可以采取动态创建 script 的方式来获取用户想要的信息。**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>天气查询</h1><br>
<input type="text" placeholder="请输入城市" id="txt"><br>
<input type="button" value="获取天气" id="btn">
<script>
function func(data) {
console.log(data);
}
document.getElementById("btn").onclick = function () {
var city = document.getElementById("txt").value;
var script = document.createElement("script");
script.src = "http://hr.pcebg.efoxconn.com/checkUsername.php?city=" + city;
document.getElementsByTagName("head")[0].appendChild(script);
};
</script>
</body>
</html>
```
### 1.4、动态指定回调函数名称
还记得我们 html 中有个回调函数的定义吗?这个函数的名称是固定的,我们可不可以动态指定呢?答案也是肯定的,我们既然可以在 php 地址传递参数过去,就可以顺便把回调函数的名称也传递过去,动态的指定回调函数的名称。
```js
//...
function foo (data) {
console.log(data);
}
script.src = "http://hr.pcebg.efoxconn.com/checkUsername.php?city=" + city + "&callback=foo";
//...
```
外部 php 代码:
```php
<?php
$city = $_GET["city"];
$callback = $_GET["callback"];
if($city == "beijing") {
echo $callback . "('获取到北京天气')";
} else {
echo $callback . "('为获取到天气信息')";
}
?>
```
之后,再看我们在 script 里面写的 foo 函数的定义,会不会觉得很突兀?我们把它改成 window 的方法就可以了。
```js
window["foo"] = function(data) { console.log(data); };
```
然后把它放到按钮的点击事件中,这样就和按钮的点击事件融为一体了。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>天气查询</h1><br>
<input type="text" placeholder="请输入城市" id="txt"><br>
<input type="button" value="获取天气" id="btn">
<script>
document.getElementById("btn").onclick = function () {
window["foo"] = function(data) { console.log(data); };
var city = document.getElementById("txt").value;
var script = document.createElement("script");
script.src = "http://hr.pcebg.efoxconn.com/checkUsername.php?city=" + city + "&callback=foo";
document.getElementsByTagName("head")[0].appendChild(script);
};
</script>
</body>
</html>
```
> 在修改回调函数的名称时,只需修改两个部分就可以了(window["foo"] 和 "&callback=foo";),php 的代码不需要修改。
## 2、案例:淘宝提示词
**淘宝提示词接口**
| 地址 | https://suggest.taobao.com/sug |
| ------ | ------------------------------ |
| 作用描述 | 获取淘宝提示词接口 |
| 请求类型 | get 请求 |
| 参数 | q:关键词; callback:回调函数名称 |
| 返回数据格式 | jsonp格式 |
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="dv">
<h1>淘宝提示词</h1>
<input type="text" placeholder="请输入关键词" id="txt">
<input type="button" value="查询" id="btn">
<ul id="uu"></ul>
</div>
<script>
document.getElementById("btn").onclick = function () {
var script = document.createElement("script");
var txt = document.getElementById("txt").value;
script.src = "https://suggest.taobao.com/sug?q="+txt+"&callback=sug";
window["sug"] = function (data) {
var str = "";
if(data.result.length !== 0) {
for (var i = 0; i < data.result.length; i++) {
str += "<li>"+data.result[i]+"</li>";
}
document.getElementById("uu").innerHTML = str;
} else {
str = "<li>未找到关键词</li>";
document.getElementById("uu").innerHTML = str;
}
};
document.querySelector("head").appendChild(script);
};
</script>
</body>
</html>
```
## 3、案例:百度提示词
**百度提示词接口**
| 地址 | http://suggestion.baidu.com/su |
| ------ | ------------------------------ |
| 作用描述 | 获取百度提示词接口 |
| 请求类型 | get 请求 |
| 参数 | wd:关键词; cb:回调函数名称 |
| 返回数据格式 | jsonp格式 |
> PS:与淘宝提示词代码相同,只需要修改地址、参数即可。
我们从之前的 Ajax 的代码知道,这样的代码太过于冗余,我们需要对代码进行封装。
我们将实现的代码封装成一个 js 文件。
```js
//my-sug.js 文件
function myAjaxCross(obj) {
var defaults = {
url: "#", //地址
data: {}, // 业务逻辑参数 ,比如:wd=web&pwd=123
success: function (data) {}, // 参数传递回来的处理函数
jsonp: "callback", // 获取方法名的key值。是一个回调函数,由后端接口文档指定
jsonpCallback: "sug" // 获取方法名的value值,也就是方法名字
};
// 由 obj 传入的对象覆盖 defaults
for (var key in obj) {
defaults[key] = obj[key];
}
var script = document.createElement("script");
// 将 data 里面的参数拼接到 url 后面
var params = "";
for (var attr in defaults.data) {
params += attr + "=" + defaults.data[attr] + "&";
}
// 去掉最后多出来的 & 符号
if (params && (params !== "")) {
params = params.substring(0, params.length - 1);
}
// 再在地址后面拼接回调函数
script.src = defaults.url + "?" + params + "&" + defaults.jsonp + "=" + defaults.jsonpCallback;
console.log(script.src);
// 对回调函数进行定义,将参数传入自己定义的处理数据函数中
window[defaults.jsonpCallback] = function (data) {
defaults.success(data);
};
document.querySelector("head").appendChild(script);
}
```
下面以百度提示词为例,使用这个封装好的 js 文件。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="dv">
<h1>百度提示词</h1>
<input type="text" placeholder="请输入关键词" id="txt">
<input type="button" value="查询" id="btn">
<ul id="uu"></ul>
</div>
<script src="my-sug.js"></script>
<script>
document.getElementById("btn").onclick = function () {
myAjaxCross({
url: "http://suggestion.baidu.com/su",
data: {wd:document.getElementById("txt").value},
success: function (data) {
console.log(data);
var str = "";
if(data.s.length !== 0) {
for (var i = 0; i < data.s.length; i++) {
str += "<li>"+data.s[i]+"</li>";
}
document.getElementById("uu").innerHTML = str;
} else {
str = "<li>未找到关键词</li>";
document.getElementById("uu").innerHTML = str;
}
},
jsonp: "cb",
jsonpCallback: "sug"
});
};
</script>
</body>
</html>
```
## 4、使用 jQuery 获取跨域数据
类似 jQuery 封装好了 Ajax 一样,jQuery 也对跨域数据的获取进行了封装,调用方法跟 Ajax 一模一样。
我们还是以百度提示词举例,使用 jQuery 来获取数据。
```js
$.ajax({
url: "http://suggestion.baidu.com/su",
data: {wd: document.getElementById("txt").value},
success: function (data) {
console.log(data);
var str = "";
if(data.s.length !== 0) {
for (var i = 0; i < data.s.length; i++) {
str += "<li>"+data.s[i]+"</li>";
}
document.getElementById("uu").innerHTML = str;
} else {
str = "<li>未找到关键词</li>";
document.getElementById("uu").innerHTML = str;
}
},
dataType: "jsonp", // 重点
jsonp: "cb", // 根据需求指定,默认为:callback
jsonpCallback: xxx // 可以省略
});
```
> 1、dataType: "jsonp" 是重点,当 dataType 的类型为 jsonp 的时候,才能实现 jQuery 的跨域获取数据,否则只能使用同源策略。
>
> 2、jsonp: "cb" :根据后端需求指定
>
> 3、jsonpCallback: xxx:可以不需要。
## 5、完善myAjax方法达到能获取同源数据和非同源数据
主要借鉴了 jQuery 的处理方法,判断 dataType 的值。
```js
//跨域数据obj dataType=jsonp
function myAjax(obj){
if(obj.dataType == "jsonp") {
myAjax4Across(obj);
} else {
myAjax4Normal(obj);
}
}
function myAjax4Across(obj){
var defaults = {
type:"get",
url:"#",
data:{},
success:function(data){},
jsonp:"callback",
jsonpCallback:"hehe"
};
for(var key in obj) {
defaults[key] = obj[key];
}
var params = "";
for(var attr in defaults.data){
params += attr + "=" + defaults.data[attr] + "&";
}
if(params) {
params = params.substring(0,params.length-1);
defaults.url += "?" + params;
}
defaults.url += "&"+defaults.jsonp+"=" + defaults.jsonpCallback;
console.log(defaults.url);
var script = document.createElement("script");
script.src = defaults.url;
window[defaults.jsonpCallback] = function(data){
defaults.success(data);
};
var head = document.querySelector("head");
head.appendChild(script);
}
function myAjax4Normal(obj) {
var defaults = {
type:"get",
url:"#",
dataType:"json",
data:{},
async:true,
success:function(result){console.log(result);}
};
//obj中的属性,覆盖到defaults中的属性
//1、如果有一些属性只存在obj中,会给defaults中增加属性
//2、如果有一些属性在obj和defaults中都存在,会将defaults中的默认值覆盖
//3、如果有一些属性只在defaults中存在,在obj中不存在,这时候defaults中将保留预定义的默认值
for(var key in obj){
defaults[key] = obj[key];
}
var xhr = null;
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//得到params
// data:{
// uname:"zhangsan",
// age:"18"
// }// uname=zhangsan&age=18
var params = "";
for(var attr in defaults.data){
params += attr + "=" + defaults.data[attr] + "&";
}
if(params) {
params = params.substring(0,params.length - 1);
}
if(defaults.type == "get") {
defaults.url += "?" + params;
}
xhr.open(defaults.type,defaults.url,defaults.async);
if(defaults.type == "get") {
xhr.send(null);
} else if(defaults.type == "post") {
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(params);
}
if(defaults.async) {
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var result = null;
if(defaults.dataType == "json") {
result = xhr.responseText;
result = JSON.parse(result);
} else if(defaults.dataType == "xml") {
result = xhr.responseXML;
} else {
result = xhr.responseText;
}
defaults.success(result);
}
}
};
} else {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var result = null;
if(defaults.dataType == "json") {
result = xhr.responseText;
result = JSON.parse(result);
} else if(defaults.dataType == "xml") {
result = xhr.responseXML;
} else {
result = xhr.responseText;
}
defaults.success(result);
}
}
}
}
```
## 6、模板引擎的使用
我们之前做的所有工作都是为了获取服务器的数据,不管是同源的数据还是跨域的数据。获取到数据之后,我们就需要将其在页面上展示出来。前端的界面都是由标签构成的,这种展示的过程其实最主要的就是生成 html 标签。
我们之前显示获取到的数据是使用字符串拼接成 li 标签,然后将 li 标签添加到 ul 标签的方式。这种做法有个弊端,就是当界面特别复杂的时候,使用字符串拼接的方式就会很复杂,对于后期的维护也会很困难。
下面介绍的模板引擎就可以很方便的生成 html 标签。
模板引擎的本质是:**将数据和模板结合来生成 html 片段。**
这里介绍一款效率很高的模板引擎:artTemplate,这个模板引擎是腾讯公司出品的开源模板引擎。
**使用步骤:**
1、引入 js 文件
2、定义模板
3、将数据和模板结合起来生成 html 片段
4、将 html 片段渲染到界面中
### 6.1、改造百度提示案例
还是以百度提示词为例:
比如我想生成类型如下格式标签的代码片段:
```html
<li>
<div>
<span>索引</span>
<span>索引对应的值</span>
</div>
</li>
```
源代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="dv">
<h1>百度提示词</h1>
<input type="text" placeholder="请输入关键词" id="txt">
<input type="button" value="查询" id="btn">
<ul id="uu"></ul>
</div>
<script src="../jquery-1.12.4.min.js"></script>
<script src="template.js"></script>
<!--定义模板-->
<!--1、指定type类型为type="text/html",而不是jacascript-->
<!--2、指定一个id值-->
<!--3、循环遍历接收到的数据,生成html片段-->
<!--each 就是循环遍历data中的数组,在百度案例里面,data中的数组是s,所以遍历s -->
<!--as 是关键字,i 是索引,value是索引的值。-->
<!--在代码片段中使用的时候,记得要加两个大括号来使用变量的值-->
<script type="text/html" id="myart">
{{each s as value i}}
<li>
<div>
<span>结果{{i}} --- </span>
<span>{{value}}</span>
</div>
</li>
{{/each}}
</script>
<script>
document.getElementById("btn").onclick = function () {
$.ajax({
url: "http://suggestion.baidu.com/su",
data: {wd: document.getElementById("txt").value},
success: function (data) {
// 将数据和模板结合起来
// template 是模板引擎提供的
// 第一个参数:自定义的模板的id值
// 第二个参数:接收到的后端的数据
var html = template("myart", data);
document.getElementById("uu").innerHTML = html;
},
dataType: "jsonp", // 重点
jsonp: "cb" // 根据需求指定,默认为:callback
});
};
</script>
</body>
</html>
```
### 6.2、artTemplate的常用语法
**示例1:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模板引擎</title>
<script type="text/javascript" src="./template.js"></script>
<script type="text/html" id="resultTemplate">
<h1>{{title}}</h1>
{{each books as value i}}
<div>{{value}}</div>
{{/each}}
</script>
<script type="text/javascript">
window.onload = function(){
var data = {
title : '四大名著图书信息',
books:['三国演义','水浒传','西游记','红楼梦']
};
var html = template("resultTemplate",data);
var container = document.querySelector("#container");
container.innerHTML = html;
}
</script>
</head>
<body>
<div id="container">
</div>
</body>
</html>
```
> 在定义的模板里面,使用的是 data 里面的属性,可以直接使用,比如 title。
**示例2:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="./template.js"></script>
<script id="test" type="text/html">
{{if isAdmin}}
<h1>{{title}}</h1>
<h2>一共有{{count}}条数据</h2>
<ul>
{{each list as value i}}
<li>索引 {{i + 1}} :{{value}}</li>
{{/each}}
</ul>
{{/if}}
{{if !isAdmin}}
<h1>没有任何数据</h1>
{{/if}}
</script>
<script>
window.onload = function(){
var data = {
title: '条件判断基本例子',
isAdmin: true,
list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他']
};
data.count = data.list.length;
var html = template("test",data);
document.querySelector("#content").innerHTML = html;
}
</script>
</head>
<body>
<div id="content">
</div>
</body>
</html>
```
> 1、定义的模板里面也可以加条件判断语句:{{if data里面的属性}}。
>
> 2、可以将得到的数据进行处理,比如增加 count 属性,然后在定义的模板里面直接使用。
**实例3:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="./template.js"></script>
<!-- data.data -->
<script id="test" type="text/html">
<ul>
{{each arr as value i}}
<li>{{value}}</li>
{{/each}}
</ul>
</script>
<script>
window.onload = function(){
var data = ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他'];
var temp = {};
temp.arr = data;
var html = template("test",temp);//data.xxx
document.querySelector("#content").innerHTML = html;
}
</script>
</head>
<body>
<div id="content">
<ul>
<li>文艺</li>
<li>博客</li>
</ul>
</div>
</body>
</html>
```
> 1、当我们获取的数据没有内部属性的时候,比如上面的例子,不可以直接使用 data,不然程序会认定为 data.data 属性,而这个属性是不存在的。
>
> 2、我们可以通过增加一个对象,增加这个对象的一个属性 arr,其值为 data,然后遍历 arr 来使用。
**示例4:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="./template.js"></script>
<script id="test" type="text/html">
<p>转义:{{#value}}</p>
<p>不转义: {{value}}</p>
</script>
<script>
window.onload = function(){
// 这里的数据当中包含特殊字符
var data = {
value: '<span style="color:#F00">hello world!</span>'
};
var html = template('test', data);
document.getElementById('content').innerHTML = html;
}
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
```
> 1、我们获取到的数据也可能是 html 的代码。
>
> 2、在定义的模板中调用的时候,通过在属性前加 “#” 可以将 html 代码转义处理。否则只会理解成字符串。
## 7、第三方接口网站
MOB:www.mob.com,里面有个 MobAPI 服务,有很多好玩的 API 接口,比如天气、电影、汽车等。
一般第三方的接口都需要先注册,然后获得 appkey,才能使用。
## 8、存在的问题
**问题:如果第三方接口返回的是 json 而不是 jsonp 格式的数据的话,怎么办么?**
我们知道 Ajax 需要返回的是函数的调用,函数的参数是 json 格式的,如果第三方直接返回一个 json 的字符串怎么办呢?由于不是返回的函数调用,按照跨域的方式肯定是会报错的。
**解决办法:通过自己的服务器作为中介来实现。**
首先,自己的服务器后台,不管是 PHP 还是 JSP,来获取第三方的数据,由于后台不受同源策略的限制,所以自己的服务器获取到 json 数据后,echo 回来,然后我们前端再使用 Ajax 的四步骤来获取后台返回的 json 类型的字符串。
| Daotin/Web/06-Ajax/10-跨域.md/0 | {
"file_path": "Daotin/Web/06-Ajax/10-跨域.md",
"repo_id": "Daotin",
"token_count": 13776
} | 17 |
## 一、常见的响应式框架
随着Web应用变的越来越复杂,在大量的开发过程中我们发现有许多功能模块非常相似,比如轮播图、分页、选项卡、导航栏等,开发中往往会把这些具有通用性的功能模块进行一系列封装,使之成为一个个组件应用到项目中,可以极大的节约开发成本,将这些通用的组件缩合到一起就形成了前端框架。
**常见的响应式框架有:**
**1、Bootstrap**
官网:http://www.bootcss.com/

简洁、直观、强悍的前端开发框架,让web开发更迅速、简单。
来自 Twitter,粉丝众多,是目前最受欢迎的前端框架。
**2、Amaze UI**
官网:http://amazeui.org/

中国首个开源 HTML5 跨屏前端框架。
Amaze ~ 妹子UI,国人开发,后起之秀!
**3、Framework7**
官网:http://www.framework7.cn/

Framework7 是一款免费、开源的移动HTML框架,主要用于开发混合手机App或者网页App,某些应用场景的体验几乎与原生开发的 iOS 和 Android 应用一模一样,同时也是一款不可获取的应用原型快速开发及展示工具。
Framework7 主要的作用就是让你有机会能够使用 HTML,CSS 和 JavaScript 简单明了地开发 iOS 和 Android 应用。Framework7 是完全开放的,它完全没有限制你进行打开脑洞的创造,同时还提供了一些解决方案。
Framework7 并不支持所有平台。为了给你带来最好的体验感受,它只专注于 iOS 和 Google Material 设计风格。
## 二、bootstrap
Bootstrap是当前最流行的前端UI框架(有预制界面组件)
Bootstrap 是最受欢迎的 HTML、CSS 和 JS 框架,用于开发响应式布局、移动设备优先的 WEB 项目。
Bootstrap是基于HTML5和CSS3开发的,它在jQuery的基础上进行了更为个性化和人性化的完善,形成一套自己独有的网站风格,并兼容大部分jQuery插件。
> Bootstrap 的所有 JavaScript 插件都依赖 jQuery。
### 1、BootStrap的版本了解
- 2.x.x:兼容性好 / 代码不够简洁,功能不够完善
- 3.x.x:稳定性好,放弃了IE6-IE7,对IE8的支持一般 /偏向于响应式布局开发,移动设备优先的web项目开发
- 4.x.x:测试阶段,偏向于响应式,移动设备
### 2、bootstrap 基本模板
```html
<!--说明页面是html5页面-->
<!DOCTYPE html>
<!--页面使用的语言环境-->
<html lang="zh-CN">
<head>
<!--指定当前页面的字符编码-->
<meta charset="utf-8">
<!--如果是IE,会使用最新的渲染引擎进行渲染-->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--标准的视口设置-->
<meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=0">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap核心样式文件 -->
<link href="../lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries: 这两个文件的引入是为了支持IE8下面的html5元素和媒体查询:因为在IE8下面默认不支持HTML5和媒体查询,所以需要引入两个插件-->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// 如果通过file://来查看文件,那么respond.js文件不能正常工作,说明必须在http://形式下访问才有用-->
<!--html5shiv.min.js:为了在IE8下面支持HTML标签
respond.min.js:为了在IE8下面支持媒体查询-->
<!--[if lt IE 9]> <!--只有IE9之前才会加载这两个文件 lt:less than-->
<script src="../lib/html5shiv/html5shiv.min.js"></script>
<script src="../lib/respond.js/respond.js"></script>
<![endif]-->
</head>
<body>
<h1>你好,世界!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) bootstrap是依赖jquery的-->
<script src="../lib/jquery/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed bootstarp核心js文件-->
<script src="../lib/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
```
### 3、bootstrap 布局容器
bootstrap 的 css 样式中,有一个起着支撑整个页面框架的容器,也叫**布局容器**,它类似于我们的版心结构。
1、`.container` 实现固定宽度并支持响应式布局的容器。
当屏幕宽度 > 1200,则页面宽度固定为 1170px
当屏幕宽度 992~1200,则页面宽度固定为 970px
当屏幕宽度 768~992,则页面宽度固定为 750px
当屏幕宽度 < 768,则页面宽度固定为 100%.
2、`.container-fluid` :实现宽度为全屏 100% 的容器。
### 4、bootstrap 栅格系统
概念:Bootstrap 提供了一套响应式、移动设备优先的流式栅格系统,随着屏幕或视口(viewport)尺寸的增加,系统会**默认分为12列**。
栅格系统用于通过一系列的行(row)与列(column)的组合来创建页面布局,你的内容就可以放入这些创建好的布局中。
**“行(row)”必须包含在 .container (固定宽度)或 .container-fluid (100% 宽度)中,以便为其赋予合适的排列(aligment)和内补(padding)。**
**你的内容应当放置于“列(column)”内**,并且,只有“列(column)”可以作为行(row)”的直接子元素。你可以使用类似 .row 和 .col-xs-4 这种预定义的类,可以用来快速创建栅格布局。Bootstrap 源码中定义的 mixin 也可以用来创建语义化的布局。
通过为“列(column)”设置 padding 属性,从而创建列与列之间的间隔(gutter)。通过为 .row 元素设置负值 margin 从而抵消掉为 .container 元素设置的 padding,也就间接为“行(row)”所包含的“列(column)”抵消掉了padding。
栅格系统中的列是通过指定1到12的值来表示其跨越的范围。例如,三个等宽的列可以使用三个 `.col-xs-4` 来创建。
如果一“行(row)”中包含了的“列(column)”大于 12,多余的“列(column)”所在的元素将被作为一个整体另起一行排列。
**示例:**
```html
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3"></div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3"></div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3"></div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3"></div>
</div>
```
解释:上面四个div,如果在超小屏幕上就 100%显示(占12栅格);在小屏幕上,每个div占50%显示;在中等屏幕上,每个div占25%显示;在大屏幕上,每个div占33.33%显示。
**栅格参数:**
>`.col-xs- `:超小屏幕 手机 (<768px)
>
>`.col-sm-` : 小屏幕 平板 (≥768px)
>
>`.col-md-` : 中等屏幕 桌面显示器 (≥992px)
>
>`.col-lg-` : 大屏幕 大桌面显示器 (≥1200px)
**注意:**
1.栅格系统是往上兼容的:意味着小屏幕上的效果在大屏幕上也是可以正常显示的人,但是大屏幕上的设置在小屏幕上却无法正常显示。
2.Row可以再次嵌套在列中。如果不能填满整列,则默认从左排列,如果超出,则换行展示。
### 5、列排序
- `col-xs-offset-n`:往右偏移 n 个栅格,但是会影响后面所有元素也偏移 n 个栅格。(内部通过 margin-left 实现的)
- `col-xs-push/pull-n`:push 往右推,pull 往左拉。往右偏移 n 个栅格,可能会与后面的元素重叠。(内部实现原理通过定位实现)
### 6、列嵌套
列嵌套就是列中还可以嵌套行,注意不能嵌套版心 container 和 container-fluid。
因为:
如果在外层没有再包含container,那么嵌套列的宽度就是参参照当前所在的栅格;
如果外层添加了container,那么参照就是核心样式文件所设置的容器宽度
```html
<div class="container">
<div class="row">
<div class="col-xs-1">1</div>
<div class="col-xs-1">2</div>
<div class="col-xs-6">
<!--
1.如果在外层没有再包含container,那么嵌套列的宽度就是参参照当前所在的栅格
2.如果外层添加了container,那么参照就是核心样式文件所设置的容器宽度-->
<!--<div class="container">-->
<div class="row">
<div class="col-xs-6">3</div> <!--这里的6占的是直接父div的一半,而不是container的一半-->
<div class="col-xs-6">4</div>
</div>
<!--</div>-->
</div>
<div class="col-xs-1">4</div>
<div class="col-xs-1">5</div>
<div class="col-xs-1">6</div>
<div class="col-xs-1">7</div>
</div>
</div>
```
### 7、响应式工具
**(无向上兼容,内部实现是一个具体的范围,没有波及到其他区域)**
> .hidden-xs :在超小屏幕下不可见
>
> .hidden-sm :在小屏幕下不可见
>
> .hidden-md :在中等屏幕下不可见
>
> .hidden-lg :在大屏幕下不可见
**示例:**
```html
<div class="container">
<div class="row">
<div class="col-xs-1 hidden-sm">1</div> <!--在小屏幕下不可见-->
<div class="col-xs-1 hidden-xs">2</div> <!--在超小屏幕下不可见-->
<div class="col-xs-6 hidden-lg"> <!--在大屏幕下不可见-->
<div class="col-xs-1">4</div>
<div class="col-xs-1">5</div>
<div class="col-xs-1">6</div>
<div class="col-xs-1">7</div>
</div>
</div>
```
| Daotin/Web/07-移动Web开发/07-Bootstrap.md/0 | {
"file_path": "Daotin/Web/07-移动Web开发/07-Bootstrap.md",
"repo_id": "Daotin",
"token_count": 6065
} | 18 |
// 封装移动端的tap事件
var fingerTap = {
tap: function (dom, callback) {
// 判断dom是否存在
if((!dom) || (typeof dom != "object")) {
return;
}
var startX, startY, endX, endY, startTime, endTime;
dom.addEventListener("touchstart", function (e) {
// 不止一个手指
if(e.targetTouches.length > 1) {
return;
}
startX = e.targetTouches[0].clientX;
startY = e.targetTouches[0].clientY;
// 点击时记录毫秒数
startTime = Date.now();
});
dom.addEventListener("touchend", function (e) {
// 不止一个手指
if(e.changedTouches.length > 1) {
return;
}
// 之所以使用changedTouches,是因为手指离开后就没有targetTouches了
endX = e.changedTouches[0].clientX;
endY = e.changedTouches[0].clientY;
// 记录离开手指的毫秒数
endTime = Date.now();
//如果是长按操作就返回
if(endTime - startTime > 300) {
return;
}
// 判断从按下到抬起手指在一定的范围滑动也算tap事件
if((Math.abs(endX-startX) <= 6) && (Math.abs(endY-startY) <= 6)) {
// tap点击事件的处理函数
callback && callback(e);
}
});
}
}; | Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/js/tap.js/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/js/tap.js",
"repo_id": "Daotin",
"token_count": 928
} | 19 |
/* 头部块 */
.wjs-header {
height: 50px;
line-height: 50px;
border-bottom: 1px solid #ccc;
}
.wjs-header .row {
height: 100%;
text-align: center;
}
.wjs-header .row > div:nth-of-type(-n+3) {
border-right: 1px solid #ccc;
}
.wjs-header .row .code {
display: block;
position: relative;
}
.wjs-header .row .code > img {
display: none;
position: absolute;
border: 1px solid #ccc;
border-top: none;
left: 50%;
transform: translateX(-50%);
top: 49px;
}
.wjs-header .row .code:hover > img {
display: block;
}
.wjs-header .row > div:nth-last-of-type(1) > .btn-danger {
background-color: #e92322;
border-color: #e92322;
}
.wjs-header .row > div:nth-last-of-type(1) > .btn {
padding: 3px 15px;
}
.wjs-header .row > div:nth-last-of-type(1) > .btn-link {
text-decoration: none;
color: #aaa;
}
/*导航条*/
.wjs-nav.navbar {
margin-bottom: 0;
}
.wjs-nav .navbar-brand {
height: 80px;
line-height: 50px;
font-size: 40px;
}
.wjs-nav .navbar-brand > span:nth-of-type(1) {
color: #e92322;
}
.wjs-nav .navbar-brand > span:nth-of-type(2) {
color: #333;
}
.wjs-nav .navbar-toggle {
margin-top: 23px;
}
.wjs-nav .navbar-nav > li {
height: 80px;
}
.wjs-nav .navbar-nav > li > a {
height: 80px;
line-height: 50px;
font-size: 16px;
}
.wjs-nav .navbar-nav > li > a:hover,
.wjs-nav .navbar-nav > li > a:active {
color: #777;
border-bottom: 3px solid #e92322;
}
.wjs-nav .navbar-nav .active a,
.wjs-nav .navbar-nav .active a:hover,
.wjs-nav .navbar-nav .active a:active {
background-color: transparent;
border-bottom: 3px solid #e92322;
}
/*轮播图*/
/*
w<768px-移动端:图片会随着屏幕的缩小自动适应--缩小
img的宽度为100%,通过img标签来实现
w>=768px:
图片做为背景,当屏幕宽度变宽的时候,会显示更多的图片的两边区域
1.background-image添加图片
2.添加background-position:center center
3.background-size:cover
*/
.wjs-banner .bigImg {
width: 100%;
height: 410px;
/*去除图片基线*/
display: block;
background-position: center center;
background-size: cover;
}
.wjs-banner .smallImg img {
width: 100%;
/*去除图片基线*/
display: block;
}
/*信息块*/
.wjs-info {
padding: 20px;
}
.wjs-info .wjs_icon {
font-size: 26px;
}
.wjs-info .row > div {
margin: 10px 0;
}
.wjs-info .row > div > a:hover {
color: #e92322;
}
/*预约块*/
.wjs-reverse {
height: 60px;
line-height: 60px;
border-top: 1px solid #ccc;
border-bottom: 1px solid #ccc;
}
.wjs-reverse .wjs_icon {
font-size: 18px;
}
.wjs-reverse a:hover {
color: #e92322;
}
.wjs-reverse .col-sm-9 > a:last-of-type {
color: #e92322;
border-bottom: 1px dashed #e92322;
}
/*产品块*/
.wjs-product {
clear: both;
background-color: #eee;
}
.wjs-product li {
height: 100px;
line-height: 100px;
padding: 0 10px;
}
.wjs-product li > a {
margin: 0;
border: none;
line-height: 50px;
}
.wjs-product li a:hover {
border: none;
border-bottom: 3px solid #e92322;
}
.wjs-product li.active > a,
.wjs-product li.active a:hover,
.wjs-product li.active a:focus {
background-color: transparent;
border: none;
border-bottom: 3px solid #e92322;
}
/*产品块*/
.wjs-product .tabs-parent {
width: 100%;
overflow: hidden;
}
.wjs-product .wjs-pBox {
height: 100%;
background-color: #fff;
margin-top: 20px;
position: relative;
box-shadow: 1px 1px 5px #ccc;
}
.wjs-product .wjs-pBox > .wjs-pLeft {
height: 100%;
margin-right: 100px;
padding: 10px 0;
font-size: 12px;
position: relative;
}
.wjs-product .wjs-pBox > .wjs-pLeft > p {
font-size: 16px;
text-align: center;
}
.wjs-product .wjs-pBox > .wjs-pLeft .row {
margin-left: 0;
margin-right: 0;
}
.wjs-product .wjs-pBox > .wjs-pLeft .row > div:nth-of-type(even) {
text-align: right;
}
.wjs-product .wjs-pBox > .wjs-pRight {
width: 100px;
height: 100%;
position: absolute;
right: 0;
top: 0;
border-left: 1px dashed #ccc;
text-align: center;
padding-top: 40px;
}
.wjs-product .wjs-pBox > .wjs-pRight > .wjs-pRight-tip {
width: 100%;
}
.wjs-product .wjs-pBox > .wjs-pRight > .wjs-pRight-tip span {
font-size: 12px;
border-radius: 3px;
cursor: pointer;
}
.wjs-product .wjs-pBox > .wjs-pRight > .wjs-pRight-tip span:first-of-type {
border: 1px solid #e92322;
color: #e92322;
}
.wjs-product .wjs-pBox > .wjs-pRight > .wjs-pRight-tip span:last-of-type {
border: 1px solid blue;
color: blue;
}
.wjs-product .wjs-pBox > .wjs-pRight > b {
font-size: 40px;
color: #e92322;
}
.wjs-product .wjs-pBox > .wjs-pRight > sub {
bottom: 0;
color: #e92322;
}
.wjs-product .wjs-pBox > .wjs-pRight::before,
.wjs-product .wjs-pBox > .wjs-pRight::after {
content: "";
width: 10%;
height: 10px;
border-radius: 5px;
background-color: #eee;
position: absolute;
left: -5px;
}
.wjs-product .wjs-pBox > .wjs-pRight::before {
top: -5px;
}
.wjs-product .wjs-pBox > .wjs-pRight::after {
bottom: -5px;
}
.wjs-product .wjs-pBox.active {
background-color: #e92322;
}
.wjs-product .wjs-pBox.active .wjs-pLeft {
color: #fff;
}
.wjs-product .wjs-pBox.active .wjs-pLeft::before {
content: "\e915";
font-family: "wjs";
position: absolute;
left: 0;
top: -4px;
font-size: 26px;
}
.wjs-product .wjs-pBox.active .wjs-pRight b,
.wjs-product .wjs-pBox.active .wjs-pRight sub,
.wjs-product .wjs-pBox.active .wjs-pRight p {
color: #fff;
}
/*新闻块*/
.wjs-news {
padding: 20px;
/*设置li元素间的虚线*/
}
.wjs-news .wjs_nTitle {
line-height: 50px;
font-size: 25px;
border-bottom: 1px solid #ccc;
text-align: center;
position: relative;
}
.wjs-news .wjs_nTitle::before {
content: "";
width: 8px;
height: 8px;
border-radius: 4px;
border: 1px solid #ccc;
position: absolute;
bottom: -4px;
right: -8px;
}
.wjs-news .wjs_newsLine {
width: 1px;
height: 100%;
position: absolute;
border-left: 1px dashed #e92322;
left: 45px;
top: 0;
}
.wjs-news .nav-tabs {
border-bottom: none;
/*媒体查询设置li元素的样式*/
}
.wjs-news .nav-tabs > li {
margin-bottom: 60px;
}
.wjs-news .nav-tabs > li > a {
background-color: #ccc;
width: 60px;
height: 60px;
border: none;
border-radius: 50%;
}
.wjs-news .nav-tabs > li > a:hover {
border: none;
background-color: #e92322;
}
.wjs-news .nav-tabs > li.active > a {
border: none;
background-color: #e92322;
}
.wjs-news .nav-tabs > li .wjs_icon {
font-size: 30px;
color: #fff;
}
.wjs-news .nav-tabs > li:last-of-type {
margin-bottom: 0;
}
@media screen and (min-width: 768px) and (max-width: 992px) {
.wjs-news .nav-tabs li {
margin: 20px 30px;
}
}
@media screen and (max-width: 768px) {
.wjs-news .nav-tabs li {
margin: 20px 0;
width: 25%;
}
}
.wjs-news .tab-content .wjs_newslist {
list-style: none;
}
.wjs-news .tab-content .wjs_newslist > li {
line-height: 60px;
}
/*合作块*/
.wjs-partner {
background-color: #eee;
padding: 20px;
text-align: center;
}
.wjs-partner h3 {
width: 100%;
}
.wjs-partner ul {
list-style: none;
display: inline-block;
}
.wjs-partner ul > li {
float: left;
margin: 0 15px;
}
.wjs-partner ul .wjs_icon {
font-size: 80px;
}
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/css/wjs-index.css/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/css/wjs-index.css",
"repo_id": "Daotin",
"token_count": 3373
} | 20 |
/*! Respond.js v1.4.0: min/max-width media query polyfill. (c) Scott Jehl. MIT Lic. j.mp/respondjs */
(function( w ){
"use strict";
//exposed namespace
var respond = {};
w.respond = respond;
//define update even in native-mq-supporting browsers, to avoid errors
respond.update = function(){};
//define ajax obj
var requestQueue = [],
xmlHttp = (function() {
var xmlhttpmethod = false;
try {
xmlhttpmethod = new w.XMLHttpRequest();
}
catch( e ){
xmlhttpmethod = new w.ActiveXObject( "Microsoft.XMLHTTP" );
}
return function(){
return xmlhttpmethod;
};
})(),
//tweaked Ajax functions from Quirksmode
ajax = function( url, callback ) {
var req = xmlHttp();
if (!req){
return;
}
req.open( "GET", url, true );
req.onreadystatechange = function () {
if ( req.readyState !== 4 || req.status !== 200 && req.status !== 304 ){
return;
}
callback( req.responseText );
};
if ( req.readyState === 4 ){
return;
}
req.send( null );
};
//expose for testing
respond.ajax = ajax;
respond.queue = requestQueue;
// expose for testing
respond.regex = {
media: /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi,
keyframes: /@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi,
urls: /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,
findStyles: /@media *([^\{]+)\{([\S\s]+?)$/,
only: /(only\s+)?([a-zA-Z]+)\s?/,
minw: /\([\s]*min\-width\s*:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/,
maxw: /\([\s]*max\-width\s*:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/
};
//expose media query support flag for external use
respond.mediaQueriesSupported = w.matchMedia && w.matchMedia( "only all" ) !== null && w.matchMedia( "only all" ).matches;
//if media queries are supported, exit here
if( respond.mediaQueriesSupported ){
return;
}
//define vars
var doc = w.document,
docElem = doc.documentElement,
mediastyles = [],
rules = [],
appendedEls = [],
parsedSheets = {},
resizeThrottle = 30,
head = doc.getElementsByTagName( "head" )[0] || docElem,
base = doc.getElementsByTagName( "base" )[0],
links = head.getElementsByTagName( "link" ),
lastCall,
resizeDefer,
//cached container for 1em value, populated the first time it's needed
eminpx,
// returns the value of 1em in pixels
getEmValue = function() {
var ret,
div = doc.createElement('div'),
body = doc.body,
originalHTMLFontSize = docElem.style.fontSize,
originalBodyFontSize = body && body.style.fontSize,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
// 1em in a media query is the value of the default font size of the browser
// reset docElem and body to ensure the correct value is returned
docElem.style.fontSize = "100%";
body.style.fontSize = "100%";
body.appendChild( div );
if( fakeUsed ){
docElem.insertBefore( body, docElem.firstChild );
}
ret = div.offsetWidth;
if( fakeUsed ){
docElem.removeChild( body );
}
else {
body.removeChild( div );
}
// restore the original values
docElem.style.fontSize = originalHTMLFontSize;
if( originalBodyFontSize ) {
body.style.fontSize = originalBodyFontSize;
}
//also update eminpx before returning
ret = eminpx = parseFloat(ret);
return ret;
},
//enable/disable styles
applyMedia = function( fromResize ){
var name = "clientWidth",
docElemProp = docElem[ name ],
currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
styleBlocks = {},
lastLink = links[ links.length-1 ],
now = (new Date()).getTime();
//throttle resize calls
if( fromResize && lastCall && now - lastCall < resizeThrottle ){
w.clearTimeout( resizeDefer );
resizeDefer = w.setTimeout( applyMedia, resizeThrottle );
return;
}
else {
lastCall = now;
}
for( var i in mediastyles ){
if( mediastyles.hasOwnProperty( i ) ){
var thisstyle = mediastyles[ i ],
min = thisstyle.minw,
max = thisstyle.maxw,
minnull = min === null,
maxnull = max === null,
em = "em";
if( !!min ){
min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
if( !!max ){
max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){
if( !styleBlocks[ thisstyle.media ] ){
styleBlocks[ thisstyle.media ] = [];
}
styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
}
}
}
//remove any existing respond style element(s)
for( var j in appendedEls ){
if( appendedEls.hasOwnProperty( j ) ){
if( appendedEls[ j ] && appendedEls[ j ].parentNode === head ){
head.removeChild( appendedEls[ j ] );
}
}
}
appendedEls.length = 0;
//inject active styles, grouped by media type
for( var k in styleBlocks ){
if( styleBlocks.hasOwnProperty( k ) ){
var ss = doc.createElement( "style" ),
css = styleBlocks[ k ].join( "\n" );
ss.type = "text/css";
ss.media = k;
//originally, ss was appended to a documentFragment and sheets were appended in bulk.
//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
head.insertBefore( ss, lastLink.nextSibling );
if ( ss.styleSheet ){
ss.styleSheet.cssText = css;
}
else {
ss.appendChild( doc.createTextNode( css ) );
}
//push to appendedEls to track for later removal
appendedEls.push( ss );
}
}
},
//find media blocks in css text, convert to style blocks
translate = function( styles, href, media ){
var qs = styles.replace( respond.regex.keyframes, '' ).match( respond.regex.media ),
ql = qs && qs.length || 0;
//try to get CSS path
href = href.substring( 0, href.lastIndexOf( "/" ) );
var repUrls = function( css ){
return css.replace( respond.regex.urls, "$1" + href + "$2$3" );
},
useMedia = !ql && media;
//if path exists, tack on trailing slash
if( href.length ){ href += "/"; }
//if no internal queries exist, but media attr does, use that
//note: this currently lacks support for situations where a media attr is specified on a link AND
//its associated stylesheet has internal CSS media queries.
//In those cases, the media attribute will currently be ignored.
if( useMedia ){
ql = 1;
}
for( var i = 0; i < ql; i++ ){
var fullq, thisq, eachq, eql;
//media attr
if( useMedia ){
fullq = media;
rules.push( repUrls( styles ) );
}
//parse for styles
else{
fullq = qs[ i ].match( respond.regex.findStyles ) && RegExp.$1;
rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
}
eachq = fullq.split( "," );
eql = eachq.length;
for( var j = 0; j < eql; j++ ){
thisq = eachq[ j ];
mediastyles.push( {
media : thisq.split( "(" )[ 0 ].match( respond.regex.only ) && RegExp.$2 || "all",
rules : rules.length - 1,
hasquery : thisq.indexOf("(") > -1,
minw : thisq.match( respond.regex.minw ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
maxw : thisq.match( respond.regex.maxw ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
} );
}
}
applyMedia();
},
//recurse through request queue, get css text
makeRequests = function(){
if( requestQueue.length ){
var thisRequest = requestQueue.shift();
ajax( thisRequest.href, function( styles ){
translate( styles, thisRequest.href, thisRequest.media );
parsedSheets[ thisRequest.href ] = true;
// by wrapping recursive function call in setTimeout
// we prevent "Stack overflow" error in IE7
w.setTimeout(function(){ makeRequests(); },0);
} );
}
},
//loop stylesheets, send text content to translate
ripCSS = function(){
for( var i = 0; i < links.length; i++ ){
var sheet = links[ i ],
href = sheet.href,
media = sheet.media,
isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
//only links plz and prevent re-parsing
if( !!href && isCSS && !parsedSheets[ href ] ){
// selectivizr exposes css through the rawCssText expando
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
translate( sheet.styleSheet.rawCssText, href, media );
parsedSheets[ href ] = true;
} else {
if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base) ||
href.replace( RegExp.$1, "" ).split( "/" )[0] === w.location.host ){
// IE7 doesn't handle urls that start with '//' for ajax request
// manually add in the protocol
if ( href.substring(0,2) === "//" ) { href = w.location.protocol + href; }
requestQueue.push( {
href: href,
media: media
} );
}
}
}
}
makeRequests();
};
//translate CSS
ripCSS();
//expose update for re-running respond later on
respond.update = ripCSS;
//expose getEmValue
respond.getEmValue = getEmValue;
//adjust on resize
function callMedia(){
applyMedia( true );
}
if( w.addEventListener ){
w.addEventListener( "resize", callMedia, false );
}
else if( w.attachEvent ){
w.attachEvent( "onresize", callMedia );
}
})(this);
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/respond/respond.js/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/respond/respond.js",
"repo_id": "Daotin",
"token_count": 4097
} | 21 |
## 1、内置模块的应用
### 1.1、node 路由
在 `http.createServer((req, res) => {});`中
通过 `req.url`可以获取客户端传递的路由地址。
通常,http.createServer函数至少执行两次,一次是根路径`/` ,一次是`/favicon.ico`
当我们访问 `http://localhost:3000` 的时候,默认的是主路径和图标路径。
如果有路由的时候,比如:`http://localhost:3000/other` 的时候,我们希望访问的是`other.html`,此时`req.url` 的地址为`/other` 和 `/favicon.ico` 。
所以,我们可以根据不同的路由地址来跳转到不同的页面。
我们先封装一个模块用来获取页面的内容:
```js
// rf.js
let rf = require("fs");
module.exports = (url, fn) => {
rf.readFile(url, "utf-8", (err, data) => {
if (!err) {
fn(data);
}
});
}
```
然后我们在开启服务界面进行调用:
```js
let http = require("http");
let rf = require("./rf"); // 自己的rf.js文件(注意自定义的模块需要加路径)
let server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8"
});
let path = req.url; // 获取路由地址
let url = "";
switch (path) {
case "/":
case "/home":
// rf("index.html", (data) => {
// res.end(data);
// });
url = "index.html";
break;
case "/other":
// rf("other.html", (data) => {
// res.end(data);
// });
url = "other.html";
break;
default:
// rf("404.html", (data) => {
// res.end(data);
// });
url = "404.html";
break;
}
// 根据不同的路由,获取不同的页面内容进行显示
rf(url, (data) => {
res.end(data);
});
});
server.listen(3000, () => {
console.log("server running at http://localhost:3000");
});
```
> 注意:自定义的模块需要加路径
我们把大量逻辑代码写到服务主界面显得特别乱,所以关于路由的操作,我们封装成一个模块叫`router.js`。
```js
// router.js
let rf = require("./rf");
module.exports = {
home(req, res) {
rander("index.html", req, res);
},
other(req, res) {
rander("other.html", req, res);
},
err(req, res) {
rander("404.html", req, res);
},
// 由于插入的图片的格式不同,所以写法也有差异
img(req, res) {
res.writeHead(200, {
"Content-Type": "image/jpeg"
});
rf("../img/s1.jpg", (data) => {
res.end(data, "binary");
}, "binary");
}
}
function rander(url, req, res) {
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8"
});
rf(url, (data) => {
res.end(data);
});
}
```
由于插入图片的形式,读取文件的模块也有改变
```js
let rf = require("fs");
module.exports = (url, fn, ecode = "utf-8") => {
rf.readFile(url, ecode, (err, data) => {
if (!err) {
fn(data);
}
});
}
```
增加 ecode参数,设置ES6中默认参数为 “utf-8”.
然后在主服务模块中,只需要调用router对象中的函数。
```js
let http = require("http");
let router = require("./router");
let server = http.createServer((req, res) => {
let path = req.url;
path = path.substring(1); // 把路由的/去掉
if (router[path]) {
router[path](req, res); // 直接获取router的函数即可显示不同的界面
} else {
router["err"](req, res);
}
});
server.listen(3000, () => {
console.log("server running at http://localhost:3000");
});
```
### 1.2、前端通过ajax和node交互
- get请求
首先是前端发起ajax请求。
```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>
<h1>首页</h1>
<div>
i d: <input type="text" id="user">
pwd: <input type="text" id="pwd">
</div>
<button id="btn">发送ajax请求</button>
</body>
<!-- <script src="../js/jquery-1.12.4.js"></script> -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
// 当点击button的时候,像服务器发出ajax请求
$("button").on("click", () => {
$.ajax({
type: "get",
url: "/ajax",
data: {
user: $("#user").val(),
pwd: $("#pwd").val()
},
dataType: "json",
success: function (response) {
console.log(response); // {code:200,msg:"成功"}
}
});
});
</script>
</html>
```
由于是get请求,所以路由地址不纯净,需要处理,才能进行路由操作。
```js
let http = require("http");
let router = require("./router");
let url = require("url");
let qs = require("querystring");
let server = http.createServer((req, res) => {
// 由于是get请求,所以获取到的req.url为/ajax?user=daotin&pwd=111
// 通过url模块,可以获取ajax请求的路由地址
let path = url.parse(req.url,true,true).pathname;
path = path.substring(1);
if (router[path]) {
router[path](req, res);
} else {
if (path === "") {
router["home"](req, res);
} else {
router["err"](req, res);
}
}
});
server.listen(3000, () => {
console.log("server running at http://localhost:3000");
});
```
服务器的具体实现模块router的操作如下:
```js
let rf = require("./rf");
module.exports = {
home(req, res) {
rander("index.html", req, res);
},
other(req, res) {
rander("other.html", req, res);
},
err(req, res) {
rander("404.html", req, res);
},
img(req, res) {
res.writeHead(200, {
"Content-Type": "image/jpeg"
});
rf("../img/s1.jpg", (data) => {
res.end(data, "binary");
}, "binary");
},
// 获取客户端针对/ajax路由的请求,然后返回给客户端{code:1,msg:"成功"}
ajax(req, res) {
// 获取客户端传过来的数据
let data = url.parse(req.url, true).query; // 收到客户端的数据后,这里没有处理直接返回客户端成功。
res.writeHead(200, {
"Content-Type": "text/x-www-form-urlencoded"
});
let msg = {
code: 200,
msg: "成功"
}
res.end(JSON.stringify(msg));
}
}
function rander(url, req, res) {
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8"
});
rf(url, (data) => {
res.end(data);
});
}
```
当服务器收到路由为 `/ajax` 的路由请求时,就会回复一个对象形式的字符串,客户端收到后就会显示出来。
这就完成了客户端和服务器的数据交流操作。
- post请求
post请求的数据在 `req.url` 是获取不到的。我们知道在`http.createServer((req, res) => {}` 中req和res也是输入流和输出流,那么就可以像数据流一样来获取数据。
我们在router.js里面获取,而不主程序获取。
```js
// index.html
$("button").on("click", () => {
$.ajax({
type: "post",
url: "/ajax",
data: {
user: $("#user").val(),
pwd: $("#pwd").val()
},
dataType: "json",
success: function (response) {
console.log(response); // {code:1,msg:"成功"}
}
});
});
```
index.html只是将type由get改成post。
主程序里面:
```js
// main.js
let http = require("http");
let router = require("./router");
let url = require("url");
let server = http.createServer((req, res) => {
let path = url.parse(req.url,true,true).pathname;
path = path.substring(1);
if (router[path]) {
router[path](req, res);
} else {
if (path === "") {
router["home"](req, res);
} else {
router["err"](req, res);
}
}
});
server.listen(3000, () => {
console.log("server running at http://localhost:3000");
});
```
由于ajax的路由地址只有 `/ajax` 所以不用处理。主要的数据获取在router.js里面处理。
```js
// router.js
let rf = require("./rf");
let url = require("url");
module.exports = {
home(req, res) {
rander("index.html", req, res);
},
other(req, res) {
rander("other.html", req, res);
},
err(req, res) {
rander("404.html", req, res);
},
img(req, res) {
res.writeHead(200, {
"Content-Type": "image/jpeg"
});
rf("../img/s1.jpg", (data) => {
res.end(data, "binary");
}, "binary");
},
// 获取客户端针对/ajax路由的请求,然后返回{code:1,msg:"成功"}
ajax(req, res) {
// 由于是get请求,所以获取到的req.url为/ajax?user=daotin&pwd=111
// 通过url模块,可以获取ajax请求的路由地址
// let data = url.parse(req.url, true).query;
let str = "";
req.on("data", chunk => {
str += chunk.toString();
});
req.on("end", () => {
console.log(str); //user=11&pwd=22
res.writeHead(200, {
"Content-Type": "text/x-www-form-urlencoded"
});
let msg = {
code: 200,
msg: "成功"
}
res.end(JSON.stringify(msg));
});
}
}
function rander(url, req, res) {
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8"
});
rf(url, (data) => {
res.end(data);
});
}
```
于是,post形式的ajax也可以和node进行数据交互。
### 1.3、爬取网站的数据到自己网站
我们这里爬的是“搜狗小游戏”的一个列表,如下图:

其实,http模块除了可以作为服务器返回数据之外,还可以作为客户端发出请求。
我们通过get的方式获取“https://123.sogou.com/xyx/”的网页源代码。
```js
// httpRequestGames.js
let https = require("https");
module.exports = (url) => {
// "https://123.sogou.com/xyx/"
https.get(url, res => {
let html = "";
res.on("data", chunk => {
html += chunk;
});
res.on("end", () => {
console.log(html)
});
})
});
}
```
> 注意:有得网络协议是http,有的是https。
获取到的源代码很杂乱,怎么处理呢?
用正则表达式的话,也会写很多,太复杂了。
所以,这里有一个插件`cheerio` ,这个插件特别强大,这个插件可以把这个源代码当做jquery来操作。
这个插件需要先用`npm i cheerio -S` 先下载再引入。
```js
let https = require("https");
let cheerio = require("cheerio");
module.exports = (url, fn) => {
// "https://123.sogou.com/xyx/"
https.get(url, res => {
let html = "";
res.on("data", chunk => {
html += chunk;
});
res.on("end", () => {
// 使用cheerio.load将获得到html注入进去,就得到整个源代码对象,这里用 $ 表示。
let $ = cheerio.load(html);
let games = [];
// $(".xyx_slide")是源代码中ul这个类似DOM的元素,然后找下面的li元素,整个
// 操作非常类似jquery。
// 我们把名字,图片地址,下载地址保存到一个数组中。
// 最后给外界回调函数使用
$(".xyx_slide").find("li").each((index, item) => {
let game = {
name: $(item).find("span").text(),
href: $(item).find("a").attr("href"),
imgSrc: $(item).find("a img").attr("src")
}
games.push(game);
});
fn(games);
})
});
}
```

这就相当于我们获取了核心数据。
这个时候,我们需要自己的架子来插入这些数据了。
这里我们新建一个 `main.html` 文件作为架子。
```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>
<ul class="gameUL">
<li>
<a href="javascript:;">
<img src="" alt="">
</a>
<p>123</p>
</li>
</ul>
</body>
</html>
```
要把这个架子中插入数据,也是用到`cheerio` 的操作。
先要把所有的架子源代码读出来,这里写一个`readFile.js`插件,然后还有把数据插入架子的插件`mixture.js` 。
```js
// readFile.js
let fs = require("fs");
// 需要获取源代码的html文件,这里就是main.html
module.exports = (url, fn) => {
let rs = fs.createReadStream(url);
let html = "";
rs.on("data", chunk => {
html += chunk;
})
rs.on("end", () => {
fn(html)
});
}
```
```js
// mixture.js
let cheerio = require("cheerio");
// html就是架子
// data就是核心代码
module.exports = (html, data) => {
let $ = cheerio.load(html);
let ul = $(".gameUL");
let li = ul.find("li");
ul.empty();
// 注意:这里的item是类DOM元素,而不是类jQuery元素
data.map((item) => {
let newLi = li.clone(false);
newLi.find("a").attr("href", item.href);
newLi.find("img").attr("src", item.imgSrc);
newLi.find("p").text(item.name);
ul.append(newLi);
});
// 返回整个html源代码
return $.html();
}
```
所有的准备工作都做好了,那么我们就将它们渲染到页面吧:
```js
// httpResponseMain.js
let http = require("http");
let readHtml = require("./readHtml");
let requestDate = require("./httpRequestGames");
let mixture = require("./mixture");
http.createServer((req, res) => {
res.writeHead(200, {
"content-Type": "text/html; charset=utf-8"
});
// 读取架子和读取核心数据应该套在一起,因为都是异步操作。
readHtml("./main.html", (html) => {
requestDate("https://123.sogou.com/xyx/", data => {
let newHTML = mixture(html, data);
// 最后发送到页面显示
res.end(newHTML);
});
});
}).listen(3000, () => {
console.log("server running at http://localhost:3000");
});
```
于是我们的main.html显示如下:
 | Daotin/Web/10-Node.js/03-内置函数的应用.md/0 | {
"file_path": "Daotin/Web/10-Node.js/03-内置函数的应用.md",
"repo_id": "Daotin",
"token_count": 8579
} | 22 |
## 使用webpack开发vue
### 1、搭建webpack环境
```
npm init -y
```
这里只使用到html-webpack-plugin,ES6转换到ES5模块和vue模块
```
npm i html-webpack-plugin babel-loader@7.1.5 babel-core babel-preset-env webpack@3 -D
npm i vue -S
```
### 2、配置config文件
```js
let Hwp = require('html-webpack-plugin');
module.exports = {
entry: __dirname + '/src/main.js',
output: {
path: __dirname + '/dist',
filename: 'index.js'
},
devServer: {
contentBase: __dirname + '/dist',
port: 3000,
inline: true
},
plugins: [
new Hwp({
template: __dirname + '/src/index.html',
filename: 'index.html',
inject: true
})
],
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
]
}
}
```
### 4、测试vue项目
```js
// main.js
import Vue from 'vue'
let app = new Vue({
el: '#app',
data: {
username: 'daotin'
},
methods: {}
});
```
在index.html中
```html
<div id="app">
<p>{{username}}</p>
</div>
```
这时候会报错:

原因是:
在node_modules的vue文件夹下的package.json中可以看到:
```json
"main": "dist/vue.runtime.common.js",
```
当我们使用import或者require的时候,默认引入的是vue.runtime.common.js,而不是vue/dist下的vue.js文件,引入这个vue.js才可以使用 new Vue({}) 的形式。
解决办法:
1、修改为`"main": "dist/vue.js",`,不推荐,别人拷贝的项目无法运行
2、`import Vue from 'vue/dist/vue.js'`,缺点是写法太low。
3、在配置文件起别名(推荐)
```json
resolve: {
alias: {
'vue': 'vue/dist/vue.js'
}
}
```
> 注意:
>
> 如果上面引入的vue文件夹下package.json没有main属性,那么会引入vue文件夹下index.js文件,如果没有在尝试引入index.json文件,都没有?报错。
| Daotin/Web/12-Vue/11-结合webpack开发vue.md/0 | {
"file_path": "Daotin/Web/12-Vue/11-结合webpack开发vue.md",
"repo_id": "Daotin",
"token_count": 1154
} | 23 |
## 一、渲染元素标签是否显示
> 在jsx语法中,标签也是一种类型,可以直接赋值给变量,那么我们就可以通过一个flag来判断是否显示该变量,也就是这个标签。
```jsx
import ReactDOM from 'react-dom';
import React from 'react';
import propTypes from 'prop-types'
class Box extends React.Component {
constructor() {
super();
this.state = {
isShow: false,
};
}
render() {
// 通过isShow判断按钮是否显示
let btn = this.state.isShow ? <button>按钮</button> : null;
return (
<div>
{btn}
</div>
);
}
}
ReactDOM.render(<Box />, document.getElementById('app'));
```
## 二、渲染列表
使用古老的循环赋值方式:
```jsx
class Box extends React.Component {
constructor() {
super();
this.state = {
list: [
{ name: 'Daotin', age: 18 },
{ name: 'lvonve', age: 19 },
{ name: 'jielun', age: 20 }
]
};
}
render() {
let listLi = [];
this.state.list.map(item => {
listLi.push(
<li>
<h3>{item.name}</h3>
<p>{item.age}</p>
</li>
);
})
return (
<div>
<ul>{listLi}</ul>
</div>
);
}
}
```
## 三、数据双向绑定
新建一个login.js组件用来测试数据的双向绑定。
由于基本上所有组件,场合都会用到 React 插件,也就是需要
`import React from 'react'`
所以我们把React在config中配置成全局的,这样就不需要每次都写上面的代码了。
```js
let Webpack = require('webpack');
plugins: [
new Webpack.ProvidePlugin({
React: 'react'
})
]
```
> 记得修改后服务要重启!
新建的Login组件:
```jsx
export class Login extends React.Component {
constructor() {
super();
this.state = {
user: '',
pwd: ''
}
}
render() {
let { user, pwd } = this.state;
return (
<div>
<h3>Login</h3>
用户:<input type="text" value={user} />
密码:<input type="text" value={pwd} />
</div>
);
}
}
```
然后在父组件引入:
```jsx
import { Login } from './login';
ReactDOM.render(<Login></Login>, document.getElementById('app'));
```
我们发现input根本无法输入,这是因为react在初始化的时候,user和pwd为空,就强制视图为空,且无法修改。
如果想修改可以将value改为`defaultValue`。
但是这时候,虽然可以修改视图input,但是不能同步到数据模型中。
这时候就只能通过手动绑定`onChange`事件获取input中的数据,然后同步到数据模型。
```jsx
export class Login extends React.Component {
constructor() {
super();
this.state = {
user: '',
pwd: ''
}
this.userInput = this.userInput.bind(this);
this.pwdInput = this.pwdInput.bind(this);
}
render() {
let { user, pwd } = this.state;
return (
<div>
<h3>Login</h3>
用户:<input type="text" defaultValue={user} onChange={this.userInput} />
密码:<input type="text" defaultValue={pwd} onChange={this.pwdInput} />
<span>用户名:{user}</span>
<span>用户名:{pwd}</span>
</div>
);
}
// 用户名输入onChange事件
userInput(e) {
this.setState({
user: e.target.value
});
}
// 密码输入onChange事件
pwdInput(e) {
this.setState({
pwd: e.target.value
});
}
}
```
但是有时候我们并不需要实时的进行数据的双向绑定,而是在点击按钮提交的时候才核实输入的数据。
我们添加一个按钮进行数据的提交:
```jsx
export class Login extends React.Component {
constructor() {
super();
this.state = {
user: '',
pwd: ''
}
this.submit = this.submit.bind(this);
}
render() {
let { user, pwd } = this.state;
return (
<div>
<h3>Login</h3>
用户:<input type="text" defaultValue={user} ref="userObj" />
密码:<input type="text" defaultValue={pwd} ref="pwdObj" />
<button onClick={this.submit}>提交</button>
</div>
);
}
submit() {
let data = {
userValue: this.refs.userObj.value,
pwdValue: this.refs.pwdObj.value,
}
// 拿到input数据
console.log(data);
}
}
```
在标签中添加一个`ref`属性,然后在获取的时候,通过`this.refs.xxx`就能够拿到这个元素的DOM对象了。
| Daotin/Web/13-React/02-各种标签渲染,数据双向绑定.md/0 | {
"file_path": "Daotin/Web/13-React/02-各种标签渲染,数据双向绑定.md",
"repo_id": "Daotin",
"token_count": 3063
} | 24 |
## 一、Angular简介
### 1、什么是 Angular?
Angular 是一个开发平台。它能帮你更轻松的构建 Web 应用。Angular 集声明式模板、依赖注入、端到端工具和一些最佳实践于一身,为你解决开发方面的各种挑战。Angular 为开发者提升构建 Web、手机或桌面应用的能力。
### 2、Angular代码整体架构
Angular项目是由一个个模块组成。
**并且至少会有一个主模块,其他的模块在使用的时候,需要导入到主模块中使用。**
一个模块中只要包含三个部分:
- **组件 component:主要是显示视图的html**
- **管道 pipe:类似于过滤器的功能**
- **服务 server:用于封装业务逻辑代码**
## 二、第一个Angular项目
创建Angular项目使用Angular脚手架。
### 1、安装Angular脚手架:
```
npm i angular-cli -g
```
> 注意:有时候安装总是失败,npm不能使用淘宝镜像。

切换npm镜像到cnpm:

验证Angular-cli版本:
```
ng -v
```
如下图显示则为安装成功:

### 2、创建angular项目
在存放angular项目的文件夹下使用命令:
```
ng new firstAngular
```

看下app文件夹:

我们之前说过,一个angular项目至少要有一个主模块,app.module.ts就是主模块。上面的四个文件就是主模块中的一个组件。
```typescript
/*app.module.ts*/
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
// 模块装饰器
// 元数据装饰器
@NgModule({
declarations: [ //用于注册(挂载)当前模块中的组件或者管道
AppComponent//主组件
],
imports: [ //用于引入别的模块
BrowserModule,
FormsModule,
HttpModule
],
providers: [], //提供器 用于挂载服务server
bootstrap: [AppComponent] // 启动的是主组件
})
export class AppModule { }
```
Component主组件
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-root', //声明组件名
templateUrl: './app.component.html', //声明模板文件
styleUrls: ['./app.component.css'] //声明需要使用到的样式文件
})
export class AppComponent {
// stage-2 语法
title = 'app works!';
// stage-2 语法 与下面等价
// constructor(){
// this.title = "app.works"
// }
}
```
## 三、angular组件
### 1、创建组件
```js
ng g component Message // 简写 ng g c Message
```

> 创建类:
>
> ```
> ng g class Box // 简写 ng g cl Box
> ```
### 2、使用Message组件
在主组件Component中使用Message组件:

> 注意:
>
> 1、angualr可以有多个顶层元素。
>
> 2、angular组件的调用必须使用双标签。
在组件中,数据不需要写在state中,可以只写写在类中。
像主组件,title直接写在AppComponent中:
```typescript
export class AppComponent {
title = 'app works!';
}
```
> 注意:
>
> `title = 'app works!';`的写法是ES6的stage-2的语法,它原来的写法是这样的:
>
> `constructor() {
> this.title = 'app works!';
> }`
>
> 两者的写法等价。
## 四、typescript
我们发现,项目中所有的js文件全部替换成了ts文件。
**ts文件就是Typescript的缩写,Typescript是JavaScript语言的超集,类似于jsx于js的关系,是对js的进一步封装,扩展,优化等。**
下面是几个常见的特性:
### 1、变量的类型验证
typescript的变量可以直接对其类型进行限定。
语法:
```
变量名 : 类型
```
示例:定义一个Box类。
```typescript
export class Box {
constructor(username: string, age: number) {
this.username = username;
this.age = age;
}
}
```
类型验证可以加在任何地方:
`let user: Box = new Box('Daotin', 20);`
限定user为Box类型,如果user赋值时不是Box类型,则报错。
**泛型:**
```typescript
list: Array<Box> = [
new Box('Daotin', 20),
new Box('Daotin', 20),
new Box('Daotin', 20),
new Box('Daotin', 20),
];
```
类型验证时,如果是数组,数组中的每个元素也需要验证的话,需要使用`<>`来表示,这种方式叫做泛型。
### 2、修饰符
在类中声明的变量还可以用`public`,`private`进行访问限制。
```typescript
export class Box {
constructor(public username: string, private age: number) {
this.username = username;
this.age = age;
}
sayHi() {
console.log(this.age);
}
}
let box: Box = new Box('aaa', 11);
box.sayHi(); // 私有属性只能类内部访问
console.log(box.username); // 公有属性可以外部访问
```
当存在修饰符的时候,上面的constructor类似于:
```typescript
constructor(public username: string, private age: number) {
// this.username = username;
// this.age = age;
}
```
形参会自动转为实参,并且自动挂载到实例上,可以直接使用。
| Daotin/Web/14-Angular/01-Angular简介,项目搭建,组件创建,Typescript.md/0 | {
"file_path": "Daotin/Web/14-Angular/01-Angular简介,项目搭建,组件创建,Typescript.md",
"repo_id": "Daotin",
"token_count": 2942
} | 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:58
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for visit_total
-- ----------------------------
DROP TABLE IF EXISTS `visit_total`;
CREATE TABLE `visit_total` (
`visit_id` int(32) NOT NULL AUTO_INCREMENT,
`visit_date` date NULL DEFAULT NULL,
`visit_count` int(32) NULL DEFAULT NULL,
PRIMARY KEY (`visit_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步 - 创建数据库/visit_total.sql/0 | {
"file_path": "Humsen/web/docs/数据库部署/第1步 - 创建数据库/visit_total.sql",
"repo_id": "Humsen",
"token_count": 346
} | 26 |
package pers.husen.web.bean.vo;
import java.util.Date;
/**
* @author 何明胜
*
* 2017年9月30日
*/
public class VisitTotalVo {
private int visitId;
private int visitCount;
private Date visitDate;
/**
* @return the visitDate
*/
public Date getVisitDate() {
return visitDate;
}
/**
* @param visitDate the visitDate to set
*/
public void setVisitDate(Date visitDate) {
this.visitDate = visitDate;
}
/**
* @return the visitId
*/
public int getVisitId() {
return visitId;
}
/**
* @param visitId the visitId to set
*/
public void setVisitId(int visitId) {
this.visitId = visitId;
}
/**
* @return the visitCount
*/
public int getVisitCount() {
return visitCount;
}
/**
* @param visitCount the visitCount to set
*/
public void setVisitCount(int visitCount) {
this.visitCount = visitCount;
}
}
| Humsen/web/web-core/src/pers/husen/web/bean/vo/VisitTotalVo.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/bean/vo/VisitTotalVo.java",
"repo_id": "Humsen",
"token_count": 318
} | 27 |
package pers.husen.web.common.helper;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.sun.mail.util.MailSSLSocketFactory;
import pers.husen.web.common.constants.CommonConstants;
import pers.husen.web.common.constants.ResponseConstants;
import pers.husen.web.config.ProjectDeployConfig;
/**
* 发送邮件
*
* @author 何明胜
*
* 2017年10月20日
*/
public class SendEmailHelper {
private final Logger logger = LogManager.getLogger(SendEmailHelper.class.getName());
public static void main(String[] args) {
SendEmailHelper sendEmail = new SendEmailHelper();
sendEmail.sendEmail2Admin("何明胜", "123@qwe.com", "", "这网站不错");
}
public int sendEmail2RetrievePwd(String email, int randomCode) {
String subject = "【何明胜的个人网站】找回密码邮箱验证";
String mode = "您正在使用找回密码功能。";
return sendEmail2User(email, randomCode, subject, mode);
}
public int sendEmail2Register(String email, int randomCode) {
String subject = "【何明胜的个人网站】新用户注册邮箱验证";
String mode = "欢迎在【何明胜的个人网站】注册账号。";
return sendEmail2User(email, randomCode, subject, mode);
}
/**
* 修改邮箱验证原邮箱
*
* @param email
* @param randomCode
* @return
*/
public int sendEmail2ModifyEmailAuth(String email, int randomCode) {
String subject = "【何明胜的个人网站】用户修改邮箱验证原邮箱";
String mode = "您正在使用修改邮箱功能。第一步,验证码您的原邮箱。";
return sendEmail2User(email, randomCode, subject, mode);
}
/**
* 修改邮箱验证原邮箱
*
* @param email
* @param randomCode
* @return
*/
public int sendEmail2ModifyEmailBind(String email, int randomCode) {
String subject = "【何明胜的个人网站】用户修改邮箱绑定新邮箱";
String mode = "您正在使用修改邮箱功能。第二步,绑定您的新邮箱。";
return sendEmail2User(email, randomCode, subject, mode);
}
/**
* 发送验证码通用函数
*/
public int sendEmail2User(String email, int randomCode, String subject, String mode) {
try {
Properties properties = loadEmailInfo();
String fromUser = properties.getProperty("email.from.user", StringUtils.EMPTY);
String fromPassword = properties.getProperty("email.from.password", StringUtils.EMPTY);
Session session = setupSession(fromUser, fromPassword);
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// Set From: 头部头字段
message.setFrom(new InternetAddress(fromUser, "一格网站机器人", StandardCharsets.UTF_8.name()));
// 收件人电子邮箱 可用数组设置多个
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
// 设置标题
message.setSubject(subject);
// 设置邮件内容 html文本
String content = "尊敬的用户:" + "<br/>  您好!" + "<br/>  " + mode + "<br/>" + "<br/>  您的邮箱验证码【" + randomCode + "】,请于10分钟内输入,任何人都不会向您索取,请勿泄露。"
+ "<br/>  注:如果不是您发出的请求,说明您的邮箱可能被人冒用或者存在风险,请留意。" + "<br/><br/><br/>此致,一格";
message.setContent(content, "text/html;charset=UTF-8");
// 发送信息的工具
Transport transport = session.getTransport();
transport.connect();
// 对方的地址
transport.sendMessage(message, new Address[] { new InternetAddress(email) });
// 关闭连接
transport.close();
logger.info("发送邮件成功! 收件人:" + email);
return ResponseConstants.RESPONSE_OPERATION_SUCCESS;
} catch (MessagingException | UnsupportedEncodingException | GeneralSecurityException mex) {
logger.error(StackTrace2Str.exceptionStackTrace2Str(mex));
}
return ResponseConstants.RESPONSE_OPERATION_FAILURE;
}
/**
* 发邮件给站长
*/
public int sendEmail2Admin(String name, String email, String phone, String content) {
try {
Properties properties = loadEmailInfo();
String fromUser = properties.getProperty("email.from.user", StringUtils.EMPTY);
String fromPassword = properties.getProperty("email.from.password", StringUtils.EMPTY);
Session session = setupSession(fromUser, fromPassword);
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// Set From: 头部头字段
message.setFrom(new InternetAddress(fromUser, "一格机器人", StandardCharsets.UTF_8.name()));
// 收件人电子邮箱 可用数组设置多个
String toUser = properties.getProperty("email.to.user", StringUtils.EMPTY);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toUser));
// 设置标题
message.setSubject("个人网站联系站长邮件");
// 设置邮件内容 普通文本
content = "我亲爱的站长:<br/>  你好! 我是您的网站的一格机器人。<br/>  现在有人通过您的网站\"联系站长\"功能给您发邮件,详情如下:"
+ "<br/>" + "<br/>  姓名:" + name + "<br/>  手机:" + phone
+ "<br/>  邮箱:" + email + "<br/>  邮件内容:<br/>    " + content;
message.setContent(content, "text/html;charset=UTF-8");
// 发送信息的工具
Transport transport = session.getTransport();
transport.connect();
// 对方的地址
transport.sendMessage(message, new Address[] { new InternetAddress("husen@hemingsheng.cn") });
// 关闭连接
transport.close();
logger.info("发送邮件给站长成功! 收件人:" + email);
return 1;
} catch (MessagingException | UnsupportedEncodingException | GeneralSecurityException mex) {
logger.error(StackTrace2Str.exceptionStackTrace2Str(mex));
}
return 0;
}
/**
* 获取邮箱机器人登录邮箱session
*/
public Session setupSession(String fromEmail, String password) throws GeneralSecurityException {
// 建立属性对象
Properties properties = new Properties();
// 开启SSL
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
// 开启认证
properties.put("mail.smtp.auth", "true");
// 开启SSL
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
// 设置邮件服务器主机名
properties.setProperty("mail.host", "smtp.qq.com");
// 设置端口
properties.setProperty("mail.smtp.port", "465");
// 根据认证获取默认session对象
return Session.getDefaultInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
});
}
private Properties loadEmailInfo() {
Properties properties = new Properties();
try {
FileInputStream inputStream = null;
inputStream = new FileInputStream(ProjectDeployConfig.WEB_ROOT_PATH + CommonConstants.COMMON_CONFIG_FILE_RELATIVE_PATH);
properties.load(inputStream);
} catch (IOException e) {
logger.error(e);
}
return properties;
}
} | Humsen/web/web-core/src/pers/husen/web/common/helper/SendEmailHelper.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/common/helper/SendEmailHelper.java",
"repo_id": "Humsen",
"token_count": 3635
} | 28 |
package pers.husen.web.dao;
import java.util.ArrayList;
import pers.husen.web.bean.vo.MessageAreaVo;
/**
* @author 何明胜
*
* 2017年9月25日
*/
public interface MessageAreaDao {
/**
* 查询留言区所有留言
*
* @param messageId
* @return
*/
public ArrayList<MessageAreaVo> queryAllMessageArea(int messageId);
/**
* 插入新的留言
* @param mVo
* @return
*/
public int insertMessageNew(MessageAreaVo mVo);
}
| Humsen/web/web-core/src/pers/husen/web/dao/MessageAreaDao.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dao/MessageAreaDao.java",
"repo_id": "Humsen",
"token_count": 194
} | 29 |
package pers.husen.web.dbutil.assist;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
/**
* 设置PreparedStatement参数的工具类
*
* @author : 何明胜
*
* 2017年9月21日
*/
public class SetPsParamUtils {
/**
* 判断参数类型并转换
*
* @param index
* @param obj
* @param ps
* @throws SQLException
*/
public static void setParamInit(int index, Object obj, PreparedStatement ps) throws SQLException {
if(obj instanceof Integer) {
setParamInt(index, (Integer) obj, ps);
}
if(obj instanceof Long) {
setParamLong(index, (Long) obj, ps);
}
if(obj instanceof Double) {
setParamDouble(index, (Double) obj, ps);
}
if(obj instanceof String) {
setParamString(index, (String) obj, ps);
}
if(obj instanceof Date) {
setParamDate(index, (Date) obj, ps);
}
}
/**
* 设置int类型的参数
*
* @param index
* @param param
* @param ps
* @throws SQLException
*/
public static void setParamInt(int index, Integer param, PreparedStatement ps) throws SQLException {
ps.setInt(index, param);
}
/**
* 设置Long类型的参数
*
* @param index
* @param param
* @param ps
* @throws SQLException
*/
public static void setParamLong(int index, Long param, PreparedStatement ps) throws SQLException {
ps.setLong(index, param);
}
/**
* 设置Double类型的参数
*
* @param index
* @param param
* @param ps
* @throws SQLException
*/
public static void setParamDouble(int index, Double param, PreparedStatement ps) throws SQLException {
ps.setDouble(index, param);
}
/**
* 设置String类型的参数
*
* @param index
* @param param
* @param ps
* @throws SQLException
*/
public static void setParamString(int index, String param, PreparedStatement ps) throws SQLException {
ps.setString(index, param);
}
/**
* 设置Date->Timestamp类型的参数
*
* @param index
* @param param
* @param ps
* @throws SQLException
*/
public static void setParamDate(int index, Date param, PreparedStatement ps) throws SQLException {
Timestamp timestamp = new Timestamp(param.getTime());
ps.setTimestamp(index, timestamp);
}
} | Humsen/web/web-core/src/pers/husen/web/dbutil/assist/SetPsParamUtils.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dbutil/assist/SetPsParamUtils.java",
"repo_id": "Humsen",
"token_count": 906
} | 30 |
package pers.husen.web.service;
import java.util.ArrayList;
import pers.husen.web.bean.vo.CodeLibraryVo;
import pers.husen.web.dao.CodeLibraryDao;
import pers.husen.web.dao.impl.CodeLibraryDaoImpl;
/**
* @author 何明胜
*
* 2017年9月28日
*/
public class CodeLibrarySvc implements CodeLibraryDao{
private static final CodeLibraryDaoImpl codeLibraryDaoImpl = new CodeLibraryDaoImpl();
@Override
public int queryCodeTotalCount(CodeLibraryVo cVo) {
return codeLibraryDaoImpl.queryCodeTotalCount(cVo);
}
@Override
public CodeLibraryVo queryPerCodeById(int codeId) {
return codeLibraryDaoImpl.queryPerCodeById(codeId);
}
@Override
public int insertCodeLibrary(CodeLibraryVo cVo) {
return codeLibraryDaoImpl.insertCodeLibrary(cVo);
}
@Override
public int updateCodeReadById(int codeId) {
return codeLibraryDaoImpl.updateCodeReadById(codeId);
}
@Override
public int updateCodeById(CodeLibraryVo cVo) {
return codeLibraryDaoImpl.updateCodeById(cVo);
}
@Override
public int logicDeleteCodeById(int codeId) {
return codeLibraryDaoImpl.logicDeleteCodeById(codeId);
}
@Override
public ArrayList<CodeLibraryVo> queryCodeLibraryPerPage(CodeLibraryVo cVo, int pageSize, int pageNo) {
return codeLibraryDaoImpl.queryCodeLibraryPerPage(cVo, pageSize, pageNo);
}
@Override
public CodeLibraryVo queryPreviousCode(int codeId) {
return codeLibraryDaoImpl.queryPreviousCode(codeId);
}
@Override
public CodeLibraryVo queryNextCode(int codeId) {
return codeLibraryDaoImpl.queryNextCode(codeId);
}
} | Humsen/web/web-core/src/pers/husen/web/service/CodeLibrarySvc.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/service/CodeLibrarySvc.java",
"repo_id": "Humsen",
"token_count": 534
} | 31 |
package pers.husen.web.servlet.contact;
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 pers.husen.web.common.helper.SendEmailHelper;
/**
* 发送邮件
*
* @author 何明胜
*
* 2017年10月20日
*/
@WebServlet(urlPatterns="/sendEmail.hms")
public class SendEmailServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SendEmailServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
SendEmailHelper sendEmail = new SendEmailHelper();
String senderName = request.getParameter("contactName");
String senderEmail = request.getParameter("contactEmail");
String senderPhone = request.getParameter("contactPhone");
String senderContent = request.getParameter("contactContent");
int result = sendEmail.sendEmail2Admin(senderName, senderEmail, senderPhone, senderContent);
PrintWriter out = response.getWriter();
out.println(result);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/contact/SendEmailServlet.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/contact/SendEmailServlet.java",
"repo_id": "Humsen",
"token_count": 475
} | 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.Cookie;
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.vo.UserInfoVo;
import pers.husen.web.common.constants.RequestConstants;
import pers.husen.web.common.helper.Md5EncryptHelper;
import pers.husen.web.service.UserInfoSvc;
/**
* 用户信息操作,不带有验证码操作
*
* @author 何明胜
*
* 2017年10月20日
*/
@WebServlet(urlPatterns = "/userInfo.hms")
public class UserInfoSvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public UserInfoSvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();
UserInfoSvc uSvc = new UserInfoSvc();
String userName = request.getParameter("userName");
String password = request.getParameter("password");
String operationType = request.getParameter("type");
//密码加盐再加密
password = Md5EncryptHelper.getMD5Code(password+"["+userName+"]");
//如果操作类型为null,直接返回
if(operationType == null) {
out.println(-1);
return;
}
/** 如果请求为查询用户信息 */
String queryUserInfo = RequestConstants.REQUEST_TYPE_QUERY + RequestConstants.MODE_USER_INFO;
if (queryUserInfo.equals(operationType)) {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
UserInfoVo uVo = uSvc.queryUserInfoByName(userName);
out.println(JSONObject.fromObject(uVo));
return;
}
/** 如果请求为修改个人信息 */
String modifyUserInfo = RequestConstants.REQUEST_TYPE_MODIFY + RequestConstants.MODE_USER_INFO;
if (modifyUserInfo.equals(operationType)) {
String formData = request.getParameter("formdata");
JSONObject jsonObject = JSONObject.fromObject(formData);
UserInfoVo uVo = (UserInfoVo) JSONObject.toBean(jsonObject, UserInfoVo.class);
int updateResult = uSvc.updateUserInfoById(uVo);
out.println(updateResult);
return;
}
/** 如果为请求修改密码 */
String modifyPwd = RequestConstants.REQUEST_TYPE_MODIFY + RequestConstants.MODE_PASSWORD;
if (modifyPwd.equals(operationType)) {
UserInfoVo uVo = new UserInfoVo();
uVo.setUserName(userName);
uVo.setUserPassword(password);
int modifyResult = uSvc.updateUserPwdByName(uVo);
out.println(modifyResult);
return;
}
/** 如果是注册新用户,插入用户信息到数据库 */
String createUserInfo = RequestConstants.REQUEST_TYPE_CREATE + RequestConstants.MODE_USER_INFO;
if (createUserInfo.equals(operationType)) {
UserInfoVo uVo = new UserInfoVo();
uVo.setUserName(userName);
uVo.setUserPassword(password);
uVo.setUserEmail(request.getParameter("email"));
out.println(uSvc.insertUserInfo(uVo));
return;
}
/** 如果为验证密码,登录或者修改密码验证 */
if (operationType.contains(RequestConstants.REQUEST_TYPE_AUTH)) {
String queryPwd = uSvc.queryPasswordByUserName(userName);
if (password.equals(queryPwd)) {
// 如果为登录,设置cookie
if (operationType.contains(RequestConstants.MODE_LOGIN)) {
Cookie cookie = new Cookie("username", userName);
cookie.setPath("/");
// cookie.setMaxAge(60*60); 不设置,关闭浏览器即失效
response.addCookie(cookie);
out.println(1);
return;
}
// 如果是修改密码验证
if (operationType.contains(RequestConstants.MODE_PASSWORD)) {
out.println(1);
return;
}
} else {
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/UserInfoSvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/userinfo/UserInfoSvt.java",
"repo_id": "Humsen",
"token_count": 1729
} | 33 |
@charset "UTF-8";
/* 留言区分页的CSS */
.pager-box:after {
display: block;
height: 0;
visibility: hidden;
clear: both;
content: '';
}
.pager {
float: left;
position: relative;
left: 50%;
font-family: 微软雅黑;
}
.pager a, .pager span {
position: relative;
left: -50%;
display: block;
float: left;
margin-left: 5px;
border: 1px solid #b6bcc1;
padding: 5px 10px;
text-decoration: none;
color: #b6bcc1;
border-radius: 3px;
}
.pager span {
border: 0;
}
.pager a.js-selected {
background: #b6bcc1;
color: #fff;
cursor: default;
}
.pager a.js-disabled {
background: #f1f1f1;
border-color: #f1f1f1;
cursor: default;
color: #fff;
} | Humsen/web/web-mobile/WebContent/css/message/pager.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/css/message/pager.css",
"repo_id": "Humsen",
"token_count": 321
} | 34 |
/**
* 加载代码目录
*
* @author 何明胜
*
* 2017年9月18日
*/
/** 加载插件 * */
$.ajax({
url : '/plugins/plugins.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$($('head')[0]).find('script:first').after(data);
}
});
$(function() {
/** 顶部导航栏 **/
$.ajax({
url : '/module/navigation/topbar.html',
async : false,
type : 'GET',
success : function(data) {
$('#menuBarNo').before(data);
}
});
/** 登录控制 **/
$.ajax({
url : '/module/login/login.html',
async : false,
type : 'GET',
success : function(data) {
$('#menuBarNo').before(data);
}
});
/** 右侧导航栏 **/
$.ajax({
url : '/module/navigation/rightbar.html',
async : false,
type : 'GET',
success : function(data) {
$('#fh5co-main').after(data);
}
});
});
var code_total_num = 0;
var code_page_size = 5;
$(function(){
queryCodeNum();
queryCodeCatalog(1);
//页面选择
choosePageSize();
});
/**
* 查询博客数量
*
* @returns
*/
function queryCodeNum(){
$.ajax({
type : 'POST',
async: false,
url : '/code/query.hms',
data : {
type : 'query_total_num'
},
success : function(response){
code_total_num = response;
},
error : function(response, status){
$.confirm({
title: '代码库数量加载出错',
content: status + ' : ' + response,
autoClose: 'ok|1000',
type: 'red',
buttons: {
ok: {
text: '确认',
btnClass: 'btn-primary',
},
}
});
}
});
}
/**
* 查询博客目录
*
* @param pageSize
* @param pageNo
* @returns
*/
function queryCodeCatalog(pageNo){
$.ajax({
type : 'POST',
async: false,
url : '/code/query.hms',
dataType : 'json',
data : {
type : 'query_one_page',
pageSize : code_page_size,
pageNo : pageNo,
},
success : function(response){
for(x in response){
loadSimpleCode(response[x]);
}
showPagination(pageNo, 6);//显示分页
},
error : function(XMLHttpRequest, textStatus){
$.confirm({
title: '代码库加载出错',
content: textStatus + ' : ' + XMLHttpRequest.status,
autoClose: 'ok|1000',
type: 'green',
buttons: {
ok: {
text: '确认',
btnClass: 'btn-primary',
},
}
});
}
});
}
/**
* 加载目录形式的代码
*
* @param code_data
* @returns
*/
function loadSimpleCode(code_data){
$('#list_code').append('<div class="fh5co-entry padding">'
+ '<span class="fh5co-post-date">' + new Date(code_data.codeDate.time).format('yyyy-MM-dd hh:mm:ss') + '</span>'
+ '<span class="fh5co-post-date">作者:' + code_data.userNickName + '</span>'
+ '<span class="fh5co-post-date">浏览' + code_data.codeRead + '次</span>'
+ '<h2 class="article-title"><input type="hidden" value=' + code_data.codeId + ' />'
+ '<a href="/code.hms?codeId=' + code_data.codeId + '">' + code_data.codeTitle + '</a></h2>'
+ '<p><b>摘要:</b>' + code_data.codeSummary + '</p>'
+ '</div>'
+ '</div>');
}
/**
* 显示底部分页
*
* @returns void
*/
function showPagination(currpagenum, paginationmaxlength){
$('#list_code').append('<hr />'
+ '<div id="pagination" class="text-align-center" pagination="pagination_new" '
+ ' currpagenum=' + currpagenum + ' paginationmaxlength=' + paginationmaxlength + ' totalpages=' + Math.ceil(code_total_num/code_page_size)
+ ' onlyonepageshow="true"> '
+ '</div>'
+ '<hr />');
PaginationHelper($('#pagination'), code_page_size);//显示分页
}
/**
* 选择每页显示博客数量
*
* @returns
*/
function choosePageSize(){
$('#choose_page_size').find('.dropdown-menu').children('li').click(function() {
code_page_size = $(this).attr('value');
$('#list_code').html('');
queryCodeNum();
queryCodeCatalog(currentPageNum);
choosePageSize();
});
}
/**
* 实现的点击事件,参数为分页容器的id
* pagination.js调用这里
*
* @param currentPageNum
* @returns
*/
function paginationClick(currentPageNum) {
$('#list_code').html('');
queryCodeNum();
queryCodeCatalog(currentPageNum);
} | Humsen/web/web-mobile/WebContent/js/article/code-library.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/js/article/code-library.js",
"repo_id": "Humsen",
"token_count": 2062
} | 35 |
/**
* 初始化菜单栏
*
* @author 何明胜
*
* 2017年9月27日
*/
$(function(){
var menuBarNo = Number($('#menuBarNo').val());
menuBarInit(menuBarNo);
});
function menuBarInit(menuBarNo){
var menu_bar = '<aside id="fh5co-aside" role="complementary" class="border js-fullheight">'
+'<h1 id="fh5co-logo">'
+'<a href="/" class="husen-name">何明胜</a>'
+'</h1>'
+'<nav id="fh5co-main-menu" role="navigation">'
+'<ul>'
+'<li><a href="/">主页</a></li>'
+'<li><a href="/module/blog.hms">文章</a></li>'
+'<li><a href="/module/code.hms">代码库</a></li>'
+'<li><a href="/module/message.hms">留言区</a></li>'
+'<li><a href="/module/download.hms">分享</a></li>'
+'<li><a href="/module/contact.hms">联系站长</a></li>'
+'</ul>'
+'</nav>'
+'<div class="web-pc-nav">'
+'<a class="btn btn-default btn-sm" href="https://demo.hemingsheng.cn/" role="button"><span class="glyphicon glyphicon-blackboard"></span> 电脑版</a>'
+'</div>'
+'<div class="fh5co-footer footer-div">'
+'<p>'
+'<small><span>渝ICP备16013250号 </span>'
+'<span>©'
+'2017-2020 </span><span>All Rights Reserved</span></small>'
+'</p>'
+'</div>'
+'</aside>';
$('#fh5co-page').prepend(menu_bar);
$('#fh5co-aside').find('ul').children().eq(menuBarNo).addClass('fh5co-active');
} | Humsen/web/web-mobile/WebContent/js/navigation/left-menu-bar.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/js/navigation/left-menu-bar.js",
"repo_id": "Humsen",
"token_count": 677
} | 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) {
CodeMirror.defineExtension("addPanel", function(node, options) {
if (!this.state.panels) initPanels(this);
var info = this.state.panels;
if (options && options.position == "bottom")
info.wrapper.appendChild(node);
else
info.wrapper.insertBefore(node, info.wrapper.firstChild);
var height = (options && options.height) || node.offsetHeight;
this._setSize(null, info.heightLeft -= height);
info.panels++;
return new Panel(this, node, options, height);
});
function Panel(cm, node, options, height) {
this.cm = cm;
this.node = node;
this.options = options;
this.height = height;
this.cleared = false;
}
Panel.prototype.clear = function() {
if (this.cleared) return;
this.cleared = true;
var info = this.cm.state.panels;
this.cm._setSize(null, info.heightLeft += this.height);
info.wrapper.removeChild(this.node);
if (--info.panels == 0) removePanels(this.cm);
};
Panel.prototype.changed = function(height) {
var newHeight = height == null ? this.node.offsetHeight : height;
var info = this.cm.state.panels;
this.cm._setSize(null, info.height += (newHeight - this.height));
this.height = newHeight;
};
function initPanels(cm) {
var wrap = cm.getWrapperElement();
var style = window.getComputedStyle ? window.getComputedStyle(wrap) : wrap.currentStyle;
var height = parseInt(style.height);
var info = cm.state.panels = {
setHeight: wrap.style.height,
heightLeft: height,
panels: 0,
wrapper: document.createElement("div")
};
wrap.parentNode.insertBefore(info.wrapper, wrap);
var hasFocus = cm.hasFocus();
info.wrapper.appendChild(wrap);
if (hasFocus) cm.focus();
cm._setSize = cm.setSize;
if (height != null) cm.setSize = function(width, newHeight) {
if (newHeight == null) return this._setSize(width, newHeight);
info.setHeight = newHeight;
if (typeof newHeight != "number") {
var px = /^(\d+\.?\d*)px$/.exec(newHeight);
if (px) {
newHeight = Number(px[1]);
} else {
info.wrapper.style.height = newHeight;
newHeight = info.wrapper.offsetHeight;
info.wrapper.style.height = "";
}
}
cm._setSize(width, info.heightLeft += (newHeight - height));
height = newHeight;
};
}
function removePanels(cm) {
var info = cm.state.panels;
cm.state.panels = null;
var wrap = cm.getWrapperElement();
info.wrapper.parentNode.replaceChild(wrap, info.wrapper);
wrap.style.height = info.setHeight;
cm.setSize = cm._setSize;
cm.setSize();
}
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/display/panel.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/display/panel.js",
"repo_id": "Humsen",
"token_count": 1192
} | 37 |
// 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";
var Pos = CodeMirror.Pos;
function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }
var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");
function Iter(cm, line, ch, range) {
this.line = line; this.ch = ch;
this.cm = cm; this.text = cm.getLine(line);
this.min = range ? range.from : cm.firstLine();
this.max = range ? range.to - 1 : cm.lastLine();
}
function tagAt(iter, ch) {
var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));
return type && /\btag\b/.test(type);
}
function nextLine(iter) {
if (iter.line >= iter.max) return;
iter.ch = 0;
iter.text = iter.cm.getLine(++iter.line);
return true;
}
function prevLine(iter) {
if (iter.line <= iter.min) return;
iter.text = iter.cm.getLine(--iter.line);
iter.ch = iter.text.length;
return true;
}
function toTagEnd(iter) {
for (;;) {
var gt = iter.text.indexOf(">", iter.ch);
if (gt == -1) { if (nextLine(iter)) continue; else return; }
if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }
var lastSlash = iter.text.lastIndexOf("/", gt);
var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
iter.ch = gt + 1;
return selfClose ? "selfClose" : "regular";
}
}
function toTagStart(iter) {
for (;;) {
var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1;
if (lt == -1) { if (prevLine(iter)) continue; else return; }
if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }
xmlTagStart.lastIndex = lt;
iter.ch = lt;
var match = xmlTagStart.exec(iter.text);
if (match && match.index == lt) return match;
}
}
function toNextTag(iter) {
for (;;) {
xmlTagStart.lastIndex = iter.ch;
var found = xmlTagStart.exec(iter.text);
if (!found) { if (nextLine(iter)) continue; else return; }
if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }
iter.ch = found.index + found[0].length;
return found;
}
}
function toPrevTag(iter) {
for (;;) {
var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1;
if (gt == -1) { if (prevLine(iter)) continue; else return; }
if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }
var lastSlash = iter.text.lastIndexOf("/", gt);
var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
iter.ch = gt + 1;
return selfClose ? "selfClose" : "regular";
}
}
function findMatchingClose(iter, tag) {
var stack = [];
for (;;) {
var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);
if (!next || !(end = toTagEnd(iter))) return;
if (end == "selfClose") continue;
if (next[1]) { // closing tag
for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {
stack.length = i;
break;
}
if (i < 0 && (!tag || tag == next[2])) return {
tag: next[2],
from: Pos(startLine, startCh),
to: Pos(iter.line, iter.ch)
};
} else { // opening tag
stack.push(next[2]);
}
}
}
function findMatchingOpen(iter, tag) {
var stack = [];
for (;;) {
var prev = toPrevTag(iter);
if (!prev) return;
if (prev == "selfClose") { toTagStart(iter); continue; }
var endLine = iter.line, endCh = iter.ch;
var start = toTagStart(iter);
if (!start) return;
if (start[1]) { // closing tag
stack.push(start[2]);
} else { // opening tag
for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {
stack.length = i;
break;
}
if (i < 0 && (!tag || tag == start[2])) return {
tag: start[2],
from: Pos(iter.line, iter.ch),
to: Pos(endLine, endCh)
};
}
}
}
CodeMirror.registerHelper("fold", "xml", function(cm, start) {
var iter = new Iter(cm, start.line, 0);
for (;;) {
var openTag = toNextTag(iter), end;
if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return;
if (!openTag[1] && end != "selfClose") {
var start = Pos(iter.line, iter.ch);
var close = findMatchingClose(iter, openTag[2]);
return close && {from: start, to: close.from};
}
}
});
CodeMirror.findMatchingTag = function(cm, pos, range) {
var iter = new Iter(cm, pos.line, pos.ch, range);
if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return;
var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);
var start = end && toTagStart(iter);
if (!end || !start || cmp(iter, pos) > 0) return;
var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};
if (end == "selfClose") return {open: here, close: null, at: "open"};
if (start[1]) { // closing tag
return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"};
} else { // opening tag
iter = new Iter(cm, to.line, to.ch, range);
return {open: here, close: findMatchingClose(iter, start[2]), at: "open"};
}
};
CodeMirror.findEnclosingTag = function(cm, pos, range) {
var iter = new Iter(cm, pos.line, pos.ch, range);
for (;;) {
var open = findMatchingOpen(iter);
if (!open) break;
var forward = new Iter(cm, pos.line, pos.ch, range);
var close = findMatchingClose(forward, open.tag);
if (close) return {open: open, close: close};
}
};
// Used by addon/edit/closetag.js
CodeMirror.scanForClosingTag = function(cm, pos, name, end) {
var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);
return findMatchingClose(iter, name);
};
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/fold/xml-fold.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/fold/xml-fold.js",
"repo_id": "Humsen",
"token_count": 2890
} | 38 |
.CodeMirror-merge {
position: relative;
border: 1px solid #ddd;
white-space: pre;
}
.CodeMirror-merge, .CodeMirror-merge .CodeMirror {
height: 350px;
}
.CodeMirror-merge-2pane .CodeMirror-merge-pane { width: 47%; }
.CodeMirror-merge-2pane .CodeMirror-merge-gap { width: 6%; }
.CodeMirror-merge-3pane .CodeMirror-merge-pane { width: 31%; }
.CodeMirror-merge-3pane .CodeMirror-merge-gap { width: 3.5%; }
.CodeMirror-merge-pane {
display: inline-block;
white-space: normal;
vertical-align: top;
}
.CodeMirror-merge-pane-rightmost {
position: absolute;
right: 0px;
z-index: 1;
}
.CodeMirror-merge-gap {
z-index: 2;
display: inline-block;
height: 100%;
-moz-box-sizing: border-box;
box-sizing: border-box;
overflow: hidden;
border-left: 1px solid #ddd;
border-right: 1px solid #ddd;
position: relative;
background: #f8f8f8;
}
.CodeMirror-merge-scrolllock-wrap {
position: absolute;
bottom: 0; left: 50%;
}
.CodeMirror-merge-scrolllock {
position: relative;
left: -50%;
cursor: pointer;
color: #555;
line-height: 1;
}
.CodeMirror-merge-copybuttons-left, .CodeMirror-merge-copybuttons-right {
position: absolute;
left: 0; top: 0;
right: 0; bottom: 0;
line-height: 1;
}
.CodeMirror-merge-copy {
position: absolute;
cursor: pointer;
color: #44c;
}
.CodeMirror-merge-copy-reverse {
position: absolute;
cursor: pointer;
color: #44c;
}
.CodeMirror-merge-copybuttons-left .CodeMirror-merge-copy { left: 2px; }
.CodeMirror-merge-copybuttons-right .CodeMirror-merge-copy { right: 2px; }
.CodeMirror-merge-r-inserted, .CodeMirror-merge-l-inserted {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12MwuCXy3+CWyH8GBgYGJgYkAABZbAQ9ELXurwAAAABJRU5ErkJggg==);
background-position: bottom left;
background-repeat: repeat-x;
}
.CodeMirror-merge-r-deleted, .CodeMirror-merge-l-deleted {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12M4Kyb2/6yY2H8GBgYGJgYkAABURgPz6Ks7wQAAAABJRU5ErkJggg==);
background-position: bottom left;
background-repeat: repeat-x;
}
.CodeMirror-merge-r-chunk { background: #ffffe0; }
.CodeMirror-merge-r-chunk-start { border-top: 1px solid #ee8; }
.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #ee8; }
.CodeMirror-merge-r-connect { fill: #ffffe0; stroke: #ee8; stroke-width: 1px; }
.CodeMirror-merge-l-chunk { background: #eef; }
.CodeMirror-merge-l-chunk-start { border-top: 1px solid #88e; }
.CodeMirror-merge-l-chunk-end { border-bottom: 1px solid #88e; }
.CodeMirror-merge-l-connect { fill: #eef; stroke: #88e; stroke-width: 1px; }
.CodeMirror-merge-l-chunk.CodeMirror-merge-r-chunk { background: #dfd; }
.CodeMirror-merge-l-chunk-start.CodeMirror-merge-r-chunk-start { border-top: 1px solid #4e4; }
.CodeMirror-merge-l-chunk-end.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #4e4; }
.CodeMirror-merge-collapsed-widget:before {
content: "(...)";
}
.CodeMirror-merge-collapsed-widget {
cursor: pointer;
color: #88b;
background: #eef;
border: 1px solid #ddf;
font-size: 90%;
padding: 0 3px;
border-radius: 4px;
}
.CodeMirror-merge-collapsed-line .CodeMirror-gutter-elt { display: none; }
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/merge/merge.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/merge/merge.css",
"repo_id": "Humsen",
"token_count": 1402
} | 39 |
.CodeMirror-search-match {
background: gold;
border-top: 1px solid orange;
border-bottom: 1px solid orange;
-moz-box-sizing: border-box;
box-sizing: border-box;
opacity: .5;
}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/search/matchesonscrollbar.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/search/matchesonscrollbar.css",
"repo_id": "Humsen",
"token_count": 73
} | 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"), require("../htmlmixed/htmlmixed"),
require("../../addon/mode/overlay"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../htmlmixed/htmlmixed",
"../../addon/mode/overlay"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("django:inner", function() {
var keywords = ["block", "endblock", "for", "endfor", "in", "true", "false",
"loop", "none", "self", "super", "if", "endif", "as", "not", "and",
"else", "import", "with", "endwith", "without", "context", "ifequal", "endifequal",
"ifnotequal", "endifnotequal", "extends", "include", "load", "length", "comment",
"endcomment", "empty"];
keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b");
function tokenBase (stream, state) {
stream.eatWhile(/[^\{]/);
var ch = stream.next();
if (ch == "{") {
if (ch = stream.eat(/\{|%|#/)) {
state.tokenize = inTag(ch);
return "tag";
}
}
}
function inTag (close) {
if (close == "{") {
close = "}";
}
return function (stream, state) {
var ch = stream.next();
if ((ch == close) && stream.eat("}")) {
state.tokenize = tokenBase;
return "tag";
}
if (stream.match(keywords)) {
return "keyword";
}
return close == "#" ? "comment" : "string";
};
}
return {
startState: function () {
return {tokenize: tokenBase};
},
token: function (stream, state) {
return state.tokenize(stream, state);
}
};
});
CodeMirror.defineMode("django", function(config) {
var htmlBase = CodeMirror.getMode(config, "text/html");
var djangoInner = CodeMirror.getMode(config, "django:inner");
return CodeMirror.overlayMode(htmlBase, djangoInner);
});
CodeMirror.defineMIME("text/x-django", "django");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/django/django.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/django/django.js",
"repo_id": "Humsen",
"token_count": 1016
} | 41 |
// 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"), require("../htmlmixed/htmlmixed"), require("../ruby/ruby"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../ruby/ruby"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
// full haml mode. This handled embeded ruby and html fragments too
CodeMirror.defineMode("haml", function(config) {
var htmlMode = CodeMirror.getMode(config, {name: "htmlmixed"});
var rubyMode = CodeMirror.getMode(config, "ruby");
function rubyInQuote(endQuote) {
return function(stream, state) {
var ch = stream.peek();
if (ch == endQuote && state.rubyState.tokenize.length == 1) {
// step out of ruby context as it seems to complete processing all the braces
stream.next();
state.tokenize = html;
return "closeAttributeTag";
} else {
return ruby(stream, state);
}
};
}
function ruby(stream, state) {
if (stream.match("-#")) {
stream.skipToEnd();
return "comment";
}
return rubyMode.token(stream, state.rubyState);
}
function html(stream, state) {
var ch = stream.peek();
// handle haml declarations. All declarations that cant be handled here
// will be passed to html mode
if (state.previousToken.style == "comment" ) {
if (state.indented > state.previousToken.indented) {
stream.skipToEnd();
return "commentLine";
}
}
if (state.startOfLine) {
if (ch == "!" && stream.match("!!")) {
stream.skipToEnd();
return "tag";
} else if (stream.match(/^%[\w:#\.]+=/)) {
state.tokenize = ruby;
return "hamlTag";
} else if (stream.match(/^%[\w:]+/)) {
return "hamlTag";
} else if (ch == "/" ) {
stream.skipToEnd();
return "comment";
}
}
if (state.startOfLine || state.previousToken.style == "hamlTag") {
if ( ch == "#" || ch == ".") {
stream.match(/[\w-#\.]*/);
return "hamlAttribute";
}
}
// donot handle --> as valid ruby, make it HTML close comment instead
if (state.startOfLine && !stream.match("-->", false) && (ch == "=" || ch == "-" )) {
state.tokenize = ruby;
return state.tokenize(stream, state);
}
if (state.previousToken.style == "hamlTag" ||
state.previousToken.style == "closeAttributeTag" ||
state.previousToken.style == "hamlAttribute") {
if (ch == "(") {
state.tokenize = rubyInQuote(")");
return state.tokenize(stream, state);
} else if (ch == "{") {
state.tokenize = rubyInQuote("}");
return state.tokenize(stream, state);
}
}
return htmlMode.token(stream, state.htmlState);
}
return {
// default to html mode
startState: function() {
var htmlState = htmlMode.startState();
var rubyState = rubyMode.startState();
return {
htmlState: htmlState,
rubyState: rubyState,
indented: 0,
previousToken: { style: null, indented: 0},
tokenize: html
};
},
copyState: function(state) {
return {
htmlState : CodeMirror.copyState(htmlMode, state.htmlState),
rubyState: CodeMirror.copyState(rubyMode, state.rubyState),
indented: state.indented,
previousToken: state.previousToken,
tokenize: state.tokenize
};
},
token: function(stream, state) {
if (stream.sol()) {
state.indented = stream.indentation();
state.startOfLine = true;
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
state.startOfLine = false;
// dont record comment line as we only want to measure comment line with
// the opening comment block
if (style && style != "commentLine") {
state.previousToken = { style: style, indented: state.indented };
}
// if current state is ruby and the previous token is not `,` reset the
// tokenize to html
if (stream.eol() && state.tokenize == ruby) {
stream.backUp(1);
var ch = stream.peek();
stream.next();
if (ch && ch != ",") {
state.tokenize = html;
}
}
// reprocess some of the specific style tag when finish setting previousToken
if (style == "hamlTag") {
style = "tag";
} else if (style == "commentLine") {
style = "comment";
} else if (style == "hamlAttribute") {
style = "attribute";
} else if (style == "closeAttributeTag") {
style = null;
}
return style;
}
};
}, "htmlmixed", "ruby");
CodeMirror.defineMIME("text/x-haml", "haml");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/haml/haml.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/haml/haml.js",
"repo_id": "Humsen",
"token_count": 2304
} | 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"), require("../xml/xml"), require("../meta"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../xml/xml", "../meta"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
var htmlFound = CodeMirror.modes.hasOwnProperty("xml");
var htmlMode = CodeMirror.getMode(cmCfg, htmlFound ? {name: "xml", htmlMode: true} : "text/plain");
function getMode(name) {
if (CodeMirror.findModeByName) {
var found = CodeMirror.findModeByName(name);
if (found) name = found.mime || found.mimes[0];
}
var mode = CodeMirror.getMode(cmCfg, name);
return mode.name == "null" ? null : mode;
}
// Should characters that affect highlighting be highlighted separate?
// Does not include characters that will be output (such as `1.` and `-` for lists)
if (modeCfg.highlightFormatting === undefined)
modeCfg.highlightFormatting = false;
// Maximum number of nested blockquotes. Set to 0 for infinite nesting.
// Excess `>` will emit `error` token.
if (modeCfg.maxBlockquoteDepth === undefined)
modeCfg.maxBlockquoteDepth = 0;
// Should underscores in words open/close em/strong?
if (modeCfg.underscoresBreakWords === undefined)
modeCfg.underscoresBreakWords = true;
// Turn on fenced code blocks? ("```" to start/end)
if (modeCfg.fencedCodeBlocks === undefined) modeCfg.fencedCodeBlocks = false;
// Turn on task lists? ("- [ ] " and "- [x] ")
if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
// Turn on strikethrough syntax
if (modeCfg.strikethrough === undefined)
modeCfg.strikethrough = false;
var codeDepth = 0;
var header = 'header'
, code = 'comment'
, quote = 'quote'
, list1 = 'variable-2'
, list2 = 'variable-3'
, list3 = 'keyword'
, hr = 'hr'
, image = 'tag'
, formatting = 'formatting'
, linkinline = 'link'
, linkemail = 'link'
, linktext = 'link'
, linkhref = 'string'
, em = 'em'
, strong = 'strong'
, strikethrough = 'strikethrough';
var hrRE = /^([*\-=_])(?:\s*\1){2,}\s*$/
, ulRE = /^[*\-+]\s+/
, olRE = /^[0-9]+\.\s+/
, taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE
, atxHeaderRE = /^#+/
, setextHeaderRE = /^(?:\={1,}|-{1,})$/
, textRE = /^[^#!\[\]*_\\<>` "'(~]+/;
function switchInline(stream, state, f) {
state.f = state.inline = f;
return f(stream, state);
}
function switchBlock(stream, state, f) {
state.f = state.block = f;
return f(stream, state);
}
// Blocks
function blankLine(state) {
// Reset linkTitle state
state.linkTitle = false;
// Reset EM state
state.em = false;
// Reset STRONG state
state.strong = false;
// Reset strikethrough state
state.strikethrough = false;
// Reset state.quote
state.quote = 0;
if (!htmlFound && state.f == htmlBlock) {
state.f = inlineNormal;
state.block = blockNormal;
}
// Reset state.trailingSpace
state.trailingSpace = 0;
state.trailingSpaceNewLine = false;
// Mark this line as blank
state.thisLineHasContent = false;
return null;
}
function blockNormal(stream, state) {
var sol = stream.sol();
var prevLineIsList = (state.list !== false);
if (state.list !== false && state.indentationDiff >= 0) { // Continued list
if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block
state.indentation -= state.indentationDiff;
}
state.list = null;
} else if (state.list !== false && state.indentation > 0) {
state.list = null;
state.listDepth = Math.floor(state.indentation / 4);
} else if (state.list !== false) { // No longer a list
state.list = false;
state.listDepth = 0;
}
var match = null;
if (state.indentationDiff >= 4) {
state.indentation -= 4;
stream.skipToEnd();
return code;
} else if (stream.eatSpace()) {
return null;
} else if (match = stream.match(atxHeaderRE)) {
state.header = match[0].length <= 6 ? match[0].length : 6;
if (modeCfg.highlightFormatting) state.formatting = "header";
state.f = state.inline;
return getType(state);
} else if (state.prevLineHasContent && (match = stream.match(setextHeaderRE))) {
state.header = match[0].charAt(0) == '=' ? 1 : 2;
if (modeCfg.highlightFormatting) state.formatting = "header";
state.f = state.inline;
return getType(state);
} else if (stream.eat('>')) {
state.indentation++;
state.quote = sol ? 1 : state.quote + 1;
if (modeCfg.highlightFormatting) state.formatting = "quote";
stream.eatSpace();
return getType(state);
} else if (stream.peek() === '[') {
return switchInline(stream, state, footnoteLink);
} else if (stream.match(hrRE, true)) {
return hr;
} else if ((!state.prevLineHasContent || prevLineIsList) && (stream.match(ulRE, false) || stream.match(olRE, false))) {
var listType = null;
if (stream.match(ulRE, true)) {
listType = 'ul';
} else {
stream.match(olRE, true);
listType = 'ol';
}
state.indentation += 4;
state.list = true;
state.listDepth++;
if (modeCfg.taskLists && stream.match(taskListRE, false)) {
state.taskList = true;
}
state.f = state.inline;
if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
return getType(state);
} else if (modeCfg.fencedCodeBlocks && stream.match(/^```[ \t]*([\w+#]*)/, true)) {
// try switching mode
state.localMode = getMode(RegExp.$1);
if (state.localMode) state.localState = state.localMode.startState();
state.f = state.block = local;
if (modeCfg.highlightFormatting) state.formatting = "code-block";
state.code = true;
return getType(state);
}
return switchInline(stream, state, state.inline);
}
function htmlBlock(stream, state) {
var style = htmlMode.token(stream, state.htmlState);
if ((htmlFound && state.htmlState.tagStart === null && !state.htmlState.context) ||
(state.md_inside && stream.current().indexOf(">") > -1)) {
state.f = inlineNormal;
state.block = blockNormal;
state.htmlState = null;
}
return style;
}
function local(stream, state) {
if (stream.sol() && stream.match("```", false)) {
state.localMode = state.localState = null;
state.f = state.block = leavingLocal;
return null;
} else if (state.localMode) {
return state.localMode.token(stream, state.localState);
} else {
stream.skipToEnd();
return code;
}
}
function leavingLocal(stream, state) {
stream.match("```");
state.block = blockNormal;
state.f = inlineNormal;
if (modeCfg.highlightFormatting) state.formatting = "code-block";
state.code = true;
var returnType = getType(state);
state.code = false;
return returnType;
}
// Inline
function getType(state) {
var styles = [];
if (state.formatting) {
styles.push(formatting);
if (typeof state.formatting === "string") state.formatting = [state.formatting];
for (var i = 0; i < state.formatting.length; i++) {
styles.push(formatting + "-" + state.formatting[i]);
if (state.formatting[i] === "header") {
styles.push(formatting + "-" + state.formatting[i] + "-" + state.header);
}
// Add `formatting-quote` and `formatting-quote-#` for blockquotes
// Add `error` instead if the maximum blockquote nesting depth is passed
if (state.formatting[i] === "quote") {
if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
styles.push(formatting + "-" + state.formatting[i] + "-" + state.quote);
} else {
styles.push("error");
}
}
}
}
if (state.taskOpen) {
styles.push("meta");
return styles.length ? styles.join(' ') : null;
}
if (state.taskClosed) {
styles.push("property");
return styles.length ? styles.join(' ') : null;
}
if (state.linkHref) {
styles.push(linkhref);
return styles.length ? styles.join(' ') : null;
}
if (state.strong) { styles.push(strong); }
if (state.em) { styles.push(em); }
if (state.strikethrough) { styles.push(strikethrough); }
if (state.linkText) { styles.push(linktext); }
if (state.code) { styles.push(code); }
if (state.header) { styles.push(header); styles.push(header + "-" + state.header); }
if (state.quote) {
styles.push(quote);
// Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
styles.push(quote + "-" + state.quote);
} else {
styles.push(quote + "-" + modeCfg.maxBlockquoteDepth);
}
}
if (state.list !== false) {
var listMod = (state.listDepth - 1) % 3;
if (!listMod) {
styles.push(list1);
} else if (listMod === 1) {
styles.push(list2);
} else {
styles.push(list3);
}
}
if (state.trailingSpaceNewLine) {
styles.push("trailing-space-new-line");
} else if (state.trailingSpace) {
styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
}
return styles.length ? styles.join(' ') : null;
}
function handleText(stream, state) {
if (stream.match(textRE, true)) {
return getType(state);
}
return undefined;
}
function inlineNormal(stream, state) {
var style = state.text(stream, state);
if (typeof style !== 'undefined')
return style;
if (state.list) { // List marker (*, +, -, 1., etc)
state.list = null;
return getType(state);
}
if (state.taskList) {
var taskOpen = stream.match(taskListRE, true)[1] !== "x";
if (taskOpen) state.taskOpen = true;
else state.taskClosed = true;
if (modeCfg.highlightFormatting) state.formatting = "task";
state.taskList = false;
return getType(state);
}
state.taskOpen = false;
state.taskClosed = false;
if (state.header && stream.match(/^#+$/, true)) {
if (modeCfg.highlightFormatting) state.formatting = "header";
return getType(state);
}
// Get sol() value now, before character is consumed
var sol = stream.sol();
var ch = stream.next();
if (ch === '\\') {
stream.next();
if (modeCfg.highlightFormatting) {
var type = getType(state);
return type ? type + " formatting-escape" : "formatting-escape";
}
}
// Matches link titles present on next line
if (state.linkTitle) {
state.linkTitle = false;
var matchCh = ch;
if (ch === '(') {
matchCh = ')';
}
matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
if (stream.match(new RegExp(regex), true)) {
return linkhref;
}
}
// If this block is changed, it may need to be updated in GFM mode
if (ch === '`') {
var previousFormatting = state.formatting;
if (modeCfg.highlightFormatting) state.formatting = "code";
var t = getType(state);
var before = stream.pos;
stream.eatWhile('`');
var difference = 1 + stream.pos - before;
if (!state.code) {
codeDepth = difference;
state.code = true;
return getType(state);
} else {
if (difference === codeDepth) { // Must be exact
state.code = false;
return t;
}
state.formatting = previousFormatting;
return getType(state);
}
} else if (state.code) {
return getType(state);
}
if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
stream.match(/\[[^\]]*\]/);
state.inline = state.f = linkHref;
return image;
}
if (ch === '[' && stream.match(/.*\](\(.*\)| ?\[.*\])/, false)) {
state.linkText = true;
if (modeCfg.highlightFormatting) state.formatting = "link";
return getType(state);
}
if (ch === ']' && state.linkText && stream.match(/\(.*\)| ?\[.*\]/, false)) {
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
state.linkText = false;
state.inline = state.f = linkHref;
return type;
}
if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
state.f = state.inline = linkInline;
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
if (type){
type += " ";
} else {
type = "";
}
return type + linkinline;
}
if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
state.f = state.inline = linkInline;
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
if (type){
type += " ";
} else {
type = "";
}
return type + linkemail;
}
if (ch === '<' && stream.match(/^\w/, false)) {
if (stream.string.indexOf(">") != -1) {
var atts = stream.string.substring(1,stream.string.indexOf(">"));
if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) {
state.md_inside = true;
}
}
stream.backUp(1);
state.htmlState = CodeMirror.startState(htmlMode);
return switchBlock(stream, state, htmlBlock);
}
if (ch === '<' && stream.match(/^\/\w*?>/)) {
state.md_inside = false;
return "tag";
}
var ignoreUnderscore = false;
if (!modeCfg.underscoresBreakWords) {
if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) {
var prevPos = stream.pos - 2;
if (prevPos >= 0) {
var prevCh = stream.string.charAt(prevPos);
if (prevCh !== '_' && prevCh.match(/(\w)/, false)) {
ignoreUnderscore = true;
}
}
}
}
if (ch === '*' || (ch === '_' && !ignoreUnderscore)) {
if (sol && stream.peek() === ' ') {
// Do nothing, surrounded by newline and space
} else if (state.strong === ch && stream.eat(ch)) { // Remove STRONG
if (modeCfg.highlightFormatting) state.formatting = "strong";
var t = getType(state);
state.strong = false;
return t;
} else if (!state.strong && stream.eat(ch)) { // Add STRONG
state.strong = ch;
if (modeCfg.highlightFormatting) state.formatting = "strong";
return getType(state);
} else if (state.em === ch) { // Remove EM
if (modeCfg.highlightFormatting) state.formatting = "em";
var t = getType(state);
state.em = false;
return t;
} else if (!state.em) { // Add EM
state.em = ch;
if (modeCfg.highlightFormatting) state.formatting = "em";
return getType(state);
}
} else if (ch === ' ') {
if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
if (stream.peek() === ' ') { // Surrounded by spaces, ignore
return getType(state);
} else { // Not surrounded by spaces, back up pointer
stream.backUp(1);
}
}
}
if (modeCfg.strikethrough) {
if (ch === '~' && stream.eatWhile(ch)) {
if (state.strikethrough) {// Remove strikethrough
if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
var t = getType(state);
state.strikethrough = false;
return t;
} else if (stream.match(/^[^\s]/, false)) {// Add strikethrough
state.strikethrough = true;
if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
return getType(state);
}
} else if (ch === ' ') {
if (stream.match(/^~~/, true)) { // Probably surrounded by space
if (stream.peek() === ' ') { // Surrounded by spaces, ignore
return getType(state);
} else { // Not surrounded by spaces, back up pointer
stream.backUp(2);
}
}
}
}
if (ch === ' ') {
if (stream.match(/ +$/, false)) {
state.trailingSpace++;
} else if (state.trailingSpace) {
state.trailingSpaceNewLine = true;
}
}
return getType(state);
}
function linkInline(stream, state) {
var ch = stream.next();
if (ch === ">") {
state.f = state.inline = inlineNormal;
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
if (type){
type += " ";
} else {
type = "";
}
return type + linkinline;
}
stream.match(/^[^>]+/, true);
return linkinline;
}
function linkHref(stream, state) {
// Check if space, and return NULL if so (to avoid marking the space)
if(stream.eatSpace()){
return null;
}
var ch = stream.next();
if (ch === '(' || ch === '[') {
state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]");
if (modeCfg.highlightFormatting) state.formatting = "link-string";
state.linkHref = true;
return getType(state);
}
return 'error';
}
function getLinkHrefInside(endChar) {
return function(stream, state) {
var ch = stream.next();
if (ch === endChar) {
state.f = state.inline = inlineNormal;
if (modeCfg.highlightFormatting) state.formatting = "link-string";
var returnState = getType(state);
state.linkHref = false;
return returnState;
}
if (stream.match(inlineRE(endChar), true)) {
stream.backUp(1);
}
state.linkHref = true;
return getType(state);
};
}
function footnoteLink(stream, state) {
if (stream.match(/^[^\]]*\]:/, false)) {
state.f = footnoteLinkInside;
stream.next(); // Consume [
if (modeCfg.highlightFormatting) state.formatting = "link";
state.linkText = true;
return getType(state);
}
return switchInline(stream, state, inlineNormal);
}
function footnoteLinkInside(stream, state) {
if (stream.match(/^\]:/, true)) {
state.f = state.inline = footnoteUrl;
if (modeCfg.highlightFormatting) state.formatting = "link";
var returnType = getType(state);
state.linkText = false;
return returnType;
}
stream.match(/^[^\]]+/, true);
return linktext;
}
function footnoteUrl(stream, state) {
// Check if space, and return NULL if so (to avoid marking the space)
if(stream.eatSpace()){
return null;
}
// Match URL
stream.match(/^[^\s]+/, true);
// Check for link title
if (stream.peek() === undefined) { // End of line, set flag to check next line
state.linkTitle = true;
} else { // More content on line, check if link title
stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
}
state.f = state.inline = inlineNormal;
return linkhref;
}
var savedInlineRE = [];
function inlineRE(endChar) {
if (!savedInlineRE[endChar]) {
// Escape endChar for RegExp (taken from http://stackoverflow.com/a/494122/526741)
endChar = (endChar+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
// Match any non-endChar, escaped character, as well as the closing
// endChar.
savedInlineRE[endChar] = new RegExp('^(?:[^\\\\]|\\\\.)*?(' + endChar + ')');
}
return savedInlineRE[endChar];
}
var mode = {
startState: function() {
return {
f: blockNormal,
prevLineHasContent: false,
thisLineHasContent: false,
block: blockNormal,
htmlState: null,
indentation: 0,
inline: inlineNormal,
text: handleText,
formatting: false,
linkText: false,
linkHref: false,
linkTitle: false,
em: false,
strong: false,
header: 0,
taskList: false,
list: false,
listDepth: 0,
quote: 0,
trailingSpace: 0,
trailingSpaceNewLine: false,
strikethrough: false
};
},
copyState: function(s) {
return {
f: s.f,
prevLineHasContent: s.prevLineHasContent,
thisLineHasContent: s.thisLineHasContent,
block: s.block,
htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
indentation: s.indentation,
localMode: s.localMode,
localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
inline: s.inline,
text: s.text,
formatting: false,
linkTitle: s.linkTitle,
em: s.em,
strong: s.strong,
strikethrough: s.strikethrough,
header: s.header,
taskList: s.taskList,
list: s.list,
listDepth: s.listDepth,
quote: s.quote,
trailingSpace: s.trailingSpace,
trailingSpaceNewLine: s.trailingSpaceNewLine,
md_inside: s.md_inside
};
},
token: function(stream, state) {
// Reset state.formatting
state.formatting = false;
if (stream.sol()) {
var forceBlankLine = !!state.header;
// Reset state.header
state.header = 0;
if (stream.match(/^\s*$/, true) || forceBlankLine) {
state.prevLineHasContent = false;
blankLine(state);
return forceBlankLine ? this.token(stream, state) : null;
} else {
state.prevLineHasContent = state.thisLineHasContent;
state.thisLineHasContent = true;
}
// Reset state.taskList
state.taskList = false;
// Reset state.code
state.code = false;
// Reset state.trailingSpace
state.trailingSpace = 0;
state.trailingSpaceNewLine = false;
state.f = state.block;
var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length;
var difference = Math.floor((indentation - state.indentation) / 4) * 4;
if (difference > 4) difference = 4;
var adjustedIndentation = state.indentation + difference;
state.indentationDiff = adjustedIndentation - state.indentation;
state.indentation = adjustedIndentation;
if (indentation > 0) return null;
}
return state.f(stream, state);
},
innerMode: function(state) {
if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};
if (state.localState) return {state: state.localState, mode: state.localMode};
return {state: state, mode: mode};
},
blankLine: blankLine,
getType: getType,
fold: "markdown"
};
return mode;
}, "xml");
CodeMirror.defineMIME("text/x-markdown", "markdown");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/markdown/markdown.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/markdown/markdown.js",
"repo_id": "Humsen",
"token_count": 10040
} | 43 |
// 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("puppet", function () {
// Stores the words from the define method
var words = {};
// Taken, mostly, from the Puppet official variable standards regex
var variable_regex = /({)?([a-z][a-z0-9_]*)?((::[a-z][a-z0-9_]*)*::)?[a-zA-Z0-9_]+(})?/;
// Takes a string of words separated by spaces and adds them as
// keys with the value of the first argument 'style'
function define(style, string) {
var split = string.split(' ');
for (var i = 0; i < split.length; i++) {
words[split[i]] = style;
}
}
// Takes commonly known puppet types/words and classifies them to a style
define('keyword', 'class define site node include import inherits');
define('keyword', 'case if else in and elsif default or');
define('atom', 'false true running present absent file directory undef');
define('builtin', 'action augeas burst chain computer cron destination dport exec ' +
'file filebucket group host icmp iniface interface jump k5login limit log_level ' +
'log_prefix macauthorization mailalias maillist mcx mount nagios_command ' +
'nagios_contact nagios_contactgroup nagios_host nagios_hostdependency ' +
'nagios_hostescalation nagios_hostextinfo nagios_hostgroup nagios_service ' +
'nagios_servicedependency nagios_serviceescalation nagios_serviceextinfo ' +
'nagios_servicegroup nagios_timeperiod name notify outiface package proto reject ' +
'resources router schedule scheduled_task selboolean selmodule service source ' +
'sport ssh_authorized_key sshkey stage state table tidy todest toports tosource ' +
'user vlan yumrepo zfs zone zpool');
// After finding a start of a string ('|") this function attempts to find the end;
// If a variable is encountered along the way, we display it differently when it
// is encapsulated in a double-quoted string.
function tokenString(stream, state) {
var current, prev, found_var = false;
while (!stream.eol() && (current = stream.next()) != state.pending) {
if (current === '$' && prev != '\\' && state.pending == '"') {
found_var = true;
break;
}
prev = current;
}
if (found_var) {
stream.backUp(1);
}
if (current == state.pending) {
state.continueString = false;
} else {
state.continueString = true;
}
return "string";
}
// Main function
function tokenize(stream, state) {
// Matches one whole word
var word = stream.match(/[\w]+/, false);
// Matches attributes (i.e. ensure => present ; 'ensure' would be matched)
var attribute = stream.match(/(\s+)?\w+\s+=>.*/, false);
// Matches non-builtin resource declarations
// (i.e. "apache::vhost {" or "mycustomclasss {" would be matched)
var resource = stream.match(/(\s+)?[\w:_]+(\s+)?{/, false);
// Matches virtual and exported resources (i.e. @@user { ; and the like)
var special_resource = stream.match(/(\s+)?[@]{1,2}[\w:_]+(\s+)?{/, false);
// Finally advance the stream
var ch = stream.next();
// Have we found a variable?
if (ch === '$') {
if (stream.match(variable_regex)) {
// If so, and its in a string, assign it a different color
return state.continueString ? 'variable-2' : 'variable';
}
// Otherwise return an invalid variable
return "error";
}
// Should we still be looking for the end of a string?
if (state.continueString) {
// If so, go through the loop again
stream.backUp(1);
return tokenString(stream, state);
}
// Are we in a definition (class, node, define)?
if (state.inDefinition) {
// If so, return def (i.e. for 'class myclass {' ; 'myclass' would be matched)
if (stream.match(/(\s+)?[\w:_]+(\s+)?/)) {
return 'def';
}
// Match the rest it the next time around
stream.match(/\s+{/);
state.inDefinition = false;
}
// Are we in an 'include' statement?
if (state.inInclude) {
// Match and return the included class
stream.match(/(\s+)?\S+(\s+)?/);
state.inInclude = false;
return 'def';
}
// Do we just have a function on our hands?
// In 'ensure_resource("myclass")', 'ensure_resource' is matched
if (stream.match(/(\s+)?\w+\(/)) {
stream.backUp(1);
return 'def';
}
// Have we matched the prior attribute regex?
if (attribute) {
stream.match(/(\s+)?\w+/);
return 'tag';
}
// Do we have Puppet specific words?
if (word && words.hasOwnProperty(word)) {
// Negates the initial next()
stream.backUp(1);
// Acutally move the stream
stream.match(/[\w]+/);
// We want to process these words differently
// do to the importance they have in Puppet
if (stream.match(/\s+\S+\s+{/, false)) {
state.inDefinition = true;
}
if (word == 'include') {
state.inInclude = true;
}
// Returns their value as state in the prior define methods
return words[word];
}
// Is there a match on a reference?
if (/(^|\s+)[A-Z][\w:_]+/.test(word)) {
// Negate the next()
stream.backUp(1);
// Match the full reference
stream.match(/(^|\s+)[A-Z][\w:_]+/);
return 'def';
}
// Have we matched the prior resource regex?
if (resource) {
stream.match(/(\s+)?[\w:_]+/);
return 'def';
}
// Have we matched the prior special_resource regex?
if (special_resource) {
stream.match(/(\s+)?[@]{1,2}/);
return 'special';
}
// Match all the comments. All of them.
if (ch == "#") {
stream.skipToEnd();
return "comment";
}
// Have we found a string?
if (ch == "'" || ch == '"') {
// Store the type (single or double)
state.pending = ch;
// Perform the looping function to find the end
return tokenString(stream, state);
}
// Match all the brackets
if (ch == '{' || ch == '}') {
return 'bracket';
}
// Match characters that we are going to assume
// are trying to be regex
if (ch == '/') {
stream.match(/.*?\//);
return 'variable-3';
}
// Match all the numbers
if (ch.match(/[0-9]/)) {
stream.eatWhile(/[0-9]+/);
return 'number';
}
// Match the '=' and '=>' operators
if (ch == '=') {
if (stream.peek() == '>') {
stream.next();
}
return "operator";
}
// Keep advancing through all the rest
stream.eatWhile(/[\w-]/);
// Return a blank line for everything else
return null;
}
// Start it all
return {
startState: function () {
var state = {};
state.inDefinition = false;
state.inInclude = false;
state.continueString = false;
state.pending = false;
return state;
},
token: function (stream, state) {
// Strip the spaces, but regex will account for them eitherway
if (stream.eatSpace()) return null;
// Go through the main process
return tokenize(stream, state);
}
};
});
CodeMirror.defineMIME("text/x-puppet", "puppet");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/puppet/puppet.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/puppet/puppet.js",
"repo_id": "Humsen",
"token_count": 2944
} | 44 |
// 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('smalltalk', function(config) {
var specialChars = /[+\-\/\\*~<>=@%|&?!.,:;^]/;
var keywords = /true|false|nil|self|super|thisContext/;
var Context = function(tokenizer, parent) {
this.next = tokenizer;
this.parent = parent;
};
var Token = function(name, context, eos) {
this.name = name;
this.context = context;
this.eos = eos;
};
var State = function() {
this.context = new Context(next, null);
this.expectVariable = true;
this.indentation = 0;
this.userIndentationDelta = 0;
};
State.prototype.userIndent = function(indentation) {
this.userIndentationDelta = indentation > 0 ? (indentation / config.indentUnit - this.indentation) : 0;
};
var next = function(stream, context, state) {
var token = new Token(null, context, false);
var aChar = stream.next();
if (aChar === '"') {
token = nextComment(stream, new Context(nextComment, context));
} else if (aChar === '\'') {
token = nextString(stream, new Context(nextString, context));
} else if (aChar === '#') {
if (stream.peek() === '\'') {
stream.next();
token = nextSymbol(stream, new Context(nextSymbol, context));
} else {
if (stream.eatWhile(/[^\s.{}\[\]()]/))
token.name = 'string-2';
else
token.name = 'meta';
}
} else if (aChar === '$') {
if (stream.next() === '<') {
stream.eatWhile(/[^\s>]/);
stream.next();
}
token.name = 'string-2';
} else if (aChar === '|' && state.expectVariable) {
token.context = new Context(nextTemporaries, context);
} else if (/[\[\]{}()]/.test(aChar)) {
token.name = 'bracket';
token.eos = /[\[{(]/.test(aChar);
if (aChar === '[') {
state.indentation++;
} else if (aChar === ']') {
state.indentation = Math.max(0, state.indentation - 1);
}
} else if (specialChars.test(aChar)) {
stream.eatWhile(specialChars);
token.name = 'operator';
token.eos = aChar !== ';'; // ; cascaded message expression
} else if (/\d/.test(aChar)) {
stream.eatWhile(/[\w\d]/);
token.name = 'number';
} else if (/[\w_]/.test(aChar)) {
stream.eatWhile(/[\w\d_]/);
token.name = state.expectVariable ? (keywords.test(stream.current()) ? 'keyword' : 'variable') : null;
} else {
token.eos = state.expectVariable;
}
return token;
};
var nextComment = function(stream, context) {
stream.eatWhile(/[^"]/);
return new Token('comment', stream.eat('"') ? context.parent : context, true);
};
var nextString = function(stream, context) {
stream.eatWhile(/[^']/);
return new Token('string', stream.eat('\'') ? context.parent : context, false);
};
var nextSymbol = function(stream, context) {
stream.eatWhile(/[^']/);
return new Token('string-2', stream.eat('\'') ? context.parent : context, false);
};
var nextTemporaries = function(stream, context) {
var token = new Token(null, context, false);
var aChar = stream.next();
if (aChar === '|') {
token.context = context.parent;
token.eos = true;
} else {
stream.eatWhile(/[^|]/);
token.name = 'variable';
}
return token;
};
return {
startState: function() {
return new State;
},
token: function(stream, state) {
state.userIndent(stream.indentation());
if (stream.eatSpace()) {
return null;
}
var token = state.context.next(stream, state.context, state);
state.context = token.context;
state.expectVariable = token.eos;
return token.name;
},
blankLine: function(state) {
state.userIndent(0);
},
indent: function(state, textAfter) {
var i = state.context.next === next && textAfter && textAfter.charAt(0) === ']' ? -1 : state.userIndentationDelta;
return (state.indentation + i) * config.indentUnit;
},
electricChars: ']'
};
});
CodeMirror.defineMIME('text/x-stsrc', {name: 'smalltalk'});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/smalltalk/smalltalk.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/smalltalk/smalltalk.js",
"repo_id": "Humsen",
"token_count": 1847
} | 45 |
.cm-tw-syntaxerror {
color: #FFF;
background-color: #900;
}
.cm-tw-deleted {
text-decoration: line-through;
}
.cm-tw-header5 {
font-weight: bold;
}
.cm-tw-listitem:first-child { /*Added first child to fix duplicate padding when highlighting*/
padding-left: 10px;
}
.cm-tw-box {
border-top-width: 0px ! important;
border-style: solid;
border-width: 1px;
border-color: inherit;
}
.cm-tw-underline {
text-decoration: underline;
} | Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/tiki/tiki.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/tiki/tiki.css",
"repo_id": "Humsen",
"token_count": 177
} | 46 |
/*
Copyright (C) 2011 by MarkLogic Corporation
Author: Mike Brevoort <mike@brevoort.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
.cm-s-xq-dark.CodeMirror { background: #0a001f; color: #f8f8f8; }
.cm-s-xq-dark .CodeMirror-selected { background: #27007A !important; }
.cm-s-xq-dark.CodeMirror ::selection { background: rgba(39, 0, 122, 0.99); }
.cm-s-xq-dark.CodeMirror ::-moz-selection { background: rgba(39, 0, 122, 0.99); }
.cm-s-xq-dark .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; }
.cm-s-xq-dark .CodeMirror-guttermarker { color: #FFBD40; }
.cm-s-xq-dark .CodeMirror-guttermarker-subtle { color: #f8f8f8; }
.cm-s-xq-dark .CodeMirror-linenumber { color: #f8f8f8; }
.cm-s-xq-dark .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-xq-dark span.cm-keyword {color: #FFBD40;}
.cm-s-xq-dark span.cm-atom {color: #6C8CD5;}
.cm-s-xq-dark span.cm-number {color: #164;}
.cm-s-xq-dark span.cm-def {color: #FFF; text-decoration:underline;}
.cm-s-xq-dark span.cm-variable {color: #FFF;}
.cm-s-xq-dark span.cm-variable-2 {color: #EEE;}
.cm-s-xq-dark span.cm-variable-3 {color: #DDD;}
.cm-s-xq-dark span.cm-property {}
.cm-s-xq-dark span.cm-operator {}
.cm-s-xq-dark span.cm-comment {color: gray;}
.cm-s-xq-dark span.cm-string {color: #9FEE00;}
.cm-s-xq-dark span.cm-meta {color: yellow;}
.cm-s-xq-dark span.cm-qualifier {color: #FFF700;}
.cm-s-xq-dark span.cm-builtin {color: #30a;}
.cm-s-xq-dark span.cm-bracket {color: #cc7;}
.cm-s-xq-dark span.cm-tag {color: #FFBD40;}
.cm-s-xq-dark span.cm-attribute {color: #FFF700;}
.cm-s-xq-dark span.cm-error {color: #f00;}
.cm-s-xq-dark .CodeMirror-activeline-background {background: #27282E !important;}
.cm-s-xq-dark .CodeMirror-matchingbracket {outline:1px solid grey; color:white !important;} | Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/xq-dark.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/xq-dark.css",
"repo_id": "Humsen",
"token_count": 1048
} | 47 |
/*!
* jQuery Cookie Plugin v1.4.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function encode(s) {
return config.raw ? s : encodeURIComponent(s);
}
function decode(s) {
return config.raw ? s : decodeURIComponent(s);
}
function stringifyCookieValue(value) {
return encode(config.json ? JSON.stringify(value) : String(value));
}
function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
// If we can't parse the cookie, ignore it, it's unusable.
s = decodeURIComponent(s.replace(pluses, ' '));
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}
function read(s, converter) {
var value = config.raw ? s : parseCookieValue(s);
return $.isFunction(converter) ? converter(value) : value;
}
var config = $.cookie = function (key, value, options) {
// Write
if (value !== undefined && !$.isFunction(value)) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setTime(+t + days * 864e+5);
}
return (document.cookie = [
encode(key), '=', stringifyCookieValue(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// Read
var result = key ? undefined : {};
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all. Also prevents odd result when
// calling $.cookie().
var cookies = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = parts.join('=');
if (key && key === name) {
// If second argument (value) is a function it's a converter...
result = read(cookie, value);
break;
}
// Prevent storing a cookie that we couldn't decode.
if (!key && (cookie = read(cookie)) !== undefined) {
result[name] = cookie;
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) === undefined) {
return false;
}
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
}));
| Humsen/web/web-mobile/WebContent/plugins/jquery/js/jquery.cookie.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/jquery/js/jquery.cookie.js",
"repo_id": "Humsen",
"token_count": 1158
} | 48 |
#发送邮箱
email.from.user=yige_robot@foxmail.com
email.from.password=ejmfrxvtxkzygjhj
#接收邮箱
email.to.user=husen@hemingsheng.cn | Humsen/web/web-mobile/config/config.properties/0 | {
"file_path": "Humsen/web/web-mobile/config/config.properties",
"repo_id": "Humsen",
"token_count": 77
} | 49 |
@charset "UTF-8";
.editor-form-div {
margin: 20px 15px;
}
.article-type {
width: initial;
}
.category-width {
width: 220px;
}
.category-input {
margin-left: 8px;
} | Humsen/web/web-pc/WebContent/css/upload/editor-article.css/0 | {
"file_path": "Humsen/web/web-pc/WebContent/css/upload/editor-article.css",
"repo_id": "Humsen",
"token_count": 78
} | 50 |
/**
* 首页
*
* @author 何明胜
*
* 2017年12月15日
*/
/** 加载插件 * */
$.ajax({
url : '/plugins/plugins.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$($('head')[0]).find('script:first').after(data);
}
});
$(function() {
/** 顶部导航栏 **/
$.ajax({
url : '/module/navigation/topbar.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$('#menuBarNo').before(data);
}
});
/** 登录控制 **/
$.ajax({
url : '/module/login/login.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$('#menuBarNo').before(data);
}
});
/** 左侧导航栏 **/
$.ajax({
url : '/module/navigation/leftbar.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$('#fh5co-main').before(data);
}
});
/** 右侧导航栏 **/
$.ajax({
url : '/module/navigation/rightbar.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$('#fh5co-main').after(data);
}
});
});
$(document).ready(function() {
$('#indexCarousel').carousel({
interval : 3000
});// 每隔3秒自动轮播
}); | Humsen/web/web-pc/WebContent/js/index/index.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/js/index/index.js",
"repo_id": "Humsen",
"token_count": 853
} | 51 |
table.dataTable {
clear: both;
margin-top: 6px !important;
margin-bottom: 6px !important;
max-width: none !important;
border-collapse: separate !important;
}
table.dataTable td,
table.dataTable th {
-webkit-box-sizing: content-box;
box-sizing: content-box;
}
table.dataTable td.dataTables_empty,
table.dataTable th.dataTables_empty {
text-align: center;
}
table.dataTable.nowrap th,
table.dataTable.nowrap td {
white-space: nowrap;
}
div.dataTables_wrapper div.dataTables_length label {
font-weight: normal;
text-align: left;
white-space: nowrap;
}
div.dataTables_wrapper div.dataTables_length select {
width: 75px;
display: inline-block;
}
div.dataTables_wrapper div.dataTables_filter {
text-align: right;
}
div.dataTables_wrapper div.dataTables_filter label {
font-weight: normal;
white-space: nowrap;
text-align: left;
}
div.dataTables_wrapper div.dataTables_filter input {
margin-left: 0.5em;
display: inline-block;
width: auto;
}
div.dataTables_wrapper div.dataTables_info {
padding-top: 8px;
white-space: nowrap;
}
div.dataTables_wrapper div.dataTables_paginate {
margin: 0;
white-space: nowrap;
text-align: right;
}
div.dataTables_wrapper div.dataTables_paginate ul.pagination {
margin: 2px 0;
white-space: nowrap;
}
div.dataTables_wrapper div.dataTables_processing {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
margin-left: -100px;
margin-top: -26px;
text-align: center;
padding: 1em 0;
}
table.dataTable thead > tr > th.sorting_asc, table.dataTable thead > tr > th.sorting_desc, table.dataTable thead > tr > th.sorting,
table.dataTable thead > tr > td.sorting_asc,
table.dataTable thead > tr > td.sorting_desc,
table.dataTable thead > tr > td.sorting {
padding-right: 30px;
}
table.dataTable thead > tr > th:active,
table.dataTable thead > tr > td:active {
outline: none;
}
table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled {
cursor: pointer;
position: relative;
}
table.dataTable thead .sorting:after,
table.dataTable thead .sorting_asc:after,
table.dataTable thead .sorting_desc:after,
table.dataTable thead .sorting_asc_disabled:after,
table.dataTable thead .sorting_desc_disabled:after {
position: absolute;
bottom: 8px;
right: 8px;
display: block;
font-family: 'Glyphicons Halflings';
opacity: 0.5;
}
table.dataTable thead .sorting:after {
opacity: 0.2;
content: "\e150";
/* sort */
}
table.dataTable thead .sorting_asc:after {
content: "\e155";
/* sort-by-attributes */
}
table.dataTable thead .sorting_desc:after {
content: "\e156";
/* sort-by-attributes-alt */
}
table.dataTable thead .sorting_asc_disabled:after,
table.dataTable thead .sorting_desc_disabled:after {
color: #eee;
}
div.dataTables_scrollHead table.dataTable {
margin-bottom: 0 !important;
}
div.dataTables_scrollBody > table {
border-top: none;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
div.dataTables_scrollBody > table > thead .sorting:after,
div.dataTables_scrollBody > table > thead .sorting_asc:after,
div.dataTables_scrollBody > table > thead .sorting_desc:after {
display: none;
}
div.dataTables_scrollBody > table > tbody > tr:first-child > th,
div.dataTables_scrollBody > table > tbody > tr:first-child > td {
border-top: none;
}
div.dataTables_scrollFoot > table {
margin-top: 0 !important;
border-top: none;
}
@media screen and (max-width: 767px) {
div.dataTables_wrapper div.dataTables_length,
div.dataTables_wrapper div.dataTables_filter,
div.dataTables_wrapper div.dataTables_info,
div.dataTables_wrapper div.dataTables_paginate {
text-align: center;
}
}
table.dataTable.table-condensed > thead > tr > th {
padding-right: 20px;
}
table.dataTable.table-condensed .sorting:after,
table.dataTable.table-condensed .sorting_asc:after,
table.dataTable.table-condensed .sorting_desc:after {
top: 6px;
right: 6px;
}
table.table-bordered.dataTable th,
table.table-bordered.dataTable td {
border-left-width: 0;
}
table.table-bordered.dataTable th:last-child, table.table-bordered.dataTable th:last-child,
table.table-bordered.dataTable td:last-child,
table.table-bordered.dataTable td:last-child {
border-right-width: 0;
}
table.table-bordered.dataTable tbody th,
table.table-bordered.dataTable tbody td {
border-bottom-width: 0;
}
div.dataTables_scrollHead table.table-bordered {
border-bottom-width: 0;
}
div.table-responsive > div.dataTables_wrapper > div.row {
margin: 0;
}
div.table-responsive > div.dataTables_wrapper > div.row > div[class^="col-"]:first-child {
padding-left: 0;
}
div.table-responsive > div.dataTables_wrapper > div.row > div[class^="col-"]:last-child {
padding-right: 0;
}
| Humsen/web/web-pc/WebContent/plugins/DataTables/css/dataTables.bootstrap.css/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/DataTables/css/dataTables.bootstrap.css",
"repo_id": "Humsen",
"token_count": 1782
} | 52 |
/*
* Table styles
*/
table.dataTable {
width: 100%;
margin: 0 auto;
clear: both;
border-collapse: separate;
border-spacing: 0;
/*
* Header and footer styles
*/
/*
* Body styles
*/
}
table.dataTable thead th,
table.dataTable thead td,
table.dataTable tfoot th,
table.dataTable tfoot td {
padding: 4px 10px;
}
table.dataTable thead th,
table.dataTable tfoot th {
font-weight: bold;
}
table.dataTable thead th:active,
table.dataTable thead td:active {
outline: none;
}
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting {
cursor: pointer;
*cursor: hand;
}
table.dataTable thead th div.DataTables_sort_wrapper {
position: relative;
padding-right: 10px;
}
table.dataTable thead th div.DataTables_sort_wrapper span {
position: absolute;
top: 50%;
margin-top: -8px;
right: -5px;
}
table.dataTable thead th.ui-state-default {
border-right-width: 0;
}
table.dataTable thead th.ui-state-default:last-child {
border-right-width: 1px;
}
table.dataTable tbody tr {
background-color: #ffffff;
}
table.dataTable tbody tr.selected {
background-color: #B0BED9;
}
table.dataTable tbody th,
table.dataTable tbody td {
padding: 8px 10px;
}
table.dataTable th.center,
table.dataTable td.center,
table.dataTable td.dataTables_empty {
text-align: center;
}
table.dataTable th.right,
table.dataTable td.right {
text-align: right;
}
table.dataTable.row-border tbody th, table.dataTable.row-border tbody td, table.dataTable.display tbody th, table.dataTable.display tbody td {
border-top: 1px solid #ddd;
}
table.dataTable.row-border tbody tr:first-child th,
table.dataTable.row-border tbody tr:first-child td, table.dataTable.display tbody tr:first-child th,
table.dataTable.display tbody tr:first-child td {
border-top: none;
}
table.dataTable.cell-border tbody th, table.dataTable.cell-border tbody td {
border-top: 1px solid #ddd;
border-right: 1px solid #ddd;
}
table.dataTable.cell-border tbody tr th:first-child,
table.dataTable.cell-border tbody tr td:first-child {
border-left: 1px solid #ddd;
}
table.dataTable.cell-border tbody tr:first-child th,
table.dataTable.cell-border tbody tr:first-child td {
border-top: none;
}
table.dataTable.stripe tbody tr.odd, table.dataTable.display tbody tr.odd {
background-color: #f9f9f9;
}
table.dataTable.stripe tbody tr.odd.selected, table.dataTable.display tbody tr.odd.selected {
background-color: #abb9d3;
}
table.dataTable.hover tbody tr:hover,
table.dataTable.hover tbody tr.odd:hover,
table.dataTable.hover tbody tr.even:hover, table.dataTable.display tbody tr:hover,
table.dataTable.display tbody tr.odd:hover,
table.dataTable.display tbody tr.even:hover {
background-color: whitesmoke;
}
table.dataTable.hover tbody tr:hover.selected,
table.dataTable.hover tbody tr.odd:hover.selected,
table.dataTable.hover tbody tr.even:hover.selected, table.dataTable.display tbody tr:hover.selected,
table.dataTable.display tbody tr.odd:hover.selected,
table.dataTable.display tbody tr.even:hover.selected {
background-color: #a9b7d1;
}
table.dataTable.order-column tbody tr > .sorting_1,
table.dataTable.order-column tbody tr > .sorting_2,
table.dataTable.order-column tbody tr > .sorting_3, table.dataTable.display tbody tr > .sorting_1,
table.dataTable.display tbody tr > .sorting_2,
table.dataTable.display tbody tr > .sorting_3 {
background-color: #f9f9f9;
}
table.dataTable.order-column tbody tr.selected > .sorting_1,
table.dataTable.order-column tbody tr.selected > .sorting_2,
table.dataTable.order-column tbody tr.selected > .sorting_3, table.dataTable.display tbody tr.selected > .sorting_1,
table.dataTable.display tbody tr.selected > .sorting_2,
table.dataTable.display tbody tr.selected > .sorting_3 {
background-color: #acbad4;
}
table.dataTable.display tbody tr.odd > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd > .sorting_1 {
background-color: #f1f1f1;
}
table.dataTable.display tbody tr.odd > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd > .sorting_2 {
background-color: #f3f3f3;
}
table.dataTable.display tbody tr.odd > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd > .sorting_3 {
background-color: whitesmoke;
}
table.dataTable.display tbody tr.odd.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_1 {
background-color: #a6b3cd;
}
table.dataTable.display tbody tr.odd.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_2 {
background-color: #a7b5ce;
}
table.dataTable.display tbody tr.odd.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_3 {
background-color: #a9b6d0;
}
table.dataTable.display tbody tr.even > .sorting_1, table.dataTable.order-column.stripe tbody tr.even > .sorting_1 {
background-color: #f9f9f9;
}
table.dataTable.display tbody tr.even > .sorting_2, table.dataTable.order-column.stripe tbody tr.even > .sorting_2 {
background-color: #fbfbfb;
}
table.dataTable.display tbody tr.even > .sorting_3, table.dataTable.order-column.stripe tbody tr.even > .sorting_3 {
background-color: #fdfdfd;
}
table.dataTable.display tbody tr.even.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_1 {
background-color: #acbad4;
}
table.dataTable.display tbody tr.even.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_2 {
background-color: #adbbd6;
}
table.dataTable.display tbody tr.even.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_3 {
background-color: #afbdd8;
}
table.dataTable.display tbody tr:hover > .sorting_1,
table.dataTable.display tbody tr.odd:hover > .sorting_1,
table.dataTable.display tbody tr.even:hover > .sorting_1, table.dataTable.order-column.hover tbody tr:hover > .sorting_1,
table.dataTable.order-column.hover tbody tr.odd:hover > .sorting_1,
table.dataTable.order-column.hover tbody tr.even:hover > .sorting_1 {
background-color: #eaeaea;
}
table.dataTable.display tbody tr:hover > .sorting_2,
table.dataTable.display tbody tr.odd:hover > .sorting_2,
table.dataTable.display tbody tr.even:hover > .sorting_2, table.dataTable.order-column.hover tbody tr:hover > .sorting_2,
table.dataTable.order-column.hover tbody tr.odd:hover > .sorting_2,
table.dataTable.order-column.hover tbody tr.even:hover > .sorting_2 {
background-color: #ebebeb;
}
table.dataTable.display tbody tr:hover > .sorting_3,
table.dataTable.display tbody tr.odd:hover > .sorting_3,
table.dataTable.display tbody tr.even:hover > .sorting_3, table.dataTable.order-column.hover tbody tr:hover > .sorting_3,
table.dataTable.order-column.hover tbody tr.odd:hover > .sorting_3,
table.dataTable.order-column.hover tbody tr.even:hover > .sorting_3 {
background-color: #eeeeee;
}
table.dataTable.display tbody tr:hover.selected > .sorting_1,
table.dataTable.display tbody tr.odd:hover.selected > .sorting_1,
table.dataTable.display tbody tr.even:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_1,
table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_1,
table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_1 {
background-color: #a1aec7;
}
table.dataTable.display tbody tr:hover.selected > .sorting_2,
table.dataTable.display tbody tr.odd:hover.selected > .sorting_2,
table.dataTable.display tbody tr.even:hover.selected > .sorting_2, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_2,
table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_2,
table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_2 {
background-color: #a2afc8;
}
table.dataTable.display tbody tr:hover.selected > .sorting_3,
table.dataTable.display tbody tr.odd:hover.selected > .sorting_3,
table.dataTable.display tbody tr.even:hover.selected > .sorting_3, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_3,
table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_3,
table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_3 {
background-color: #a4b2cb;
}
table.dataTable.nowrap th, table.dataTable.nowrap td {
white-space: nowrap;
}
table.dataTable.compact thead th,
table.dataTable.compact thead td {
padding: 5px 9px;
}
table.dataTable.compact tfoot th,
table.dataTable.compact tfoot td {
padding: 5px 9px 3px 9px;
}
table.dataTable.compact tbody th,
table.dataTable.compact tbody td {
padding: 4px 5px;
}
table.dataTable th.dt-left,
table.dataTable td.dt-left {
text-align: left;
}
table.dataTable th.dt-center,
table.dataTable td.dt-center,
table.dataTable td.dataTables_empty {
text-align: center;
}
table.dataTable th.dt-right,
table.dataTable td.dt-right {
text-align: right;
}
table.dataTable th.dt-justify,
table.dataTable td.dt-justify {
text-align: justify;
}
table.dataTable th.dt-nowrap,
table.dataTable td.dt-nowrap {
white-space: nowrap;
}
table.dataTable thead th.dt-head-left,
table.dataTable thead td.dt-head-left,
table.dataTable tfoot th.dt-head-left,
table.dataTable tfoot td.dt-head-left {
text-align: left;
}
table.dataTable thead th.dt-head-center,
table.dataTable thead td.dt-head-center,
table.dataTable tfoot th.dt-head-center,
table.dataTable tfoot td.dt-head-center {
text-align: center;
}
table.dataTable thead th.dt-head-right,
table.dataTable thead td.dt-head-right,
table.dataTable tfoot th.dt-head-right,
table.dataTable tfoot td.dt-head-right {
text-align: right;
}
table.dataTable thead th.dt-head-justify,
table.dataTable thead td.dt-head-justify,
table.dataTable tfoot th.dt-head-justify,
table.dataTable tfoot td.dt-head-justify {
text-align: justify;
}
table.dataTable thead th.dt-head-nowrap,
table.dataTable thead td.dt-head-nowrap,
table.dataTable tfoot th.dt-head-nowrap,
table.dataTable tfoot td.dt-head-nowrap {
white-space: nowrap;
}
table.dataTable tbody th.dt-body-left,
table.dataTable tbody td.dt-body-left {
text-align: left;
}
table.dataTable tbody th.dt-body-center,
table.dataTable tbody td.dt-body-center {
text-align: center;
}
table.dataTable tbody th.dt-body-right,
table.dataTable tbody td.dt-body-right {
text-align: right;
}
table.dataTable tbody th.dt-body-justify,
table.dataTable tbody td.dt-body-justify {
text-align: justify;
}
table.dataTable tbody th.dt-body-nowrap,
table.dataTable tbody td.dt-body-nowrap {
white-space: nowrap;
}
table.dataTable,
table.dataTable th,
table.dataTable td {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
/*
* Control feature layout
*/
.dataTables_wrapper {
position: relative;
clear: both;
*zoom: 1;
zoom: 1;
}
.dataTables_wrapper .dataTables_length {
float: left;
}
.dataTables_wrapper .dataTables_filter {
float: right;
text-align: right;
}
.dataTables_wrapper .dataTables_filter input {
margin-left: 0.5em;
}
.dataTables_wrapper .dataTables_info {
clear: both;
float: left;
padding-top: 0.55em;
}
.dataTables_wrapper .dataTables_paginate {
float: right;
text-align: right;
}
.dataTables_wrapper .dataTables_paginate .fg-button {
box-sizing: border-box;
display: inline-block;
min-width: 1.5em;
padding: 0.5em;
margin-left: 2px;
text-align: center;
text-decoration: none !important;
cursor: pointer;
*cursor: hand;
color: #333 !important;
border: 1px solid transparent;
}
.dataTables_wrapper .dataTables_paginate .fg-button:active {
outline: none;
}
.dataTables_wrapper .dataTables_paginate .fg-button:first-child {
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
}
.dataTables_wrapper .dataTables_paginate .fg-button:last-child {
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
.dataTables_wrapper .dataTables_processing {
position: absolute;
top: 50%;
left: 50%;
width: 100%;
height: 40px;
margin-left: -50%;
margin-top: -25px;
padding-top: 20px;
text-align: center;
font-size: 1.2em;
background-color: white;
background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255, 255, 255, 0)), color-stop(25%, rgba(255, 255, 255, 0.9)), color-stop(75%, rgba(255, 255, 255, 0.9)), color-stop(100%, rgba(255, 255, 255, 0)));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
/* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
/* FF3.6+ */
background: -ms-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
/* IE10+ */
background: -o-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
/* Opera 11.10+ */
background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
/* W3C */
}
.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter,
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_processing,
.dataTables_wrapper .dataTables_paginate {
color: #333;
}
.dataTables_wrapper .dataTables_scroll {
clear: both;
}
.dataTables_wrapper .dataTables_scrollBody {
*margin-top: -1px;
-webkit-overflow-scrolling: touch;
}
.dataTables_wrapper .ui-widget-header {
font-weight: normal;
}
.dataTables_wrapper .ui-toolbar {
padding: 8px;
}
.dataTables_wrapper:after {
visibility: hidden;
display: block;
content: "";
clear: both;
height: 0;
}
@media screen and (max-width: 767px) {
.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter,
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_paginate {
float: none;
text-align: center;
}
.dataTables_wrapper .dataTables_filter,
.dataTables_wrapper .dataTables_paginate {
margin-top: 0.5em;
}
}
| Humsen/web/web-pc/WebContent/plugins/DataTables/css/jquery.dataTables_themeroller.css/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/DataTables/css/jquery.dataTables_themeroller.css",
"repo_id": "Humsen",
"token_count": 5359
} | 53 |
env:
browser: true
es6: true
# See https://github.com/OCA/odoo-community.org/issues/37#issuecomment-470686449
parserOptions:
ecmaVersion: 2019
overrides:
- files:
- "**/*.esm.js"
parserOptions:
sourceType: module
# Globals available in Odoo that shouldn't produce errorings
globals:
_: readonly
$: readonly
fuzzy: readonly
jQuery: readonly
moment: readonly
odoo: readonly
openerp: readonly
owl: readonly
luxon: readonly
# Styling is handled by Prettier, so we only need to enable AST rules;
# see https://github.com/OCA/maintainer-quality-tools/pull/618#issuecomment-558576890
rules:
accessor-pairs: warn
array-callback-return: warn
callback-return: warn
capitalized-comments:
- warn
- always
- ignoreConsecutiveComments: true
ignoreInlineComments: true
complexity:
- warn
- 15
constructor-super: warn
dot-notation: warn
eqeqeq: warn
global-require: warn
handle-callback-err: warn
id-blacklist: warn
id-match: warn
init-declarations: error
max-depth: warn
max-nested-callbacks: warn
max-statements-per-line: warn
no-alert: warn
no-array-constructor: warn
no-caller: warn
no-case-declarations: warn
no-class-assign: warn
no-cond-assign: error
no-const-assign: error
no-constant-condition: warn
no-control-regex: warn
no-debugger: error
no-delete-var: warn
no-div-regex: warn
no-dupe-args: error
no-dupe-class-members: error
no-dupe-keys: error
no-duplicate-case: error
no-duplicate-imports: error
no-else-return: warn
no-empty-character-class: warn
no-empty-function: error
no-empty-pattern: error
no-empty: warn
no-eq-null: error
no-eval: error
no-ex-assign: error
no-extend-native: warn
no-extra-bind: warn
no-extra-boolean-cast: warn
no-extra-label: warn
no-fallthrough: warn
no-func-assign: error
no-global-assign: error
no-implicit-coercion:
- warn
- allow: ["~"]
no-implicit-globals: warn
no-implied-eval: warn
no-inline-comments: warn
no-inner-declarations: warn
no-invalid-regexp: warn
no-irregular-whitespace: warn
no-iterator: warn
no-label-var: warn
no-labels: warn
no-lone-blocks: warn
no-lonely-if: error
no-mixed-requires: error
no-multi-str: warn
no-native-reassign: error
no-negated-condition: warn
no-negated-in-lhs: error
no-new-func: warn
no-new-object: warn
no-new-require: warn
no-new-symbol: warn
no-new-wrappers: warn
no-new: warn
no-obj-calls: warn
no-octal-escape: warn
no-octal: warn
no-param-reassign: warn
no-path-concat: warn
no-process-env: warn
no-process-exit: warn
no-proto: warn
no-prototype-builtins: warn
no-redeclare: warn
no-regex-spaces: warn
no-restricted-globals: warn
no-restricted-imports: warn
no-restricted-modules: warn
no-restricted-syntax: warn
no-return-assign: error
no-script-url: warn
no-self-assign: warn
no-self-compare: warn
no-sequences: warn
no-shadow-restricted-names: warn
no-shadow: warn
no-sparse-arrays: warn
no-sync: warn
no-this-before-super: warn
no-throw-literal: warn
no-undef-init: warn
no-undef: error
no-unmodified-loop-condition: warn
no-unneeded-ternary: error
no-unreachable: error
no-unsafe-finally: error
no-unused-expressions: error
no-unused-labels: error
no-unused-vars: error
no-use-before-define: error
no-useless-call: warn
no-useless-computed-key: warn
no-useless-concat: warn
no-useless-constructor: warn
no-useless-escape: warn
no-useless-rename: warn
no-void: warn
no-with: warn
operator-assignment: [error, always]
prefer-const: warn
radix: warn
require-yield: warn
sort-imports: warn
spaced-comment: [error, always]
strict: [error, function]
use-isnan: error
valid-jsdoc:
- warn
- prefer:
arg: param
argument: param
augments: extends
constructor: class
exception: throws
func: function
method: function
prop: property
return: returns
virtual: abstract
yield: yields
preferType:
array: Array
bool: Boolean
boolean: Boolean
number: Number
object: Object
str: String
string: String
requireParamDescription: false
requireReturn: false
requireReturnDescription: false
requireReturnType: false
valid-typeof: warn
yoda: warn
| OCA/web/.eslintrc.yml/0 | {
"file_path": "OCA/web/.eslintrc.yml",
"repo_id": "OCA",
"token_count": 1744
} | 54 |
[settings]
; see https://github.com/psf/black
multi_line_output=3
include_trailing_comma=True
force_grid_wrap=0
combine_as_imports=True
use_parentheses=True
line_length=88
known_odoo=odoo
known_odoo_addons=odoo.addons
sections=FUTURE,STDLIB,THIRDPARTY,ODOO,ODOO_ADDONS,FIRSTPARTY,LOCALFOLDER
default_section=THIRDPARTY
ensure_newline_before_comments = True
| OCA/web/.isort.cfg/0 | {
"file_path": "OCA/web/.isort.cfg",
"repo_id": "OCA",
"token_count": 144
} | 55 |
===============
Advanced search
===============
..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:49aa0bfa3f44cf2d0a4825e8734b3ddcc51097df43051eaba3d04945a3885a3d
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |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_advanced_search
: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_advanced_search
: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|
More powerful and easy to use search, especially for related fields.
**Table of contents**
.. contents::
:local:
Usage
=====
To use this module, you need to:
* Open *Filters* in a search view
* Select any relational field
* Select operator `is equal to` or `is not equal to`
* The text field changes to a relational selection field where you
can search for the record in question
* Click *Apply*
To search for properties of linked records (ie invoices for customers
with a credit limit higher than X):
* Open *Filters* in a search view
* Select *Add Advanced Filter*
* Edit the advanced filter
* Click *Save*
Note that you can stack searching for properties: Simply add another
advanced search in the selection search window. You can do
this indefinetely, so it is possible to search for moves belonging
to a journal which has a user who is member of a certain group etc.
Note also the domain dialog offers an editable preview in debug mode:
.. image:: https://raw.githubusercontent.com/OCA/web/16.0/web_advanced_search/static/img/debug_mode.png
Known issues / Roadmap
======================
Improvements to the ``domain`` widget, not exclusively related to this addon:
* Use relational widgets when filtering a relational field
* Allow to filter field names
Improvements to the search view in this addon:
* Use widgets ``one2many_tags`` when searching ``one2many`` fields
* Use widgets ``many2many_tags`` when searching ``many2many`` fields
* Allow to edit current full search using the advanced domain editor
Issues:
* Grouped totals can show incorrect values. See https://github.com/odoo/odoo/issues/47950
Changelog
=========
11.0.1.0.2 (2018-10-31)
~~~~~~~~~~~~~~~~~~~~~~~
* Fix initialization of 1st domain node
Sometime the dialog is not ready yet, like on EE version.
Hence when you inject the 1st domain node
the dialog must be already opened.
[simahawk]
11.0.1.0.1 (2018-09-18)
~~~~~~~~~~~~~~~~~~~~~~~
* Fix `undefined` in x2m fields
Before this patch, when searching with the "equals to" operator in any
x2many field, the searched parameter was always `undefined`.
The problem was that the underlying field manager implementation was
treating those fields as x2many, while the widget used was the `one2many`
one.
This patch simply mocks the underlying fake record to make think that
any relational field is always a `one2many`. This sets all pieces in
place and makes the field manager work as expected, and thus you can
search as expected too.
* Make linter happy
[Yajo]
11.0.1.0.0 (2018-07-20)
~~~~~~~~~~~~~~~~~~~~~~~
* Rename, refactor, migrate to v11
[Yajo]
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_advanced_search%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
~~~~~~~
* Therp BV
* Tecnativa
* Camptocamp
Contributors
~~~~~~~~~~~~
* Holger Brunn <hbrunn@therp.nl>
* Rami Alwafaie <rami.alwafaie@initos.com>
* Jose Mª Bernet <josemaria.bernet@guadaltech.es>
* Simone Orsi <simone.orsi@camptocamp.com>
* Dennis Sluijk <d.sluijk@onestein.nl>
* `Tecnativa <https://www.tecnativa.com>`_:
* Vicent Cubells
* Jairo Llopis
* Alexandre Díaz
* `DynApps NV <https://www.dynapps.be>`_:
* Raf Ven
* `Camptocamp <https://www.camptocamp.com>`_
* Iván Todorovich <ivan.todorovich@camptocamp.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-ivantodorovich| image:: https://github.com/ivantodorovich.png?size=40px
:target: https://github.com/ivantodorovich
:alt: ivantodorovich
Current `maintainer <https://odoo-community.org/page/maintainer-role>`__:
|maintainer-ivantodorovich|
This module is part of the `OCA/web <https://github.com/OCA/web/tree/16.0/web_advanced_search>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
| OCA/web/web_advanced_search/README.rst/0 | {
"file_path": "OCA/web/web_advanced_search/README.rst",
"repo_id": "OCA",
"token_count": 1989
} | 56 |
* Holger Brunn <hbrunn@therp.nl>
* Rami Alwafaie <rami.alwafaie@initos.com>
* Jose Mª Bernet <josemaria.bernet@guadaltech.es>
* Simone Orsi <simone.orsi@camptocamp.com>
* Dennis Sluijk <d.sluijk@onestein.nl>
* `Tecnativa <https://www.tecnativa.com>`_:
* Vicent Cubells
* Jairo Llopis
* Alexandre Díaz
* `DynApps NV <https://www.dynapps.be>`_:
* Raf Ven
* `Camptocamp <https://www.camptocamp.com>`_
* Iván Todorovich <ivan.todorovich@camptocamp.com>
| OCA/web/web_advanced_search/readme/CONTRIBUTORS.rst/0 | {
"file_path": "OCA/web/web_advanced_search/readme/CONTRIBUTORS.rst",
"repo_id": "OCA",
"token_count": 212
} | 57 |
/** @odoo-module **/
import {CustomFilterItem} from "@web/search/filter_menu/custom_filter_item";
import {RecordPicker} from "../../js/RecordPicker.esm";
import {patch} from "@web/core/utils/patch";
/**
* Patches the CustomFilterItem for owl widgets.
*/
patch(CustomFilterItem.prototype, "web_advanced_search.CustomFilterItem", {
/**
* @override
*/
setup() {
this._super.apply(this, arguments);
this.OPERATORS.relational = this.OPERATORS.char;
this.FIELD_TYPES.many2one = "relational";
},
/**
* @override
*/
setDefaultValue(condition) {
const res = this._super.apply(this, arguments);
const fieldType = this.fields[condition.field].type;
const genericType = this.FIELD_TYPES[fieldType];
if (genericType === "relational") {
condition.value = 0;
condition.displayedValue = "";
}
return res;
},
/**
* Add displayed value to preFilters for "relational" types.
*
* @override
*/
onApply() {
// To avoid the complete override, we patch this.conditions.map()
const originalMapFn = this.conditions.map;
const self = this;
this.conditions.map = function () {
const preFilters = originalMapFn.apply(this, arguments);
for (const condition of this) {
const field = self.fields[condition.field];
const type = self.FIELD_TYPES[field.type];
if (type === "relational") {
const idx = this.indexOf(condition);
const preFilter = preFilters[idx];
const operator = self.OPERATORS[type][condition.operator];
if (
["=", "!="].includes(operator.symbol) &&
operator.value === undefined
) {
const descriptionArray = [
field.string,
operator.description,
`"${condition.displayedValue}"`,
];
preFilter.description = descriptionArray.join(" ");
}
}
}
return preFilters;
};
const res = this._super.apply(this, arguments);
// Restore original map()
this.conditions.map = originalMapFn;
return res;
},
/**
* @private
* @param {Object} condition
* @param {OwlEvent} ev
*/
onRelationalChanged(condition, ev) {
if (ev.detail) {
condition.value = ev.detail.id;
condition.displayedValue = ev.detail.display_name;
}
},
onValueChange(condition, ev) {
if (!ev.target.value) {
return this.setDefaultValue(condition);
}
const field = this.fields[condition.field];
const type = this.FIELD_TYPES[field.type];
if (type === "relational") {
condition.value = ev.target.value;
condition.displayedValue = ev.target.value;
} else {
this._super.apply(this, arguments);
}
},
});
patch(CustomFilterItem, "web_advanced_search.CustomFilterItem", {
components: {
...CustomFilterItem.components,
RecordPicker,
},
});
export default CustomFilterItem;
| OCA/web/web_advanced_search/static/src/search/filter_menu/custom_filter_item.esm.js/0 | {
"file_path": "OCA/web/web_advanced_search/static/src/search/filter_menu/custom_filter_item.esm.js",
"repo_id": "OCA",
"token_count": 1613
} | 58 |
Allow to set an additional css class to fields in form view.
Use case : you may highlight some fields for training purpose
.. figure:: ../static/description/demo.png
:alt: Colored fields
| OCA/web/web_apply_field_style/readme/DESCRIPTION.rst/0 | {
"file_path": "OCA/web/web_apply_field_style/readme/DESCRIPTION.rst",
"repo_id": "OCA",
"token_count": 53
} | 59 |
* Drop module if/when https://github.com/odoo/odoo/pull/66739 is merged.
| OCA/web/web_calendar_slot_duration/readme/ROADMAP.rst/0 | {
"file_path": "OCA/web/web_calendar_slot_duration/readme/ROADMAP.rst",
"repo_id": "OCA",
"token_count": 26
} | 60 |
# 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-10-11 14:37+0000\n"
"Last-Translator: Adriano Prado <adrianojprado@gmail.com>\n"
"Language-Team: none\n"
"Language: pt_BR\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 "Em Baixo"
#. module: web_chatter_position
#: model:ir.model.fields,field_description:web_chatter_position.field_res_users__chatter_position
msgid "Chatter Position"
msgstr "Posição da Conversa"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__auto
msgid "Responsive"
msgstr "Responsivo"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__sided
msgid "Sided"
msgstr "Lateral"
#. module: web_chatter_position
#: model:ir.model,name:web_chatter_position.model_res_users
msgid "User"
msgstr "Usuário"
| OCA/web/web_chatter_position/i18n/pt_BR.po/0 | {
"file_path": "OCA/web/web_chatter_position/i18n/pt_BR.po",
"repo_id": "OCA",
"token_count": 522
} | 61 |
# Copyright 2019 Alexandre Díaz <dev@redneboa.es>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import SUPERUSER_ID, api
from .models.res_company import URL_BASE
def uninstall_hook(cr, registry):
env = api.Environment(cr, SUPERUSER_ID, {})
env["ir.attachment"].search([("url", "=like", "%s%%" % URL_BASE)]).unlink()
def post_init_hook(cr, registry):
env = api.Environment(cr, SUPERUSER_ID, {})
env["res.company"].search([]).scss_create_or_update_attachment()
| OCA/web/web_company_color/hooks.py/0 | {
"file_path": "OCA/web/web_company_color/hooks.py",
"repo_id": "OCA",
"token_count": 193
} | 62 |
This module change navbar colors based in the company logo colors.
| OCA/web/web_company_color/readme/DESCRIPTION.rst/0 | {
"file_path": "OCA/web/web_company_color/readme/DESCRIPTION.rst",
"repo_id": "OCA",
"token_count": 14
} | 63 |
* Stefan Rijnhart <stefan@opener.amsterdam>
* Robin Conjour <rconjour@demolium.com>
* Dhara Solanki <dhara.solanki@initos.com>
| OCA/web/web_copy_confirm/readme/CONTRIBUTORS.rst/0 | {
"file_path": "OCA/web/web_copy_confirm/readme/CONTRIBUTORS.rst",
"repo_id": "OCA",
"token_count": 54
} | 64 |
# 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"
"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_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 ""
#. 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 ""
#. module: web_dark_mode
#: model:ir.model,name:web_dark_mode.model_ir_http
msgid "HTTP Routing"
msgstr ""
#. module: web_dark_mode
#: model:ir.model,name:web_dark_mode.model_res_users
msgid "User"
msgstr ""
| OCA/web/web_dark_mode/i18n/web_dark_mode.pot/0 | {
"file_path": "OCA/web/web_dark_mode/i18n/web_dark_mode.pot",
"repo_id": "OCA",
"token_count": 386
} | 65 |
from . import models
| OCA/web/web_dashboard_tile/__init__.py/0 | {
"file_path": "OCA/web/web_dashboard_tile/__init__.py",
"repo_id": "OCA",
"token_count": 5
} | 66 |
<?xml version="1.0" encoding="utf-8" ?>
<odoo noupdate="1">
<record id="model_tile_rule" model="ir.rule">
<field name="name">tile.owner</field>
<field name="model_id" ref="model_tile_tile" />
<field name="groups" eval="[(4, ref('base.group_user'))]" />
<field name="domain_force">
[
'|',
('user_id','=',user.id),
('user_id','=',False),
'|',
('group_ids','=',False),
('group_ids','in',[g.id for g in user.groups_id]),
]
</field>
</record>
</odoo>
| OCA/web/web_dashboard_tile/security/ir_rule.xml/0 | {
"file_path": "OCA/web/web_dashboard_tile/security/ir_rule.xml",
"repo_id": "OCA",
"token_count": 308
} | 67 |
# Copyright 2015 ACSONE SA/NV
# Copyright 2018 Amaris
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Web Dialog Size",
"summary": """
A module that lets the user expand a
dialog box to the full screen width.""",
"author": "ACSONE SA/NV, "
"Therp BV, "
"Siddharth Bhalgami,"
"Tecnativa, "
"Amaris, "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/web",
"category": "web",
"version": "16.0.1.0.0",
"license": "AGPL-3",
"depends": ["web"],
"installable": True,
"assets": {
"web.assets_backend": [
"/web_dialog_size/static/src/js/web_dialog_size.js",
"/web_dialog_size/static/src/js/web_dialog_size.esm.js",
"/web_dialog_size/static/src/js/web_dialog_draggable.esm.js",
"/web_dialog_size/static/src/scss/web_dialog_size.scss",
"/web_dialog_size/static/src/xml/web_dialog_size.xml",
"/web_dialog_size/static/src/xml/ExpandButton.xml",
"/web_dialog_size/static/src/xml/DialogDraggable.xml",
],
},
}
| OCA/web/web_dialog_size/__manifest__.py/0 | {
"file_path": "OCA/web/web_dialog_size/__manifest__.py",
"repo_id": "OCA",
"token_count": 544
} | 68 |
/** @odoo-module **/
import {ActionDialog} from "@web/webclient/actions/action_dialog";
import {onMounted, useExternalListener} from "@odoo/owl";
import {useListener} from "@web/core/utils/hooks";
import {LegacyComponent} from "@web/legacy/legacy_component";
import {Dialog} from "@web/core/dialog/dialog";
export class DialogDraggable extends LegacyComponent {
setup() {
this.element_position = {x: 0, y: 0};
this.mouse_to_element_ratio = {x: 0, y: 0};
const bound_onDrag = this.onDrag.bind(this);
useListener("mousedown", "header.modal-header", (event) => {
const y = parseInt(this.el.querySelector(".modal-content").offsetTop, 10);
const x = parseInt(this.el.querySelector(".modal-content").offsetLeft, 10);
this.mouse_to_element_ratio = {x: event.x - x, y: event.y - y};
this.element_position = {
x: event.x - this.mouse_to_element_ratio.x - x,
y: event.y - this.mouse_to_element_ratio.y - y,
};
document.addEventListener("mousemove", bound_onDrag);
});
useExternalListener(document, "mouseup", () =>
document.removeEventListener("mousemove", bound_onDrag)
);
onMounted(() => {
this.el.querySelector(".modal-content").classList.add("position-absolute");
this.el.parentNode.classList.add("position-relative");
});
}
getMovePosition({x, y}) {
return {
x: x - this.mouse_to_element_ratio.x - this.element_position.x,
y: y - this.mouse_to_element_ratio.y - this.element_position.y,
};
}
onDrag(event) {
const {x, y} = this.getMovePosition(event);
const el = this.el.querySelector(".modal-content");
el.style.left = `${x}px`;
el.style.top = `${y}px`;
}
}
DialogDraggable.template = "DialogDraggable";
Dialog.components = Object.assign(Dialog.components || {}, {DialogDraggable});
Object.assign(ActionDialog.components, {DialogDraggable});
| OCA/web/web_dialog_size/static/src/js/web_dialog_draggable.esm.js/0 | {
"file_path": "OCA/web/web_dialog_size/static/src/js/web_dialog_draggable.esm.js",
"repo_id": "OCA",
"token_count": 901
} | 69 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_disable_export_group
#
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_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 ""
| OCA/web/web_disable_export_group/i18n/web_disable_export_group.pot/0 | {
"file_path": "OCA/web/web_disable_export_group/i18n/web_disable_export_group.pot",
"repo_id": "OCA",
"token_count": 298
} | 70 |
/** @odoo-module **/
/* Copyright 2020 Tecnativa - João Marques
Copyright 2022 Tecnativa - Víctor Martínez
License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). */
import tour from "web_tour.tour";
tour.register(
"export_tour_xlsx_button_ok",
{
test: true,
url: "/web#model=ir.ui.view&view_type=list&cids=&action=base.action_ui_view",
},
[
{
content: "Check if 'Export all' button exists",
trigger: ".o_list_buttons:has(.o_list_export_xlsx)",
},
]
);
tour.register(
"export_tour_xlsx_button_ko",
{
test: true,
url: "/web#model=ir.ui.view&view_type=list&cids=&action=base.action_ui_view",
},
[
{
content: "Check if 'Export all' button exists",
trigger: ".o_list_buttons:not(:has(.o_list_export_xlsx))",
},
]
);
| OCA/web/web_disable_export_group/static/tests/web_disable_export_group_tour.esm.js/0 | {
"file_path": "OCA/web/web_disable_export_group/static/tests/web_disable_export_group_tour.esm.js",
"repo_id": "OCA",
"token_count": 437
} | 71 |
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import HttpCase, tagged
@tagged("-at_install", "post_install")
class TestQunit(HttpCase):
def test_qunit(self):
self.browser_js(
"/web/tests?module=web_domain_field&failfast",
"",
"",
login="admin",
)
| OCA/web/web_domain_field/tests/test_qunit.py/0 | {
"file_path": "OCA/web/web_domain_field/tests/test_qunit.py",
"repo_id": "OCA",
"token_count": 212
} | 72 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_environment_ribbon
#
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_environment_ribbon
#: model:ir.model,name:web_environment_ribbon.model_web_environment_ribbon_backend
msgid "Web Environment Ribbon Backend"
msgstr ""
| OCA/web/web_environment_ribbon/i18n/web_environment_ribbon.pot/0 | {
"file_path": "OCA/web/web_environment_ribbon/i18n/web_environment_ribbon.pot",
"repo_id": "OCA",
"token_count": 202
} | 73 |
============================
Web Numeric Field Formatting
============================
..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:38fdc63f7bc8de7646a14a287422f74484e8692bd69c1aa54e339fbc8508afef
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |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-LGPL--3-blue.png
:target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html
:alt: License: LGPL-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_field_numeric_formatting
: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_field_numeric_formatting
: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|
Having this module installed allows a developer to render a float or integer field
without a thousands separator using
.. code-block:: xml
<field name="id" options="{'enable_formatting': false}" />
Setting this option is supported for list and form views. In kanban views you
can simply use
.. code-block:: xml
<t t-esc="record.id.raw_value" />
The code in this module is a backport of
https://github.com/odoo/odoo/commit/592794b397ba7f6468e45a5cc3e93681b1ed8578
from Odoo 17, so this module should not be ported beyond version 16.
The new `enable_formatting` option in Odoo 17 replaces the `format` option in
Odoo 15.
**Table of contents**
.. contents::
:local:
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_field_numeric_formatting%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
~~~~~~~
* Opener B.V.
Contributors
~~~~~~~~~~~~
* Lucas Perais (lpe) <lpe@odoo.com> contributed the original code to Odoo.
* Stefan Rijnhart <stefan@opener.amsterdam> created the backport to Odoo 16
in this module.
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_field_numeric_formatting>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
| OCA/web/web_field_numeric_formatting/README.rst/0 | {
"file_path": "OCA/web/web_field_numeric_formatting/README.rst",
"repo_id": "OCA",
"token_count": 1227
} | 74 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_group_expand
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 14.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2021-02-17 10:45+0000\n"
"Last-Translator: claudiagn <claudia.gargallo@qubiq.es>\n"
"Language-Team: none\n"
"Language: ca\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.3.2\n"
#. module: web_group_expand
#. odoo-javascript
#: code:addons/web_group_expand/static/src/xml/list_controller.xml:0
#, python-format
msgid "Compress"
msgstr ""
#. module: web_group_expand
#. odoo-javascript
#: code:addons/web_group_expand/static/src/xml/list_controller.xml:0
#, python-format
msgid "Expand"
msgstr ""
#, python-format
#~ msgid "Collapse groups"
#~ msgstr "Col·lapsar grups"
#, python-format
#~ msgid "Expand groups"
#~ msgstr "Expandir grups"
| OCA/web/web_group_expand/i18n/ca.po/0 | {
"file_path": "OCA/web/web_group_expand/i18n/ca.po",
"repo_id": "OCA",
"token_count": 413
} | 75 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_help
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2023-09-02 20:35+0000\n"
"Last-Translator: Ivorra78 <informatica@totmaterial.es>\n"
"Language-Team: none\n"
"Language: es\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_help
#. odoo-javascript
#: code:addons/web_help/static/src/user_trip.esm.js:0
#, python-format
msgid "Cancel"
msgstr "Cancelar"
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/change_password_trip.esm.js:0
#, python-format
msgid "Change the password here, make sure it's secure."
msgstr "Cambie la contraseña aquí, asegúrese de que sea segura."
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/change_password_trip.esm.js:0
#, python-format
msgid "Click here to confirm it."
msgstr "Haga clic aquí para confirmarlo."
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/trip.esm.js:0
#, python-format
msgid "Close"
msgstr "Cerrar"
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/trip.esm.js:0
#, python-format
msgid "Finish"
msgstr "Finalizar"
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/trip.esm.js:0
#, python-format
msgid "Got it"
msgstr "Lo tengo"
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/user_trip.esm.js:0
#, python-format
msgid "Next"
msgstr "Siguiente"
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/user_trip.esm.js:0
#, python-format
msgid "To create a new user click here."
msgstr "Para crear un nuevo usuario haga clic aquí."
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/user_trip.esm.js:0
#, python-format
msgid "Use the searchbar to find specific users."
msgstr "Utiliza la barra de búsqueda para encontrar usuarios concretos."
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/user_trip.esm.js:0
#, python-format
msgid "You can switch to different views here."
msgstr "Aquí puede cambiar a diferentes vistas."
| OCA/web/web_help/i18n/es.po/0 | {
"file_path": "OCA/web/web_help/i18n/es.po",
"repo_id": "OCA",
"token_count": 927
} | 76 |
/** @odoo-module **/
import {Component, EventBus, useRef, useState} from "@odoo/owl";
import {registry} from "@web/core/registry";
export class Highlighter extends Component {
setup() {
this.state = useState({visible: false});
this.bus = this.props.bus;
this.bus.on("hide", this, () => this.hide());
this.bus.on("highlight", this, (options) => this.highlight(options));
this.highlightRef = useRef("highlightRef");
this.overlayRef = useRef("overlay");
}
hide() {
this.state.visible = false;
this.resetAnimation();
}
_getBoundsOfElement($el) {
const bounds = {
x: Number.MAX_SAFE_INTEGER,
y: Number.MAX_SAFE_INTEGER,
};
let xEnd = 0,
yEnd = 0;
$el.filter(":visible").each(function () {
const elementBounds = this.getBoundingClientRect();
if (elementBounds.x < bounds.x) {
bounds.x = elementBounds.x;
}
if (elementBounds.y < bounds.y) {
bounds.y = elementBounds.y;
}
if (xEnd < elementBounds.x + elementBounds.width) {
xEnd = elementBounds.x + elementBounds.width;
}
if (yEnd < elementBounds.y + elementBounds.height) {
yEnd = elementBounds.y + elementBounds.height;
}
});
bounds.width = xEnd - bounds.x;
bounds.height = yEnd - bounds.y;
return bounds;
}
highlight({selector, content, animate = 250, padding = 10}) {
const selection = $(selector);
if (!selection.length) {
return console.error("Element not found.", selector);
}
const bounds = this._getBoundsOfElement(selection);
this.state.visible = true;
this.animate(content, bounds, animate, padding);
}
animate(content, bounds, animate = 250, padding = 10) {
const $el = $(this.highlightRef.el);
$el.popover("dispose");
$el.animate(
{
top: _.str.sprintf("%spx", Math.floor(bounds.y) - padding),
left: _.str.sprintf("%spx", Math.floor(bounds.x) - padding),
width: _.str.sprintf("%spx", Math.floor(bounds.width) + padding * 2),
height: _.str.sprintf("%spx", Math.floor(bounds.height) + padding * 2),
},
animate ? animate : 0,
function () {
$el.popover(
_.extend(this._getPopoverOptions(), {
content: content,
})
).popover("show");
}.bind(this)
);
}
_getPopoverOptions() {
return {
container: $(this.overlayRef.el),
placement: "auto",
html: true,
trigger: "manual",
boundary: "viewport",
sanitize: false,
template:
'<div class="popover" role="tooltip"><div class="popover-body"></div></div>',
};
}
resetAnimation() {
const $el = $(this.highlightRef.el);
$el.popover("dispose");
$el.css({
top: 0,
left: 0,
width: 0,
height: 0,
});
}
}
Highlighter.template = "web_help.Highlighter";
export const highlighterService = {
start() {
const bus = new EventBus();
registry.category("main_components").add("Highlighter", {
Component: Highlighter,
props: {bus},
});
return {
hide: () => bus.trigger("hide"),
highlight: (selector, content, animate = 250, padding = 10) =>
bus.trigger("highlight", {
selector: selector,
content: content,
animate: animate,
padding: padding,
}),
};
},
};
registry.category("services").add("highlighter", highlighterService);
| OCA/web/web_help/static/src/components/highlighter/highlighter.esm.js/0 | {
"file_path": "OCA/web/web_help/static/src/components/highlighter/highlighter.esm.js",
"repo_id": "OCA",
"token_count": 2032
} | 77 |
(function () {
"use strict";
// Those are weak because we don't want to prevent
// GC of the dom nodes when we leave a page
const elementStyleMap = new WeakMap();
const alreadyRemove = new WeakSet();
function changeStyle(nodes) {
nodes.forEach((el) => {
if (el.style.display === "none") {
el.style.display = elementStyleMap.get(el) || "block";
} else {
elementStyleMap.set(el, el.style.display);
el.style.display = "none";
}
if (el.tagName === "TD") {
const cellIndex = el.cellIndex;
const tableHead = el.parentNode.parentNode.previousSibling;
const header = tableHead.querySelectorAll("th")[cellIndex];
header.style.display = el.style.display;
}
});
}
// Unfortunately we cannot trust the css because we need
// to store the base display style to restore it properly
function rafCallback() {
// Query only nodes that we did not already defaulted to none
const filteredNodes = Array.from(
document.querySelectorAll(".web-hide-field")
).filter((e) => !alreadyRemove.has(e));
// Add the filtered node to the weakset to avoid removing them multiple times
filteredNodes.forEach((e) => alreadyRemove.add(e));
if (filteredNodes.length > 0) {
changeStyle(filteredNodes);
}
requestAnimationFrame(rafCallback);
}
rafCallback();
document.addEventListener("keypress", function (event) {
if (event.key === "p") {
changeStyle(document.querySelectorAll(".web-hide-field"));
}
});
})();
| OCA/web/web_hide_field_with_key/static/src/js/hide_custom_hidden_fields.js/0 | {
"file_path": "OCA/web/web_hide_field_with_key/static/src/js/hide_custom_hidden_fields.js",
"repo_id": "OCA",
"token_count": 743
} | 78 |
/** @odoo-module **/
import {registry} from "@web/core/registry";
/**
* Handle 'ir.actions.act_multi' action
* @param {object} action see _handleAction() parameters
* @returns {$.Promise}
*/
async function executeMultiAction({env, action}) {
return action.actions
.map((item) => {
return () => {
return env.services.action.doAction(item);
};
})
.reduce((prev, cur) => {
return prev.then(cur);
}, Promise.resolve());
}
registry.category("action_handlers").add("ir.actions.act_multi", executeMultiAction);
| OCA/web/web_ir_actions_act_multi/static/src/js/web_ir_actions_act_multi.esm.js/0 | {
"file_path": "OCA/web/web_ir_actions_act_multi/static/src/js/web_ir_actions_act_multi.esm.js",
"repo_id": "OCA",
"token_count": 249
} | 79 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_ir_actions_act_window_message
#
# Translators:
# Dorin Hongu <dhongu@gmail.com>, 2017
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 10.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-01-03 03:50+0000\n"
"PO-Revision-Date: 2018-01-03 03:50+0000\n"
"Last-Translator: Dorin Hongu <dhongu@gmail.com>, 2017\n"
"Language-Team: Romanian (https://www.transifex.com/oca/teams/23907/ro/)\n"
"Language: ro\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?"
"2:1));\n"
#. module: web_ir_actions_act_window_message
#. openerp-web
#: code:addons/web_ir_actions_act_window_message/static/src/js/web_ir_actions_act_window_message.js:0
#, python-format
msgid "Close"
msgstr "Închide"
| OCA/web/web_ir_actions_act_window_message/i18n/ro.po/0 | {
"file_path": "OCA/web/web_ir_actions_act_window_message/i18n/ro.po",
"repo_id": "OCA",
"token_count": 392
} | 80 |
# © 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
| OCA/web/web_listview_range_select/__init__.py/0 | {
"file_path": "OCA/web/web_listview_range_select/__init__.py",
"repo_id": "OCA",
"token_count": 46
} | 81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.